Algorithm Search⌘K

Algorithmadvanced

Fisher vector

Also called Fisher vector image representation.

Represent an image by the gradient of the log-likelihood of its descriptors under a Gaussian mixture with respect to the means and variances, whitened and normalized.

Time
O(n K D) worst · best
Space
O(K D) extra
Where
D = the descriptor dimension; K = the number of mixture components; n = the number of local descriptors of the image
Properties
deterministicexactorder invariant
Origin
Tommi Jaakkola, David Haussler, Florent Perronnin, Christopher Dance, Jorge Sanchez, Thomas Mensink, 2007

The Fisher vector describes the set of local descriptors of an image by how the parameters of a fixed Gaussian mixture model would have to change to fit that set better. It is the gradient of the average log-likelihood of the descriptors with respect to the means and the standard deviations of the mixture, scaled by the inverse square root of the Fisher information, then power and L2 normalized. With KK components in dimension DD, it has 2KD2 K D values. Compared with VLAD, it uses soft assignments and also keeps second order statistics; compared with the bag of visual words, which only counts, it keeps the first and second moments of the descriptors per component.

In plain words

First, learn a model of what local patches look like in general: a mixture of a few dozen or a few hundred bell-shaped clouds. Then, for a new image, ask: if I wanted this general model to describe the patches of this image better, how should I move each cloud, and how should I make it wider or narrower?

The answer is a list of small pushes, one for each cloud and each descriptor coordinate. Two images that need the same pushes have similar content. The pushes are scaled so that each one counts the same on average, and large values are damped so that one repeated pattern cannot dominate. A linear classifier on this vector works about as well as much slower nonlinear methods on simpler image signatures.

The problem

Input. A diagonal Gaussian mixture uu with KK components: weights wk>0w_k > 0 with ∑kwk=1\sum_k w_k = 1, means μk∈RD\mu_k \in \mathbb{R}^D and standard deviations σk∈R>0D\sigma_k \in \mathbb{R}^D_{>0}. It is learned once, usually by expectation maximization on training descriptors. Also the nn local descriptors X={x1,…,xn}X = \{x_1, \ldots, x_n\} of one image, and the power ρ∈(0,1]\rho \in (0, 1] (usually 1/21/2).

Output. A vector z∈R2KDz \in \mathbb{R}^{2KD} (or R(2D+1)K\mathbb{R}^{(2D+1)K} with the weight part). The Fisher score of the image is ∇λ1n∑tlog⁡u(xt)\nabla_\lambda \frac1n \sum_t \log u(x_t), the gradient with respect to the parameters λ\lambda; see score function. The Fisher kernel of Jaakkola and Haussler compares two images by GX⊤F−1GYG_X^\top F^{-1} G_Y, where FF is the Fisher information of uu. Writing F−1=L⊤LF^{-1} = L^\top L, the Fisher vector is GX=L GX\mathcal{G}_X = L\, G_X, so the kernel becomes a plain inner product (Sanchez et al. 2013, Section 2.1). With the posterior γt(k)=wkN(xt;μk,σk)/∑jwjN(xt;μj,σj)\gamma_t(k) = w_k \mathcal{N}(x_t; \mu_k, \sigma_k) / \sum_j w_j \mathcal{N}(x_t; \mu_j, \sigma_j), and all operations on vectors taken per coordinate, the entries are (Sanchez et al., Eq. 16 to 18, divided by nn)

Gαk=1nwk∑t=1n(γt(k)−wk),Gμk=1nwk∑t=1nγt(k)xt−μkσk,Gσk=1n2wk∑t=1nγt(k)[(xt−μk)2σk2−1].\mathcal{G}_{\alpha_k} = \frac{1}{n\sqrt{w_k}} \sum_{t=1}^{n} (\gamma_t(k) - w_k), \quad \mathcal{G}_{\mu_k} = \frac{1}{n\sqrt{w_k}} \sum_{t=1}^{n} \gamma_t(k) \frac{x_t - \mu_k}{\sigma_k}, \quad \mathcal{G}_{\sigma_k} = \frac{1}{n\sqrt{2 w_k}} \sum_{t=1}^{n} \gamma_t(k) \Big[ \frac{(x_t - \mu_k)^2}{\sigma_k^2} - 1 \Big].

Here α\alpha are the soft-max parameters with w=softmax(α)w = \mathrm{softmax}(\alpha). The weight part is often left out, as in Perronnin et al. (2010), since it adds only KK values.

The algorithm

  1. FISHER-VECTOR(X, w, mu, sigma, rho) ▷ n = |X|, K components, dimension D
  2. 1S0_k ← 0, S1_k ← 0 in R^D, S2_k ← 0 in R^D for k = 1..K
  3. 2for each descriptor x_t in X do
  4. 3gamma_t(k) ← w_k N(x_t; mu_k, sigma_k) / sum_j w_j N(x_t; mu_j, sigma_j) for all k
  5. 4for each k, with r = (x_t - mu_k) / sigma_k: S0_k += gamma_t(k); S1_k += gamma_t(k) r; S2_k += gamma_t(k) (r^2 - 1)
  6. 5G_alpha_k ← (S0_k - n w_k) / (n sqrt(w_k)) ▷ optional weight part
  7. 6G_mu_k ← S1_k / (n sqrt(w_k))
  8. 7G_sigma_k ← S2_k / (n sqrt(2 w_k))
  9. 8z ← the concatenation of (G_mu_k, G_sigma_k) for k = 1..K
  10. 9z_i ← sign(z_i) |z_i|^rho for each i
  11. 10if z ≠ 0 then z ← z / ||z||
  12. 11return z

