Search

Search papers and lessons

Image Captioning

Level 3 · 12 min read

Image captioning is generating a sentence that describes a picture, usually by encoding the image with a convolutional network and decoding words one at a time while looking back at the image.

On this page

  • Colour = topic mix
  • Calculus
  • Discrete math
  • Neural network basics
  • Linear algebra
  • Architectures
  • Probability
  • ReadReady to readNot yet

TL;DR

Image captioning is the task of writing a sentence that describes what is in a picture. A convolutional network reads the image and produces a set of feature vectors, one for each region. A language model then writes the caption one word at a time, and at each word it can look back at the regions it needs. The method matters because it turns a picture into text without anyone writing rules for objects or grammar.

Builds on: convolutional networks, encoder-decoder networks, attention · Leads to: vision-language models that answer questions about images and describe them in chat

Where it's used

Alt text for images. Websites and apps need a short description of each picture for people who use screen readers. A captioning model can draft that description for an uploaded photo, and a person can check and edit it.

Searching and sorting photo libraries. A caption gives each photo a line of words that a search engine can index. A query such as "dog on a beach" can then match photos whose captions contain those words, even when the user never tagged them.

Benchmarks for vision and language research. The standard test sets are Flickr8k, with 8,000 images, Flickr30k, with 30,000 images, and MS COCO, with 82,783 images. The 2015 attention model by Xu and colleagues reported state-of-the-art results on all three, which made these sets the usual yardstick for new captioning methods.

How it works

We will trace one tiny instance. Real systems use a large image encoder and a vocabulary of many thousands of words. Here the "image" is a 2-by-2 grid of cells, and each cell has a feature vector of length 2. The decoder will produce a single word.

  1. Encode the image. A convolutional network turns the picture into one feature vector per cell. In our tiny case the four vectors are a1=(1,0)a_1 = (1, 0), a2=(0,1)a_2 = (0, 1), a3=(2,2)a_3 = (2, 2) and a4=(0,0)a_4 = (0, 0). Each one describes a part of the picture. Check: there are four cells and four vectors.
  2. Start the decoder. The decoder is a recurrent network, such as an LSTM, that keeps a hidden state. Its first memory and hidden states are predicted by small networks from the average of the feature vectors, so the decoder starts with a summary of the whole image.
  3. Score the cells for the first word. The decoder compares its current state with each cell's vector and gives each cell a score. Suppose the scores are (0,0,2,0)(0, 0, 2, 0), so cell 3 looks most relevant to the word the decoder is about to write.
  4. Turn scores into weights. A Softmax turns the scores into positive weights that sum to 1. The weights are about (0.096,0.096,0.711,0.096)(0.096, 0.096, 0.711, 0.096), which is mostly on cell 3. This is the attention step: the model decides where to look.
  5. Build the context vector. Multiply each feature vector by its weight and add them up. The result is 0.096×(1,0)+0.096×(0,1)+0.711×(2,2)+0.096×(0,0)≈(1.52,1.52)0.096 \times (1, 0) + 0.096 \times (0, 1) + 0.711 \times (2, 2) + 0.096 \times (0, 0) \approx (1.52, 1.52). Check: the result is close to cell 3's vector, because cell 3 has most of the weight.
  6. Predict the word. The decoder combines the context vector with its state and the embedding of the previous word, then produces a score for every word in the vocabulary. The highest-probability word, here "dog", is chosen.
  7. Repeat for the next word. The decoder updates its state, attends again, and may now look at a different cell, for example the one with the grass. The caption grows one word at a time until the decoder emits an end token.
  8. Keep several candidates. Instead of taking the top word at every step, beam search keeps the best few partial captions and extends each one, so a single early mistake does not decide the whole sentence.
flowchart LR
  A[Image] --> B[CNN: one vector per cell]
  B --> C[Attention weights over cells]
  C --> D[Context vector]
  D --> E[Decoder LSTM]
  E --> F[Word scores]
  F --> G[Beam search picks next word]
  G --> E

