Foundations

Self-Supervised Learning: Making Labels From the Data Itself

Understand how models learn from unlabeled data by predicting hidden or related parts of it, with worked examples and common pitfalls.

Key takeaways

  • Self-supervised learning creates input and target pairs from raw data by a fixed rule, so labels cost almost nothing.
  • The training task, called a pretext task, matters mostly for the representation it forces the model to learn.
  • Predicting hidden parts and contrasting matched with unmatched pairs are two major families of methods.
  • Models can cheat through shortcuts or collapse to a constant output, so evaluate on the tasks you actually care about.
  • Unlabeled data still carries biases, errors, licensing terms and private information into the model.

Self-supervised learning trains a model on targets that are generated automatically from the data. You hide, corrupt or transform part of an example and ask the model to recover what you did, or to recognize which pieces belong together. No person labels anything, yet training uses the same machinery as supervised learning: inputs, targets and a loss.

The point is usually the internal representation the model builds along the way. A representation is the list of numbers a network computes to describe an input. A good one makes later tasks learnable from far fewer human labels.

Turning raw data into exercises

Take the sentence "the cat sat on the mat." A next-word rule turns it into several supervised examples without any annotation.

words = "the cat sat on the mat".split()

for i in range(1, len(words)):
    context, target = words[:i], words[i]
    print(" ".join(context), "->", target)

This prints five pairs, from "the -> cat" to "the cat sat on the -> mat". Scale this to a very large body of text and the model must absorb grammar, word meanings and many regularities to predict well. Real systems work on tokens, which are words or pieces of words, and process many positions in parallel. That is the basis of next-token pretraining.

The same trick applies elsewhere. Cut patches out of an image and predict them. Mask a stretch of audio and reconstruct it or its features. Hide a column in a table row and guess it from the others.

Two main families

Predictive or masked methods hide something and ask for it back. A masked language model sees "the cat [MASK] on the mat" and must assign high probability to plausible fillers. Because it can read both sides of the gap, it learns a different skill from a next-word predictor, which only sees the past. Masked prediction covers the design choices, such as how much to hide.

Contrastive methods teach similarity. Two altered views of the same photograph, say a crop and a color shift, form a positive pair. Views of different photographs form negative pairs. The model learns to place positives close together and negatives apart.

Two families of pretext tasks
Predict hidden parts Next token or masked token Missing image patches Target comes from the input itself Loss: classification or reconstruction Match related views Two crops of one image An image and its caption Other examples serve as negatives Loss: pick the true partner VS Predict hidden parts Next token or masked token Missing image patches Target comes from the input itself Loss: classification or reconstruction Match related views Two crops of one image An image and its caption Other examples serve as negatives Loss: pick the true partner

A contrastive loss worked by hand

A widely used contrastive loss asks the model to pick the true partner out of a set of candidates. Let the anchor have similarity 0.8 with its positive and similarities 0.2 and 0.0 with two negatives. Divide by a temperature τ, a number that controls how sharply differences count. Take τ = 0.5 and use the natural log.

scaled scores   1.6, 0.4, 0.0        (similarity ÷ τ)
exponentials    4.953, 1.492, 1.000
sum             7.445
p(positive)     4.953 / 7.445 ≈ 0.665
loss            −ln(0.665) ≈ 0.41

This is a softmax followed by cross-entropy, where the "correct class" is the true partner. Training lowers the loss by raising the positive similarity or lowering the negative ones. A smaller temperature magnifies the gaps and puts more emphasis on the hardest negatives. See contrastive learning for how pairs and negatives are chosen.

Why predicting the input can teach anything

It may seem odd that guessing missing words would help classify reviews. The reason is that good guesses require information that many tasks share. To fill the gap in "the soup was cold, so I sent it ___," a model benefits from knowing about food, temperature, cause and effect, and ordinary phrasing.

In statistical terms, you are learning about p(x), or about how parts of x predict each other, and hoping that the useful structure for p(y given x) overlaps with it. Nothing guarantees the overlap. A model trained to reconstruct every pixel may spend much of its capacity on fine texture that says nothing about what object is present. One reason for hiding large regions of an image is that small gaps can be filled by copying neighbors, with no need to understand the scene.