Line L3 is computed in the log domain with the log-sum-exp trick. A descriptor far from every component makes all densities underflow to 0 in floating point, and a direct division then gives 0/0. Lines L1 to L4 collect the statistics S0S_0, S1S_1 and S2S_2 of Sanchez et al. (Eq. 20 to 22, in a centered form), and lines L5 to L7 turn them into the normalized gradient. Lines L9 and L10 are the improvements of Perronnin et al. (2010). This is Algorithm 1 of Sanchez et al.

Example

Take D=1D = 1, K=2K = 2, w=(0.5,0.5)w = (0.5, 0.5), μ=(−1,1)\mu = (-1, 1), σ=(1,1)\sigma = (1, 1), and n=3n = 3 descriptors 00, 11, 22. The log ratio of the two components at xx is ((x+1)2−(x−1)2)/2=2x((x+1)^2 - (x-1)^2)/2 = 2x, so γ(2)=1/(1+e−2x)\gamma(2) = 1/(1 + e^{-2x}).

xtx_t γt(1)\gamma_t(1) γt(2)\gamma_t(2) zz for comp. 1 zz for comp. 2
0 0.5 0.5 1 −1-1
1 0.119203 0.880797 2 0
2 0.017986 0.982014 3 1

Here z=(xt−μk)/σkz = (x_t - \mu_k)/\sigma_k. The statistics are S0=(0.637189,2.362811)S_0 = (0.637189, 2.362811), S1=(0.5+2⋅0.119203+3⋅0.017986, −0.5+0.982014)=(0.792364,0.482014)S_1 = (0.5 + 2 \cdot 0.119203 + 3 \cdot 0.017986,\ -0.5 + 0.982014) = (0.792364, 0.482014) and S2=(3⋅0.119203+8⋅0.017986, −0.880797)=(0.501497,−0.880797)S_2 = (3 \cdot 0.119203 + 8 \cdot 0.017986,\ -0.880797) = (0.501497, -0.880797). With nwk=2.1213n \sqrt{w_k} = 2.1213 and n2wk=3n \sqrt{2 w_k} = 3, lines L5 to L7 give

Gα=(−0.4067,0.4067),Gμ=(0.3735,0.2272),Gσ=(0.1672,−0.2936).\mathcal{G}_\alpha = (-0.4067, 0.4067), \quad \mathcal{G}_\mu = (0.3735, 0.2272), \quad \mathcal{G}_\sigma = (0.1672, -0.2936).

The weight part sums to zero, as it must, since ∑k(γt(k)−wk)=0\sum_k (\gamma_t(k) - w_k) = 0 and the weights are equal. The 4 values of the means and sigmas, in the order (μ1,σ1,μ2,σ2)(\mu_1, \sigma_1, \mu_2, \sigma_2), are (0.3735,0.1672,0.2272,−0.2936)(0.3735, 0.1672, 0.2272, -0.2936). After the signed square root and L2 normalization they become (0.5932,0.3968,0.4627,−0.5259)(0.5932, 0.3968, 0.4627, -0.5259). The negative Gσ2\mathcal{G}_{\sigma_2} says that the descriptors near component 2 are less spread than the model expects: two of them sit at distance 0 and 1 from its mean.

Correctness

The proof in the correctness file first derives the gradients of log⁡u\log u with respect to αk\alpha_k, μk\mu_k and σk\sigma_k; the tests check them against finite differences. Then it computes the Fisher information under the assumption of Sanchez et al. (Appendix A) that each descriptor comes from one component with a posterior of 0 or 1 (well separated components). Under this assumption, the blocks for the means and the standard deviations are diagonal, with entries wk/σk,i2w_k / \sigma_{k,i}^2 and 2wk/σk,i22 w_k / \sigma_{k,i}^2, so F−1/2F^{-1/2} multiplies the gradients by σk,i/wk\sigma_{k,i}/\sqrt{w_k} and σk,i/2wk\sigma_{k,i}/\sqrt{2 w_k}. This is exactly lines L6 and L7. It also shows that each normalized entry for one descriptor has mean 0 and variance 1 under the model. For the weights, the block is diag(w)−ww⊤\mathrm{diag}(w) - w w^\top, which is singular; the factor 1/wk1/\sqrt{w_k} of line L5 is its diagonal approximation without the ww⊤w w^\top term, and the variance of a normalized weight entry is 1−wk1 - w_k, not 1. When the components overlap, the diagonal form is an approximation, so the whitening is approximate. The code computes the definition exactly up to floating point.

Proof: The Fisher vector lines compute the log-likelihood gradient whitened by the exact Fisher information of the hard-assignment modelfull

We use the notation of the page. The mixture density is u(x)=∑k=1Kwk N(x;μk,σk)u(x) = \sum_{k=1}^{K} w_k\, \mathcal{N}(x; \mu_k, \sigma_k) on RD\mathbb{R}^D with diagonal covariances, where