The math

Definition

Definition: Image caption model with soft attention

Let a1,…,aL\mathbf{a}_1, \ldots, \mathbf{a}_L be the LL annotation vectors from the image encoder, one per location. At each word tt, the model computes attention weights and a context vector,

αt,i=exp⁡(et,i)∑j=1Lexp⁡(et,j),zt=∑i=1Lαt,i ai,\alpha_{t,i} = \frac{\exp(e_{t,i})}{\sum_{j=1}^{L} \exp(e_{t,j})}, \qquad \mathbf{z}_t = \sum_{i=1}^{L} \alpha_{t,i}\, \mathbf{a}_i,

where et,ie_{t,i} is a score that depends on ai\mathbf{a}_i and the decoder's previous state. The next word yty_t is drawn from a distribution computed from zt\mathbf{z}_t, the previous word and the decoder state.

Read it in words: the weights αt,i\alpha_{t,i} are positive and sum to 1 over the locations. The context vector zt\mathbf{z}_t is a weighted average of the locations, where the weights change at every word.

Step 3 in symbols: the scores

The score et,ie_{t,i} comes from a small learned function of the feature vector ai\mathbf{a}_i and the decoder's state. For the tiny example we set the scores directly to e=(0,0,2,0)e = (0, 0, 2, 0).

Step 4 in symbols: the softmax

Using the definition on the scores gives denominator e0+e0+e2+e0=3+e2≈10.39e^0 + e^0 + e^2 + e^0 = 3 + e^2 \approx 10.39. The weights are therefore 1/10.39≈0.0961/10.39 \approx 0.096 for the three cells with score 0, and e2/10.39≈0.711e^2/10.39 \approx 0.711 for cell 3. Rounded to three decimals, the weights are (0.096,0.096,0.711,0.096)(0.096, 0.096, 0.711, 0.096), which sum to about 1.

Step 5 in symbols: the context vector

With those weights,

z=0.096 (1,0)+0.096 (0,1)+0.711 (2,2)+0.096 (0,0)=(1.518,  1.518).\mathbf{z} = 0.096\,(1,0) + 0.096\,(0,1) + 0.711\,(2,2) + 0.096\,(0,0) = (1.518,\; 1.518).

Rounded, this is (1.52,1.52)(1.52, 1.52), which matches step 5 of the walkthrough.

Step 6 in symbols: the word distribution

The decoder produces a score for each vocabulary word, and a softmax over those scores gives the probability of each word:

p(yt=w∣y<t,image)=exp⁡(sw)∑vexp⁡(sv),p(y_t = w \mid y_{\lt t}, \text{image}) = \frac{\exp(s_w)}{\sum_{v} \exp(s_v)},

where sws_w is the decoder's score for word ww and the sum runs over the whole vocabulary. Training maximizes the probability of the reference caption, which is the same as minimizing the cross-entropy summed over its words.

A regularizer on the attention

The 2015 model adds a term that encourages each location to receive attention in total over the whole caption. Writing the sum over words, it pushes ∑tαt,i\sum_t \alpha_{t,i} toward 1 for every location ii. The paper describes this as encouraging the model to pay roughly equal attention to every part of the image over the course of generation.

Worked examples

Example
Tiny: the context vector for one word

Use the four vectors a1=(1,0)a_1 = (1, 0), a2=(0,1)a_2 = (0, 1), a3=(2,2)a_3 = (2, 2), a4=(0,0)a_4 = (0, 0) and the weights (0.5,0.5,0,0)(0.5, 0.5, 0, 0).

  1. Multiply a1a_1 by 0.5: the result is (0.5,0)(0.5, 0).
  2. Multiply a2a_2 by 0.5: the result is (0,0.5)(0, 0.5).
  3. Multiply a3a_3 by 0: the result is (0,0)(0, 0).
  4. Multiply a4a_4 by 0: the result is (0,0)(0, 0).
  5. Add the four results: (0.5,0.5)(0.5, 0.5).

