Search

Search papers and lessons

Episodic Training

Level 3 · 11 min read

Episodic training teaches a few-shot model by practising small tasks that copy the test situation: a few classes, a few labelled examples each, and new queries to label.

On this page

  • Colour = topic mix
  • Calculus
  • Discrete math
  • Probability
  • Learning basics
  • Linear algebra
  • Losses & regularization
  • ReadReady to readNot yet

TL;DR

Episodic training is the way a few-shot model is trained. Instead of feeding the model ordinary batches of labelled data, the training loop builds many small practice tasks called episodes. Each episode picks a few classes, gives the model a handful of labelled examples of each, and asks it to label new examples of those same classes. Because the training tasks look like the test tasks, the model learns features that still work when examples are scarce.

Builds on: Few-Shot Learning, Cross-Entropy Loss, Stochastic Gradient Descent · Leads to: Prototypical Networks, Meta-Learning

Where it's used

Benchmarks for few-shot image classification. Omniglot holds 1623 handwritten characters from 50 alphabets, with 20 drawings of each character. Prototypical networks are trained on it with episodes that contain 60 classes, then tested on the characters kept back for testing. The paper reports its accuracies as averages over 1,000 randomly generated test episodes, not over one fixed split of tasks.

Meta-learners that fit a classifier to each episode. Ravi and Larochelle trained an LSTM to read an episode and produce updates for a classifier, so the classifier is adjusted to the episode's few examples before it labels the queries. The LSTM itself is trained on many episodes of this kind.

Adding a new defect type on a factory line. Imagine a factory with thousands of photographs of known defect types and only five photographs of a new one. A model trained on episodes drawn from the known types can learn to separate the new type from the others using those five examples, and an engineer checks its calls before anyone acts on them. This is a scenario, not a reported deployment.

How it works

Pretend a model has already mapped every image to a point in a plane, so each example is just two numbers. The training pool has four classes, A, B, C and D, with several labelled points each. We build one episode that is a 2-way 2-shot task with one query per class: two classes, two labelled support examples per class, and one unlabelled query per class.

flowchart LR
  P[Training pool with many classes] --> S[Sample N classes]
  S --> K[Sample K support and Q query points per class]
  K --> E[Embed all points]
  E --> L[Prototypes from support, loss on queries]
  L --> U[One gradient step]
  U --> P
  1. Start from the pool. The training data holds all four classes, each with at least four points. Check: the pool has more classes than any one episode uses.
  2. Sample two classes. Suppose the random draw picks B and D. Check: this episode shows only B and D, so the model never sees A or C in it.
  3. Split each class. For B, the support points are (1, 1) and (3, 1), and the query is (2, 3). For D, the support points are (6, 0) and (8, 0), and the query is (5, 1). Check: no query point is also a support point.
  4. Make one prototype per class. A prototype is the average of the class's support points. For B: ((1 + 3) / 2, (1 + 1) / 2) = (2, 1). For D: ((6 + 8) / 2, (0 + 0) / 2) = (7, 0). Check: each prototype lies between its own support points.
  5. Assign each query to its nearest prototype. Use squared Euclidean distance. Query (2, 3): to B, 0² + 2² = 4; to D, 5² + 3² = 34. The nearest is B, which is correct. Query (5, 1): to B, 3² + 0² = 9; to D, 2² + 1² = 5. The nearest is D, which is correct.
  6. Turn distances into a loss. The true class of query (5, 1) is D. Turn the squared distances into probabilities with a softmax over their negatives: p(D) = e^(-5) / (e^(-5) + e^(-9)) = 1 / (1 + e^(-4)), which is about 0.982. The loss is minus its logarithm, about 0.018. Check: a probability near one gives a loss near zero.
  7. Average and update. Query (2, 3) has a probability for B so close to one that its loss is essentially zero. The episode loss is the average over both queries: (0 + 0.018) / 2, about 0.009. One step of stochastic gradient descent changes the network's weights to lower this loss.
  8. Draw a new episode. The next episode may draw A and C, and it relabels them 1 and 2. Check: labels only mean something inside one episode, so the model cannot learn a fixed mapping from label numbers to classes.

The math

Definition: Episode