log⁡N(x;μk,σk)=−12∑i=1D[log⁡(2π)+2log⁡σk,i+(xi−μk,i)2σk,i2].\log \mathcal{N}(x; \mu_k, \sigma_k) = -\frac12 \sum_{i=1}^{D} \Big[ \log(2\pi) + 2 \log \sigma_{k,i} + \frac{(x_i - \mu_{k,i})^2}{\sigma_{k,i}^2} \Big].

The weights are wk=eαk/∑jeαjw_k = e^{\alpha_k} / \sum_j e^{\alpha_j}. The posterior is γx(k)=wkN(x;μk,σk)/u(x)\gamma_x(k) = w_k \mathcal{N}(x; \mu_k, \sigma_k)/u(x), so ∑kγx(k)=1\sum_k \gamma_x(k) = 1. We write rk,i(x)=(xi−μk,i)/σk,ir_{k,i}(x) = (x_i - \mu_{k,i})/\sigma_{k,i}.

Part 1: the gradients

Lemma 1. For one descriptor xx,

∂log⁡u(x)∂αk=γx(k)−wk,∂log⁡u(x)∂μk,i=γx(k)rk,i(x)σk,i,∂log⁡u(x)∂σk,i=γx(k)rk,i(x)2−1σk,i.\frac{\partial \log u(x)}{\partial \alpha_k} = \gamma_x(k) - w_k, \qquad \frac{\partial \log u(x)}{\partial \mu_{k,i}} = \gamma_x(k) \frac{r_{k,i}(x)}{\sigma_{k,i}}, \qquad \frac{\partial \log u(x)}{\partial \sigma_{k,i}} = \gamma_x(k) \frac{r_{k,i}(x)^2 - 1}{\sigma_{k,i}}.

Proof. Let pk=N(x;μk,σk)p_k = \mathcal{N}(x; \mu_k, \sigma_k). For a parameter θ\theta of component kk only, ∂θlog⁡u=wk∂θpku=wkpku∂θlog⁡pk=γx(k) ∂θlog⁡pk\partial_\theta \log u = \frac{w_k \partial_\theta p_k}{u} = \frac{w_k p_k}{u} \partial_\theta \log p_k = \gamma_x(k)\, \partial_\theta \log p_k. From the formula for log⁡pk\log p_k, ∂log⁡pk/∂μk,i=(xi−μk,i)/σk,i2=rk,i/σk,i\partial \log p_k / \partial \mu_{k,i} = (x_i - \mu_{k,i})/\sigma_{k,i}^2 = r_{k,i}/\sigma_{k,i} and ∂log⁡pk/∂σk,i=−1/σk,i+(xi−μk,i)2/σk,i3=(rk,i2−1)/σk,i\partial \log p_k / \partial \sigma_{k,i} = -1/\sigma_{k,i} + (x_i - \mu_{k,i})^2/\sigma_{k,i}^3 = (r_{k,i}^2 - 1)/\sigma_{k,i}. For the weights, ∂wj/∂αk=wj(δjk−wk)\partial w_j / \partial \alpha_k = w_j(\delta_{jk} - w_k), so ∂αklog⁡u=1u∑jpjwj(δjk−wk)=γx(k)−wk∑jγx(j)=γx(k)−wk\partial_{\alpha_k} \log u = \frac{1}{u} \sum_j p_j w_j (\delta_{jk} - w_k) = \gamma_x(k) - w_k \sum_j \gamma_x(j) = \gamma_x(k) - w_k. □\square

These are the formulas of Sanchez et al. (2013, Section 2.2). The gradient of the average 1n∑tlog⁡u(xt)\frac1n \sum_t \log u(x_t) is the average of these terms.

Lemma 2 (the loop). After lines L1 to L4, S0,k=∑tγt(k)S_{0,k} = \sum_t \gamma_t(k), S1,k,i=∑tγt(k)rk,i(xt)S_{1,k,i} = \sum_t \gamma_t(k) r_{k,i}(x_t) and S2,k,i=∑tγt(k)(rk,i(xt)2−1)S_{2,k,i} = \sum_t \gamma_t(k) (r_{k,i}(x_t)^2 - 1).

Proof. Line L1 sets the sums to 0, and each pass of the loop adds the term of one descriptor, computed in line L3 and line L4 from the definitions. By induction over the passes the sums hold the stated values. □\square

Corollary 1. Lines L5 to L7 give

Gαk=1wk⋅1n∑t∂log⁡u(xt)∂αk,Gμk,i=σk,iwk⋅1n∑t∂log⁡u(xt)∂μk,i,Gσk,i=σk,i2wk⋅1n∑t∂log⁡u(xt)∂σk,i.\mathcal{G}_{\alpha_k} = \frac{1}{\sqrt{w_k}} \cdot \frac1n \sum_t \frac{\partial \log u(x_t)}{\partial \alpha_k}, \quad \mathcal{G}_{\mu_{k,i}} = \frac{\sigma_{k,i}}{\sqrt{w_k}} \cdot \frac1n \sum_t \frac{\partial \log u(x_t)}{\partial \mu_{k,i}}, \quad \mathcal{G}_{\sigma_{k,i}} = \frac{\sigma_{k,i}}{\sqrt{2 w_k}} \cdot \frac1n \sum_t \frac{\partial \log u(x_t)}{\partial \sigma_{k,i}}.