Answer: the context vector is (0.5,0.5)(0.5, 0.5), the average of the first two cells, because the weights put all their mass on cells 1 and 2.

Example
Standard: a second word moves the attention

Use the same vectors. For the first word the weights were (0.096,0.096,0.711,0.096)(0.096, 0.096, 0.711, 0.096), which gave z1≈(1.52,1.52)\mathbf{z}_1 \approx (1.52, 1.52). For the second word the decoder's scores change to (3,0,0,0)(3, 0, 0, 0), which points at cell 1.

  1. Compute the exponentials: e3≈20.09e^3 \approx 20.09 and e0=1e^0 = 1 three times, so the sum is 20.09+3=23.0920.09 + 3 = 23.09.
  2. The weight on cell 1 is 20.09/23.09≈0.87020.09 / 23.09 \approx 0.870.
  3. Each of the other three cells gets 1/23.09≈0.0431 / 23.09 \approx 0.043.
  4. Check: 0.870+3×0.043=0.9990.870 + 3 \times 0.043 = 0.999, which is 1 up to rounding.
  5. The context vector is z2=0.870 (1,0)+0.043 (0,1)+0.043 (2,2)+0.043 (0,0)=(0.956,  0.129)\mathbf{z}_2 = 0.870\,(1,0) + 0.043\,(0,1) + 0.043\,(2,2) + 0.043\,(0,0) = (0.956,\; 0.129) with these rounded weights, which is (0.96,0.13)(0.96, 0.13) to two decimals.
  6. Compare with z1=(1.52,1.52)\mathbf{z}_1 = (1.52, 1.52). The second context vector leans toward cell 1, so the second word can use different evidence from the first.

Answer: z2≈(0.96,0.13)\mathbf{z}_2 \approx (0.96, 0.13). Attention moved from cell 3 to cell 1 between the two words.

Example
Realistic: the size of the attention grid in a real model

Real captioning models use the feature map of a convolutional network, not a 2-by-2 grid. The 2015 model in the Xu paper uses the 14-by-14-by-512 feature map of the fourth convolutional layer of the 19-layer Oxford VGG network, taken before max pooling.

  1. The grid has 14×14=19614 \times 14 = 196 locations, so L=196L = 196.
  2. Each location has a 512-number feature vector, so one image gives 196×512=100,352196 \times 512 = 100{,}352 numbers.
  3. At each word, the decoder computes 196 scores, turns them into 196 weights with a softmax, and forms one context vector of length 512.
  4. The weights for one word sum to 1, so most of the image can be left out of any single word's context while the rest of the caption still draws on it.

Try it: a model uses a 7-by-7 grid of 512-number vectors. How many locations LL does it have, and how many numbers does one image produce? Answer: L=49L = 49 and 49×512=25,08849 \times 512 = 25{,}088 numbers.

Common mistakes and tradeoffs

Mistake: "The attention map shows exactly what the model is reasoning about." It is tempting to read the highlighted cell as the model's explanation. In fact the weights are a useful visualization of where the model looked for one word, and the Xu paper uses them that way, but they do not fully explain the output, because the words also depend on the decoder's own state and on the language it has learned.

Mistake: "A higher BLEU score always means better captions." It is tempting to rank models by one number. In fact BLEU rewards word overlap with a reference, and it misses meaning and fluency. The Xu paper reports BLEU alongside METEOR and notes that the authors used BLEU on the validation set for model selection, but also observed that BLEU and validation log-likelihood stopped correlating late in training.

Mistake: "Taking the most likely word at each step gives the best caption." It is tempting to decode greedily. In fact a locally best word can lead to a poor sentence later. Beam search keeps several candidates and usually gives more fluent captions, at a higher compute cost.

