Contrastive learning is a self-supervised learning technique that trains models by teaching them to distinguish between similar and dissimilar data points. The core idea is to learn representations by pulling similar items closer together in the embedding space while pushing dissimilar items apart.
The process typically works like this:
Data augmentation and pair creation: For each data point (like an image), the system creates multiple "views" through augmentation. For images, this might involve cropping, rotating, or color jittering. These augmented versions of the same image form "positive pairs" - they should have similar representations since they're derived from the same source.
Negative sampling: The system also needs examples of what should be far apart. These "negative pairs" are typically formed by pairing a data point with other random samples from the dataset. Some methods use large batches where every other sample in the batch serves as a negative.
Embedding through neural networks: Each view is passed through a neural network (often called an encoder) to produce a vector representation or embedding. The goal is to train this encoder so that positive pairs have similar embeddings while negative pairs have dissimilar ones.
Loss function: The training uses a contrastive loss function, such as InfoNCE or NT-Xent, which mathematically expresses the goal of maximizing similarity between positive pairs while minimizing similarity with negative pairs. The loss essentially treats the problem as classifying which samples belong together.
Training dynamics: During training, the model learns features that are invariant to the augmentations (since augmented versions should map to similar points) but discriminative enough to distinguish between different instances. This forces the model to capture meaningful, high-level features rather than superficial details.
Contrastive learning has proven particularly powerful for pre-training models without labels. Methods like SimCLR, MoCo, and CLIP have shown that models trained this way can learn rich representations that transfer well to downstream tasks, sometimes matching or exceeding supervised pre-training performance.