Proof. By Lemma 2, S0,k−nwk=∑t(γt(k)−wk)S_{0,k} - n w_k = \sum_t (\gamma_t(k) - w_k), S1,k,i=σk,i∑tγt(k)rk,i/σk,iS_{1,k,i} = \sigma_{k,i} \sum_t \gamma_t(k) r_{k,i}/\sigma_{k,i} and S2,k,i=σk,i∑tγt(k)(rk,i2−1)/σk,iS_{2,k,i} = \sigma_{k,i} \sum_t \gamma_t(k)(r_{k,i}^2 - 1)/\sigma_{k,i}. Compare with Lemma 1 and divide by the factors of lines L5 to L7. □\square

So the vector is the average gradient with each coordinate multiplied by a positive factor. Part 2 shows that these factors are the inverse square roots of the Fisher information under the stated assumption.

Part 2: the Fisher information under hard assignment

The Fisher information is F=Ex∼u[g(x)g(x)⊤]F = \mathbb{E}_{x \sim u}[g(x) g(x)^\top], with g=∇λlog⁡ug = \nabla_\lambda \log u. It is hard to compute exactly for a mixture. Sanchez et al. (Appendix A) assume that the posterior of each xx drawn from uu is sharply peaked. We state this as an exact assumption.

Assumption H. Let cc be the component that generated xx (so Pr⁡[c=k]=wk\Pr[c = k] = w_k and x∣c=k∼N(μk,σk)x \mid c = k \sim \mathcal{N}(\mu_k, \sigma_k)). Then γx(k)=[c=k]\gamma_x(k) = [c = k] for all kk, with probability 1.

This holds in the limit of components whose means move apart while the variances stay fixed. It is also exactly the Fisher information of the complete-data model in which the component label is observed.

Theorem 1. Under Assumption H, the Fisher information FF in the parameters (α,μ,σ)(\alpha, \mu, \sigma) is block diagonal with

  1. E[gμk,i2]=wk/σk,i2\mathbb{E}[g_{\mu_{k,i}}^2] = w_k / \sigma_{k,i}^2,
  2. E[gσk,i2]=2wk/σk,i2\mathbb{E}[g_{\sigma_{k,i}}^2] = 2 w_k / \sigma_{k,i}^2,
  3. the block of α\alpha equal to diag(w)−ww⊤\mathrm{diag}(w) - w w^\top, and every other entry 0.

Proof. Under H, gμk,i=[c=k] rk,i/σk,ig_{\mu_{k,i}} = [c = k]\, r_{k,i}/\sigma_{k,i} and gσk,i=[c=k](rk,i2−1)/σk,ig_{\sigma_{k,i}} = [c = k] (r_{k,i}^2 - 1)/\sigma_{k,i}. Given c=kc = k, the variables rk,1,…,rk,Dr_{k,1}, \ldots, r_{k,D} are independent standard normal, so E[r]=0\mathbb{E}[r] = 0, E[r2]=1\mathbb{E}[r^2] = 1, E[r3]=0\mathbb{E}[r^3] = 0 and E[r4]=3\mathbb{E}[r^4] = 3.

Item 1: E[gμk,i2]=wkE[r2]/σk,i2=wk/σk,i2\mathbb{E}[g_{\mu_{k,i}}^2] = w_k \mathbb{E}[r^2]/\sigma_{k,i}^2 = w_k/\sigma_{k,i}^2. Item 2: E[(r2−1)2]=E[r4]−2E[r2]+1=2\mathbb{E}[(r^2 - 1)^2] = \mathbb{E}[r^4] - 2\mathbb{E}[r^2] + 1 = 2, so E[gσk,i2]=2wk/σk,i2\mathbb{E}[g_{\sigma_{k,i}}^2] = 2 w_k / \sigma_{k,i}^2. Item 3: gα=ec−wg_\alpha = e_c - w, where ece_c is the one-hot vector of cc, so E[gαgα⊤]=Cov(ec)=diag(w)−ww⊤\mathbb{E}[g_\alpha g_\alpha^\top] = \mathrm{Cov}(e_c) = \mathrm{diag}(w) - w w^\top.

Off-diagonal entries. A product of a term of component kk and a term of component j≠kj \ne k contains [c=k][c=j]=0[c = k][c = j] = 0. Inside one component, for i≠li \ne l: E[rirl]=0\mathbb{E}[r_i r_l] = 0, E[ri(rl2−1)]=0\mathbb{E}[r_i (r_l^2 - 1)] = 0 and E[(ri2−1)(rl2−1)]=0\mathbb{E}[(r_i^2 - 1)(r_l^2 - 1)] = 0 by independence, and for the same ii: E[r(r2−1)]=E[r3]−E[r]=0\mathbb{E}[r (r^2 - 1)] = \mathbb{E}[r^3] - \mathbb{E}[r] = 0. Between α\alpha and the component terms: E[([c=j]−wj)[c=k] r]=E[([c=j]−wj)[c=k]] E[r∣c=k]=0\mathbb{E}[([c = j] - w_j)[c = k]\, r] = \mathbb{E}[([c=j] - w_j)[c=k]]\, \mathbb{E}[r \mid c = k] = 0, and in the same way with r2−1r^2 - 1, whose conditional mean is 0. □\square