So the design of a pretext task is a search for exercises that cannot be solved without learning something transferable. Difficulty should sit in a middle range. If the answer is trivially readable from the surroundings, little is learned. If it is essentially random, such as predicting the exact digits of a serial number, there is nothing to learn.

Choosing what counts as the same

The alterations you apply to create positive pairs declare what should be ignored. If two crops with different colors must match, the representation learns to discount color. That is helpful for recognizing a chair and harmful for judging whether fruit is ripe.

This is an inductive bias you control. Ask of every transformation: would my downstream label stay the same after it? Mirroring is fine for most animal photos and wrong for reading text. Shifting pitch may be harmless for detecting a door slam and damaging for identifying a speaker.

Shortcuts and collapse

A model is rewarded for solving the exercise by any available route. If a cheap cue solves it, the model has little reason to learn anything deeper. Reported shortcuts in vision include low-level traces of the camera or lens that reveal where a patch came from. In text, repeated boilerplate can make many predictions trivial.

Collapse is the extreme case. If you only ask matched views to have similar outputs, a network can output the same vector for everything and score perfectly. Methods prevent this with negative examples, with penalties that keep representation dimensions varied and decorrelated, or with deliberately asymmetric network designs.

A falling pretext loss therefore proves little on its own. Check that outputs actually vary across inputs, and test usefulness downstream.

Using the representation

After pretraining, you adapt the model to a labeled task. Two common options are:

  1. Linear probe: freeze the network and train a simple classifier on its outputs. It is cheap and shows what is easy to read out of the representation.
  2. Fine-tuning: continue training some or all of the weights on the labeled data. It usually has more potential and more room to overfit.

Choosing between them depends on how much labeled data you have and how close your task is to the pretraining data. Either way, compare against a plain baseline, including a model trained from scratch and one using a publicly available pretrained network.

When it is worth doing yourself

Most practitioners benefit from self-supervision by downloading a pretrained model. Training your own makes more sense when several conditions hold together:

  • You have far more unlabeled than labeled data.
  • Your domain differs sharply from what public models saw, such as an unusual sensor.
  • You can afford the compute and the experimentation.
  • You have a labeled evaluation set large enough to show a difference.

If you have only a few thousand unlabeled records, adapting an existing model or using ordinary supervised methods is likely the better use of time. Tabular data in particular often gains less than text or images, and boosted trees remain a strong comparison.

How it differs from its neighbors

Approach Source of the training signal
Supervised Labels from people or recorded outcomes
Unsupervised Structure only, as in clustering or density estimation
Self-supervised Targets derived from the input by a rule
Semi-supervised A few labels plus many unlabeled examples

The boundaries are a matter of convention, and many people count self-supervision as a form of unsupervised learning. It also combines naturally with semi-supervised methods: pretrain on everything, then use the few labels carefully.

An experiment design that answers the question

Suppose you have 200,000 unlabeled sensor recordings and 2,000 labeled ones, a hypothetical but typical shape. Set aside a labeled test set first, split by machine or site so that near-identical recordings cannot land on both sides. Exclude it from pretraining too if you want the cleanest estimate for unseen equipment.

Then compare four options on the rest: a simple model on hand-built features, a network trained from scratch on the labels, a public pretrained model adapted to your data, and your own pretrained network adapted the same way. Give each a similar tuning budget.

Repeat the comparison with 100, 500 and all of the labeled training examples. Self-supervision often shows its value most clearly when labels are scarcest, and the curve tells you whether more labeling would close the gap more cheaply. Run several random seeds, since differences on small labeled sets can easily be noise.

Responsibilities that remain

Free labels do not make data free of obligations. Check the license and terms of your sources, whether you have a lawful basis to use personal information, and whether the model might reproduce sensitive strings it saw. Legal requirements vary by jurisdiction, so ask counsel when in doubt.

Skews in the raw data also shape the representation. A group, dialect or condition that rarely appears will tend to be represented poorly. Measure performance on those slices after adaptation, because an average score can hide the gap.

Written for 4MachineLearning with AI writing tools and not reviewed line by line by a person. Check anything you rely on against a textbook or primary source. Report an error.

Keep reading

All 42 articles in Foundations →

Latest news on this topic