An episode is a training task built from the training set. It samples NN classes, and for each sampled class nn it draws KK labelled support examples Sn\mathcal{S}_n and QQ query examples Qn\mathcal{Q}_n, with the queries kept apart from the supports. The model is judged on the queries, after it has seen the supports.

Step 1 in symbols

Let the training set have CC classes. An episode picks NN of them, with N≤CN \le C. Each sampled class has ∣Sn∣=K|\mathcal{S}_n| = K support points and ∣Qn∣=Q|\mathcal{Q}_n| = Q query points. The walkthrough had N=2N = 2, K=2K = 2 and Q=1Q = 1.

Step 2 in symbols: prototypes

Let fϕf_\phi be the embedding network with weights ϕ\phi. The prototype of class nn is

cn=1K∑xi∈Snfϕ(xi).\mathbf{c}_n = \frac{1}{K} \sum_{\mathbf{x}_i \in \mathcal{S}_n} f_\phi(\mathbf{x}_i).

In words: embed every support example, then average the embeddings. The points in the walkthrough play the role of the embedded outputs fϕ(x)f_\phi(\mathbf{x}), so step 4 is this formula with K=2K = 2.

Steps 3 to 5 in symbols: distances and the softmax

Use squared Euclidean distance, d(u,v)=∥u−v∥2d(\mathbf{u}, \mathbf{v}) = \lVert \mathbf{u} - \mathbf{v} \rVert^2. The probability that a query x\mathbf{x} belongs to class nn is

pϕ(y=n∣x)=exp⁡(−d(fϕ(x),cn))∑m=1Nexp⁡(−d(fϕ(x),cm)).p_\phi(y = n \mid \mathbf{x}) = \frac{\exp\big(-d(f_\phi(\mathbf{x}), \mathbf{c}_n)\big)}{\sum_{m=1}^{N} \exp\big(-d(f_\phi(\mathbf{x}), \mathbf{c}_m)\big)}.

Here exp⁡\exp is the exponential function. The denominator runs over all NN prototypes, so the probabilities add to one. The prediction is the class with the largest probability, which is the nearest prototype.

Steps 6 and 7 in symbols: the loss and the update

For one query with true class nn, the loss is J=−log⁡pϕ(y=n∣x)J = -\log p_\phi(y = n \mid \mathbf{x}). The episode loss averages this over all NQNQ queries:

Jep(ϕ)=1NQ∑n=1N∑x∈Qn−log⁡pϕ(y=n∣x).J_{\text{ep}}(\phi) = \frac{1}{NQ} \sum_{n=1}^{N} \sum_{\mathbf{x} \in \mathcal{Q}_n} -\log p_\phi(y = n \mid \mathbf{x}).

The weights move one step against the gradient, ϕ←ϕ−η ∇ϕJep(ϕ)\phi \leftarrow \phi - \eta \, \nabla_\phi J_{\text{ep}}(\phi), where η\eta is the learning rate and ∇ϕ\nabla_\phi is the gradient with respect to the weights. Then a new episode is drawn.

Worked examples

Example
Example 1: counting the points in one episode

Take a 5-way 5-shot episode with 15 query points per class.

  1. The episode samples 5 classes from the training set.
  2. Support points: 5 classes times 5 shots gives 25.
  3. Query points: 5 classes times 15 queries gives 75.
  4. Total images in the episode: 25 + 75 = 100.

Interpretation: most of the episode is queries. The support points are the scarce resource being simulated, so the model learns to use the few examples it gets, rather than memorising the training classes.

Example
Example 2: the loss for one query

Suppose the query's squared distance to its true-class prototype is 1, and its squared distance to the other prototype is 2.

  1. Probability of the true class: e−1/(e−1+e−2)e^{-1} / (e^{-1} + e^{-2}).
  2. Divide the top and bottom by e−1e^{-1}: 1/(1+e−1)1 / (1 + e^{-1}).
  3. e−1e^{-1} is about 0.368, so the denominator is about 1.368 and the probability is about 0.731.
  4. The loss is −ln⁡0.731≈0.313-\ln 0.731 \approx 0.313.
  5. Check with a wrong prototype that is far away, at squared distance 9: p=1/(1+e−8)≈0.99966p = 1 / (1 + e^{-8}) \approx 0.99966, and the loss is about 0.00034. The loss falls as the true prototype pulls ahead.