Corollary 2 (the normalizers). Under Assumption H, the mean and sigma part of F−1/21n∑tg(xt)F^{-1/2} \frac1n \sum_t g(x_t) is exactly what lines L6 and L7 compute: the factors σk,i/wk\sigma_{k,i}/\sqrt{w_k} and σk,i/2wk\sigma_{k,i}/\sqrt{2 w_k} are (wk/σk,i2)−1/2(w_k/\sigma_{k,i}^2)^{-1/2} and (2wk/σk,i2)−1/2(2 w_k / \sigma_{k,i}^2)^{-1/2}. For a single descriptor (n=1n = 1) each of these normalized entries has mean 0 and variance 1 under uu.

Proof. The inverse square root of a positive diagonal block is the diagonal of the inverse square roots; Corollary 1 gives the factors. For the moments: E[g]=0\mathbb{E}[g] = 0 because each component term has a factor rr or r2−1r^2 - 1 with conditional mean 0, and the variance is the diagonal entry times the square of the factor, which is 1. □\square

The weight part. The block diag(w)−ww⊤\mathrm{diag}(w) - w w^\top has the null vector (1,…,1)(1, \ldots, 1), because the soft-max parameters are defined only up to a common shift. It has no inverse. Line L5 uses 1/wk1/\sqrt{w_k}, the inverse square root of the diagonal diag(w)\mathrm{diag}(w) alone, as Sanchez et al. do (Eq. 16). With this factor a normalized weight entry of one descriptor has variance (wk−wk2)/wk=1−wk(w_k - w_k^2)/w_k = 1 - w_k, not 1. The tests check this value.

Without Assumption H. When components overlap, γx(k)\gamma_x(k) is strictly between 0 and 1, and the entries of Theorem 1 change; the off-diagonal entries are no longer 0. Then lines L5 to L7 are the diagonal approximation of Sanchez et al., not the exact whitening. Lemma 1, Lemma 2 and Corollary 1 hold without the assumption.

Part 3: the normalization steps

Line L9 maps each entry tt to sign(t)∣t∣ρ\mathrm{sign}(t)|t|^\rho, which is zero exactly when t=0t = 0 and keeps the sign. Line L10 divides a nonzero vector by its norm, so the output has norm 1 or is zero. The result is a function of the multiset XX only, since every statistic of Lemma 2 is a sum over XX.

What is not claimed. That the Fisher vector classifies or ranks images well is a benchmark result, not a consequence of these facts.

Complexity

In the real RAM, line L3 costs O(KD)O(K D) per descriptor (one diagonal Gaussian density per component), and line L4 costs O(KD)O(K D). So lines L2 to L4 cost O(nKD)O(n K D), and lines L5 to L11 cost O(KD)O(K D). Extra space is O(KD)O(K D) for the statistics and the output. The exp⁡\exp and log⁡\log calls are counted as one operation each. In practice many posteriors are below a small threshold and are skipped, which saves time but changes the result slightly.

For example, K=256K = 256 and SIFT reduced to D=64D = 64 by principal component analysis give a vector with 2⋅256⋅64=32,7682 \cdot 256 \cdot 64 = 32{,}768 values. The PCA step also decorrelates the coordinates, which makes the diagonal covariance model fit better.

Properties

  • Order invariant. The statistics are sums over descriptors.
  • Generalizes the bag of words and VLAD. The weight part is a centered, scaled soft histogram of words. With hard posteriors, equal weights and unit variances, the mean part is (K/n)(\sqrt{K}/n) times VLAD (Sanchez et al., Section 2.5). The tests check this identity.
  • Zero for a typical image. If the descriptors of an image follow uu exactly, the expected score is zero. An image differs from the model through its nonzero entries.
  • A kernel. Without the power step, the inner product of two Fisher vectors is a sum over pairs of descriptors, as for VLAD, so it is a positive semidefinite match kernel (Sanchez et al., Eq. 38).
  • Dense and high-dimensional. Most entries are nonzero, which makes storage large. Sanchez et al. compress the vectors with product quantization for large data sets.
  • Depends on the mixture. The vector is defined only for one fixed uu. Vectors from different mixtures cannot be compared.

Variants and improvements

  • Power normalization (line L9, ρ=1/2\rho = 1/2). It reduces the effect of bursty descriptors and of the sparsity that comes with large KK. Sanchez et al. relate it to the Hellinger kernel.
  • L2 normalization (line L10). Perronnin et al. (2010) motivate it as removing the part of the score that depends on the amount of image-specific background. It is a heuristic with that motivation, not a theorem.
  • Spatial pyramid. One Fisher vector per cell of a grid, concatenated, as in spatial pyramid matching.
  • Weight gradient. Including line L5 gives (2D+1)K(2D + 1) K values. Its benefit is small.
  • Full or exact Fisher information. Using the exact FF instead of the diagonal approximation is possible but costs much more and is rare.
  • VLAD. The simplified version with hard assignment and the mean part only is VLAD.

When to use it

Use the Fisher vector when you need a fixed-length image signature that works well with a linear classifier, for example a linear support vector machine. The linear classifier then costs O(2KD)O(2KD) per image, while a nonlinear kernel on a bag of words costs much more at scale. For retrieval it is a strong alternative to VLAD at a higher cost. On most recognition benchmarks, features from convolutional networks later did better, and the Fisher vector is now used mostly on top of such features or as a baseline.