Tradeoffs. A single global feature vector for the whole image is cheap and simple, but it throws away where things are. Attention over a grid keeps location information and gives visualizations, at the cost of more computation for each word. Using a pretrained encoder, the common choice, saves a great deal of training data and compute, but it limits how well the captioner can adapt to unusual images.

When to use it. Use a captioning model when you need a short description of many images and some errors are acceptable, with a person reviewing the output. When not to use it. Do not rely on it alone where a wrong description has serious consequences, such as medical or legal images. Alternatives. Retrieval, which returns the caption of the most similar training image, is simpler and never invents words, but it cannot describe a scene that is not already in its data.

History

Neural captioning started around 2014. Kiros and colleagues proposed a multimodal log-bilinear model that used image features to bias a language model, which the Xu paper cites as the first use of neural networks for caption generation. Vinyals and colleagues then published an encoder-decoder captioner, usually called Show and Tell, in which a convolutional network encodes the image and a recurrent network writes the sentence.

Attention came from machine translation. Bahdanau and colleagues in 2014 let a translation model look back at the source words while writing each target word, and the Xu paper took that idea to images. Its abstract says the work was inspired by recent work in machine translation and object detection.

The 2015 Xu model learned to attend to image regions and was trained both deterministically and stochastically. It reported state-of-the-art results on Flickr8k, Flickr30k and MS COCO, and its attention maps made the captioner's choices visible, without the object detectors that other systems used to produce such alignments. Since then, captioning has become one part of larger vision-language models.

Recap

  • An image encoder turns a picture into one feature vector per region.
  • A recurrent decoder writes the caption one word at a time, and at each word attention decides which regions to read.
  • The context vector is a weighted average of the region vectors, with weights from a softmax over scores.
  • Beam search keeps several partial captions so that early choices can be corrected.
  • Read next: attention in more depth, and BLEU to see how captions are scored.

Check yourself

QuestionAn image has 4 region vectors and the attention weights for one word are (0.2,0.2,0.4,0.2)(0.2, 0.2, 0.4, 0.2). Each vector is (1,0)(1, 0) except the third, which is (0,3)(0, 3). What is the context vector?Show answer

Answer: (0.6,1.2)(0.6, 1.2). The first, second and fourth vectors are (1,0)(1,0) with weights 0.20.2, 0.20.2 and 0.20.2, which contribute 0.60.6 to the first coordinate. The third vector is (0,3)(0,3) with weight 0.40.4, which contributes 1.21.2 to the second coordinate.

QuestionWhy does the model use a softmax over the region scores instead of a hard choice of the single best region?Show answer

Answer: A softmax gives a smooth set of positive weights that sum to 1, so the context vector is a weighted average and is differentiable. A hard choice of one region is a discrete selection, which cannot be trained by ordinary backpropagation and needs a sampling-based estimator. The Xu paper's deterministic version uses the smooth soft attention and trains end to end with standard backpropagation; its stochastic version samples one location per step.

QuestionA captioner has 100 region vectors of length 256 for each image. How many numbers does one image produce, and how many attention weights are computed per word?Show answer

Answer: 25,600 numbers per image, since 100×256=25,600100 \times 256 = 25{,}600. For each word there are 100 attention weights, one per region.

QuestionA colleague says a caption with a higher BLEU score must describe the image better. Give one reason this could be wrong.Show answer

Answer: BLEU measures word overlap with reference captions, so a caption can score well by using the same words in a wrong or awkward arrangement, and it can score poorly while describing the scene correctly with different words. The Xu paper also notes that BLEU and validation log-likelihood stopped correlating late in training.

QuestionWhen would greedy decoding be a poor choice for caption generation?Show answer

Answer: When the most likely first word leads to a sentence that is worse overall than a sentence starting with a slightly less likely word. Greedy decoding cannot recover from that early choice, while beam search keeps several candidates and can find a better full caption.

Sources