Interpretation: training pushes the embedding so that queries sit close to their own prototype, and the loss shrinks as the margin grows.

Example
Example 3: how many classes to train with (Omniglot)

This uses Table 4 of Snell, Swersky and Zemel (2017), for prototypical networks with Euclidean distance. The training episodes have 15 query points per class, and each accuracy is averaged over 1,000 random test episodes.

  1. A model trained with 5-way, 1-shot episodes scores 97.4% on 5-way 1-shot test episodes.
  2. A model trained with 20-way, 1-shot episodes scores 98.7% on the same test.
  3. Error rate with 5-way training: 100 - 97.4 = 2.6%.
  4. Error rate with 20-way training: 100 - 98.7 = 1.3%.
  5. Ratio of the two error rates: 1.3 / 2.6 = 0.5, so training with more classes per episode halves the error here.
  6. The 5-shot columns show the same direction: 99.3% against 99.6%.

Interpretation: training on episodes with more classes than the test uses helped, which the paper found and tuned on a validation set. Try it: a 5-way 1-shot model scores 97.4% and another scores 98.7%. Out of 1,000 queries scored at each accuracy, how many errors does each model make? Answer: 26 errors for the first model and 13 for the second.

Common mistakes and tradeoffs

It is tempting to think an episode is just a random mini-batch of the training data. In fact an episode is a mini-batch with its own task. Its classes are a random subset of the training classes, and its labels are reassigned inside the episode, so the same class can be label 1 in one episode and label 2 in the next. Because the labels only mean something within one episode, the model cannot memorise a fixed label-to-class table.

It is tempting to make every training episode look exactly like the test task. In fact the paper found it beneficial to train with more classes per episode than the test uses, and it tuned that number on a validation set. For shots, it found it usually best to use the same number of support examples at training and at test time.

It is tempting to think episodic training always helps. In fact it helps when the test classes are new and the training tasks resemble them. If the target classes already have plenty of labels, ordinary supervised training is simpler and usually better. Alternatives include pretraining a model on many labelled classes and then fine-tuning it on the new ones, which can work well but can overfit a few examples, and MAML, which trains a starting point that adapts in a few gradient steps.

History

Retraining a standard classifier on a few new examples overfits badly, as the prototypical networks paper points out. In 2016, Vinyals and colleagues proposed matching networks and trained them on episodes built this way. In 2017, Ravi and Larochelle took the episodic idea further with a meta-learner based on an LSTM. In the same year, Snell, Swersky and Zemel used episodes with class prototypes, and they reported that squared Euclidean distance worked better than the cosine distance used in matching networks. Their training setup is the one described in this lesson.

Recap

  • An episode is a small training task: NN classes, with KK support and QQ query examples per class.
  • Episodes are drawn at random from the training set, and labels are reassigned inside each episode.
  • A query is classified by its nearest prototype, with a softmax over negative squared distances. The loss is the negative log probability of the true class.
  • One gradient step per episode trains the embedding so that few-shot tasks become easier.
  • Read next: Prototypical Networks for the method used in the walkthrough, and Meta-Learning for the wider idea of learning from tasks.

Check yourself

QuestionRecall: what are the support points and the query points in one episode?Show answer
The support points are the labelled examples the model is given for each sampled class, KK per class. The query points are the examples of those same classes that the model must label, QQ per class. The loss is computed on the queries after the model has used the supports.
QuestionComputation: how many support points and how many query points are in a 4-way 3-shot episode with 2 queries per class?Show answer
Support points: 4 classes times 3 shots gives 12. Query points: 4 classes times 2 queries gives 8. The episode has 12 support points and 8 query points.
QuestionWhy: why are the class labels reassigned inside each episode, rather than kept fixed across training?Show answer
Each episode uses a random subset of the training classes, so the same class would otherwise have different labels from one episode to the next. Reassigning labels within the episode means the model cannot rely on a fixed table of label numbers. It has to compare the examples it is given, which is the skill the test tasks need.
QuestionApplied: a team trains with 2-class episodes but will test on 5-class tasks. Should it change the training episodes, and what should it check?Show answer
The paper found that training with more classes per episode than the test uses can help, so the team could try 5-class or larger training episodes. It should choose the number on a held-out validation set, keep the shot count the same at training and test time, and average its results over many random test episodes rather than one draw.

Sources