Pitfalls

  • Variance, not standard deviation. Some texts take the gradient with respect to σ2\sigma^2. The normalized vector is the same up to a constant per entry only if the Fisher normalization is also redone for that parameter. Mixing the two gives wrong scales.
  • Underflow in line L3. Compute the posteriors in the log domain.
  • Forgetting 1/n1/n. Without it, images with more descriptors get larger vectors before L2 normalization, and the power step then acts differently on them.
  • A mixture with tiny σ\sigma. EM can produce components with very small variance on a few training points. Their entries then explode. Put a floor on the variances during training.
  • Using full covariances. The formulas of this page are for diagonal covariances. Decorrelate the descriptors with PCA first, or the model fits poorly.
  • Power step on a vector that is then compared with another kernel. After line L9 the inner product is no longer a sum over pairs of descriptors.

Implementations

The Python code computes the posteriors with log-sum-exp, the statistics, the normalized gradient with an optional weight part and an optional hard assignment, the signed power and the L2 normalization. A separate function gives the unnormalized gradients and the log-likelihood. The tests check the example of this page, the gradients against central finite differences, the scaling of the gradients by the diagonal Fisher factors, a Monte Carlo check that the normalized entries have mean 0 and variance 1 (and 1−wk1 - w_k for the weights) on well separated components, the identity with scaled VLAD under hard assignment, and order invariance.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

fisher_vector.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fisher-vector/. The authors are listed in prov/WR6YRW.jsonl.
"""The Fisher vector of a set of local descriptors under a diagonal Gaussian mixture.

The mixture has K components with weights w[k] (positive, sum 1), means
mu[k] and standard deviations sigma[k] (lists of D floats, all positive).
For descriptors x_1..x_T the Fisher vector is the gradient of the average
log-likelihood with respect to the means and the standard deviations (and,
as an option, the soft-max weight parameters), each component scaled by the
diagonal approximation of the inverse square root of the Fisher information,
as in Sanchez, Perronnin, Mensink and Verbeek (IJCV 2013, Eq. 16 to 19).
Then the signed power rho and an L2 normalization are applied.
Layout of the output: for each k, the D mean entries, then the D sigma
entries; with include_weights=True the K weight entries come first.
Standard library only. Cost: O(T K D) time and O(K D) extra space.
"""

import math

LOG_2PI = math.log(2.0 * math.pi)


def log_gauss(x, mean, std):
    """Log density of a diagonal Gaussian at x."""
    s = 0.0
    for xi, mi, si in zip(x, mean, std):
        z = (xi - mi) / si
        s += LOG_2PI + 2.0 * math.log(si) + z * z
    return -0.5 * s


def log_mixture_terms(x, w, mu, sigma):
    """The K values log(w_k) + log N(x; mu_k, sigma_k)."""
    return [math.log(w[k]) + log_gauss(x, mu[k], sigma[k]) for k in range(len(w))]


def log_sum_exp(values):
    m = max(values)
    return m + math.log(sum(math.exp(v - m) for v in values))


def posteriors(x, w, mu, sigma, hard=False):
    """Soft assignments gamma(k) of x; with hard=True, a one-hot vector at the largest one."""
    a = log_mixture_terms(x, w, mu, sigma)
    if hard:
        k = max(range(len(a)), key=lambda j: (a[j], -j))
        return [1.0 if j == k else 0.0 for j in range(len(a))]
    m = log_sum_exp(a)
    return [math.exp(v - m) for v in a]


def log_likelihood(xs, w, mu, sigma):
    """The sum over the descriptors of log u(x), u the mixture density."""
    return sum(log_sum_exp(log_mixture_terms(x, w, mu, sigma)) for x in xs)


def raw_gradients(xs, w, mu, sigma):
    """Unnormalized gradients of log_likelihood (Sanchez et al. 2013, Section 2.2).

    Returns (g_alpha, g_mu, g_sigma): the gradient with respect to the soft-max
    parameters alpha (w = softmax(alpha)), the means and the standard deviations.
    """
    K, D = len(w), len(mu[0])
    g_alpha = [0.0] * K
    g_mu = [[0.0] * D for _ in range(K)]
    g_sigma = [[0.0] * D for _ in range(K)]
    for x in xs:
        gam = posteriors(x, w, mu, sigma)
        for k in range(K):
            g_alpha[k] += gam[k] - w[k]
            for i in range(D):
                d = x[i] - mu[k][i]
                s = sigma[k][i]
                g_mu[k][i] += gam[k] * d / (s * s)
                g_sigma[k][i] += gam[k] * (d * d / (s * s * s) - 1.0 / s)
    return g_alpha, g_mu, g_sigma


def fisher_vector(xs, w, mu, sigma, rho=0.5, normalize=True, include_weights=False, hard=False):
    """The Fisher vector of the descriptors xs (a flat list).

    rho = 1 and normalize = False give the plain normalized gradient. With
    hard = True the posteriors are replaced by a one-hot assignment.
    """
    K, D, T = len(w), len(mu[0]), len(xs)
    S0 = [0.0] * K  # @line L1
    S1 = [[0.0] * D for _ in range(K)]
    S2 = [[0.0] * D for _ in range(K)]
    for x in xs:  # @line L2
        gam = posteriors(x, w, mu, sigma, hard)  # @line L3
        for k in range(K):  # @line L4
            g = gam[k]
            if g == 0.0:
                continue
            S0[k] += g
            for i in range(D):
                z = (x[i] - mu[k][i]) / sigma[k][i]
                S1[k][i] += g * z
                S2[k][i] += g * (z * z - 1.0)
    if T == 0:
        out = [0.0] * ((K if include_weights else 0) + 2 * K * D)
        return out
    out = []
    if include_weights:
        out.extend((S0[k] - T * w[k]) / (T * math.sqrt(w[k])) for k in range(K))  # @line L5
    for k in range(K):
        out.extend(S1[k][i] / (T * math.sqrt(w[k])) for i in range(D))  # @line L6
        out.extend(S2[k][i] / (T * math.sqrt(2.0 * w[k])) for i in range(D))  # @line L7
    out = [float(t) for t in out]  # @line L8
    if rho != 1.0:  # @line L9
        out = [math.copysign(abs(t) ** rho, t) if t != 0 else 0.0 for t in out]
    if normalize:  # @line L10
        s = math.sqrt(sum(t * t for t in out))
        if s > 0.0:
            out = [t / s for t in out]
    return out  # @line L11
test_fisher_vector.py 159 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fisher-vector/. The authors are listed in prov/WR6YRW.jsonl.

import math
import random

from fisher_vector import fisher_vector, log_likelihood, posteriors, raw_gradients

W = [0.5, 0.5]
MU = [[-1.0], [1.0]]
SIG = [[1.0], [1.0]]
X = [[0.0], [1.0], [2.0]]


def close(a, b, tol):
    return len(a) == len(b) and all(abs(x - y) <= tol for x, y in zip(a, b))


def random_gmm(rng, K, D):
    a = [rng.uniform(-1.0, 1.0) for _ in range(K)]
    s = sum(math.exp(t) for t in a)
    w = [math.exp(t) / s for t in a]
    mu = [[rng.uniform(-2.0, 2.0) for _ in range(D)] for _ in range(K)]
    sigma = [[rng.uniform(0.5, 1.5) for _ in range(D)] for _ in range(K)]
    return w, mu, sigma


def sample(rng, w, mu, sigma):
    u, k = rng.random(), 0
    while k < len(w) - 1 and u > w[k]:
        u -= w[k]
        k += 1
    return [rng.gauss(m, s) for m, s in zip(mu[k], sigma[k])]


def test_example_of_the_page():
    g = posteriors([1.0], W, MU, SIG)
    assert abs(g[1] - 1 / (1 + math.exp(-2))) < 1e-12
    raw = fisher_vector(X, W, MU, SIG, rho=1.0, normalize=False, include_weights=True)
    s0 = 0.5 + 1 / (1 + math.exp(2)) + 1 / (1 + math.exp(4))
    assert abs(raw[0] - (s0 - 1.5) / (3 * math.sqrt(0.5))) < 1e-12
    assert close(raw, [-0.4067, 0.4067, 0.3735, 0.1672, 0.2272, -0.2936], 5e-5)
    assert close(fisher_vector(X, W, MU, SIG), [0.5932, 0.3968, 0.4627, -0.5259], 5e-5)


def test_dimension_and_unit_norm():
    rng = random.Random(1)
    for K, D in [(1, 2), (3, 2), (4, 3)]:
        w, mu, sigma = random_gmm(rng, K, D)
        xs = [sample(rng, w, mu, sigma) for _ in range(20)]
        z = fisher_vector(xs, w, mu, sigma)
        assert len(z) == 2 * K * D
        assert abs(sum(t * t for t in z) - 1.0) < 1e-12
        assert len(fisher_vector(xs, w, mu, sigma, include_weights=True)) == (2 * D + 1) * K


def test_gradients_match_finite_differences():
    rng = random.Random(2)
    K, D, h = 3, 2, 1e-5
    w, mu, sigma = random_gmm(rng, K, D)
    alpha = [math.log(t) for t in w]
    xs = [sample(rng, w, mu, sigma) for _ in range(15)]
    g_alpha, g_mu, g_sigma = raw_gradients(xs, w, mu, sigma)

    def softmax(a):
        s = sum(math.exp(t) for t in a)
        return [math.exp(t) / s for t in a]

    for k in range(K):
        ap, am = list(alpha), list(alpha)
        ap[k] += h
        am[k] -= h
        fd = (log_likelihood(xs, softmax(ap), mu, sigma) - log_likelihood(xs, softmax(am), mu, sigma)) / (2 * h)
        assert abs(fd - g_alpha[k]) < 1e-6
        for i in range(D):
            for par, grad in ((mu, g_mu), (sigma, g_sigma)):
                old = par[k][i]
                par[k][i] = old + h
                fp = log_likelihood(xs, w, mu, sigma)
                par[k][i] = old - h
                fm = log_likelihood(xs, w, mu, sigma)
                par[k][i] = old
                assert abs((fp - fm) / (2 * h) - grad[k][i]) < 1e-6


def test_normalized_gradient_is_raw_gradient_scaled():
    rng = random.Random(3)
    K, D = 2, 3
    w, mu, sigma = random_gmm(rng, K, D)
    xs = [sample(rng, w, mu, sigma) for _ in range(10)]
    T = len(xs)
    g_alpha, g_mu, g_sigma = raw_gradients(xs, w, mu, sigma)
    z = fisher_vector(xs, w, mu, sigma, rho=1.0, normalize=False, include_weights=True)
    expect = [g_alpha[k] / (T * math.sqrt(w[k])) for k in range(K)]
    for k in range(K):
        expect += [g_mu[k][i] * sigma[k][i] / (T * math.sqrt(w[k])) for i in range(D)]
        expect += [g_sigma[k][i] * sigma[k][i] / (T * math.sqrt(2 * w[k])) for i in range(D)]
    assert close(z, expect, 1e-12)


def test_whitening_for_separated_components():
    # Well separated components: posteriors are almost 0 or 1, the diagonal
    # Fisher information is almost exact, and each normalized per-sample
    # gradient entry of the means and sigmas has mean 0 and variance 1.
    # The weight entries have variance 1 - w_k, not 1.
    rng = random.Random(4)
    w = [0.3, 0.7]
    mu = [[0.0, 0.0], [30.0, -30.0]]
    sigma = [[1.0, 2.0], [0.5, 1.0]]
    n = 3000
    dim = 2 + 2 * 2 * 2
    s1, s2 = [0.0] * dim, [0.0] * dim
    for _ in range(n):
        z = fisher_vector([sample(rng, w, mu, sigma)], w, mu, sigma, rho=1.0, normalize=False, include_weights=True)
        for j in range(dim):
            s1[j] += z[j]
            s2[j] += z[j] * z[j]
    for j in range(dim):
        mean = s1[j] / n
        var = s2[j] / n - mean * mean
        target = 1.0 - w[j] if j < 2 else 1.0
        assert abs(mean) < 0.15
        assert abs(var - target) < 0.3


def test_hard_assignment_gives_scaled_vlad():
    rng = random.Random(5)
    K, D, T = 4, 2, 30
    w = [1.0 / K] * K
    mu = [[rng.uniform(-3, 3) for _ in range(D)] for _ in range(K)]
    sigma = [[1.0] * D for _ in range(K)]
    xs = [[rng.uniform(-4, 4) for _ in range(D)] for _ in range(T)]
    v = [[0.0] * D for _ in range(K)]
    for x in xs:
        k = min(range(K), key=lambda j: (sum((a - b) ** 2 for a, b in zip(x, mu[j])), j))
        for i in range(D):
            v[k][i] += x[i] - mu[k][i]
    z = fisher_vector(xs, w, mu, sigma, rho=1.0, normalize=False, hard=True)
    for k in range(K):
        assert close(z[2 * D * k:2 * D * k + D], [math.sqrt(K) / T * t for t in v[k]], 1e-12)


def test_order_invariance_and_power_sign():
    rng = random.Random(6)
    w, mu, sigma = random_gmm(rng, 3, 2)
    xs = [sample(rng, w, mu, sigma) for _ in range(25)]
    ys = list(xs)
    rng.shuffle(ys)
    a = fisher_vector(xs, w, mu, sigma)
    assert close(a, fisher_vector(ys, w, mu, sigma), 1e-12)
    plain = fisher_vector(xs, w, mu, sigma, rho=1.0)
    assert all((p > 0) == (q > 0) for p, q in zip(plain, a) if p != 0)


def test_posteriors_sum_to_one_far_from_all_components():
    g = posteriors([1e3, -1e3], [0.5, 0.5], [[0.0, 0.0], [1.0, 1.0]], [[1.0, 1.0], [1.0, 1.0]])
    # A naive exp() of log densities near -1e6 underflows to 0/0; log-sum-exp does not.
    assert abs(sum(g) - 1.0) < 1e-9
    assert all(0.0 < t < 1.0 for t in g)

History

Jaakkola and Haussler (1998) proposed the Fisher kernel to use a generative model inside a discriminative classifier, with protein sequences and hidden Markov models as the first application. Perronnin and Dance (2007) used a Gaussian mixture over local image descriptors as the generative model and showed that the Fisher kernel gives a compact image signature for categorization. Perronnin, Sanchez and Mensink (2010) kept only the mean and variance gradients and added power and L2 normalization and spatial pyramids, which made the Fisher vector competitive with much more costly methods. Sanchez, Perronnin, Mensink and Verbeek (2013) gave the complete derivation, the approximations and an extensive experimental study.

References

  1. Tommi Jaakkola and David Haussler, Exploiting generative models in discriminative classifiers, Advances in Neural Information Processing Systems 11 (NIPS 1998), 487-493, The Fisher score, the Fisher information as a metric, and the Fisher kernel
  2. Florent Perronnin and Christopher Dance, Fisher kernels on visual vocabularies for image categorization, CVPR 2007, The gradient of the log-likelihood of a Gaussian mixture of local descriptors as an image signature
  3. Florent Perronnin, Jorge Sanchez and Thomas Mensink, Improving the Fisher kernel for large-scale image classification, ECCV 2010, LNCS 6314, 143-156, The gradients with respect to the means and variances only (2 K D values), L2 normalization, power normalization and spatial pyramids
  4. Jorge Sanchez, Florent Perronnin, Thomas Mensink and Jakob Verbeek, Image classification with the Fisher vector: theory and practice, International Journal of Computer Vision 105(3), 2013, 222-245, Section 2.1 (Fisher kernel, Eq. 1 to 4), Section 2.2 (Gaussian mixture gradients, Eq. 16 to 19, and Algorithm 1), Section 2.3 (L2 and power normalization, Eq. 30), Section 2.5 (relation to the bag of words and VLAD), Appendix A (diagonal Fisher information)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example