All Projects → lucidrains → Contrastive Learner

lucidrains / Contrastive Learner

Licence: mit
A simple to use pytorch wrapper for contrastive self-supervised learning on any neural network

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to Contrastive Learner

Carrecognition
This is one of the best vehicle recognition applications. It can determine the car's license plate number, color, model, brand and year.
Stars: ✭ 34 (-20.93%)
Mutual labels:  artificial-intelligence
Coursera Natural Language Processing Specialization
Programming assignments from all courses in the Coursera Natural Language Processing Specialization offered by deeplearning.ai.
Stars: ✭ 39 (-9.3%)
Mutual labels:  artificial-intelligence
Machine Learning From Scratch
Succinct Machine Learning algorithm implementations from scratch in Python, solving real-world problems (Notebooks and Book). Examples of Logistic Regression, Linear Regression, Decision Trees, K-means clustering, Sentiment Analysis, Recommender Systems, Neural Networks and Reinforcement Learning.
Stars: ✭ 42 (-2.33%)
Mutual labels:  artificial-intelligence
Artificialintelligenceengines
Computer code collated for use with Artificial Intelligence Engines book by JV Stone
Stars: ✭ 35 (-18.6%)
Mutual labels:  artificial-intelligence
Ml Classify Text Js
Machine learning based text classification in JavaScript using n-grams and cosine similarity
Stars: ✭ 38 (-11.63%)
Mutual labels:  artificial-intelligence
Science Toolkit
Intelygenz standard environment that covers the technological and methodological needs of a data team in an artificial intelligence project.
Stars: ✭ 40 (-6.98%)
Mutual labels:  artificial-intelligence
Goapy
Goal-Oriented Action Planning implementation in Python
Stars: ✭ 33 (-23.26%)
Mutual labels:  artificial-intelligence
Student Teacher Anomaly Detection
Student–Teacher Anomaly Detection with Discriminative Latent Embeddings
Stars: ✭ 43 (+0%)
Mutual labels:  artificial-intelligence
True artificial intelligence
真AI人工智能
Stars: ✭ 38 (-11.63%)
Mutual labels:  artificial-intelligence
Awesome Mlss
List of summer schools in machine learning + related fields across the globe
Stars: ✭ 1,001 (+2227.91%)
Mutual labels:  artificial-intelligence
Dataconfs
A list of conferences connected with data worldwide.
Stars: ✭ 36 (-16.28%)
Mutual labels:  artificial-intelligence
Reading comprehension tf
Machine Reading Comprehension in Tensorflow
Stars: ✭ 37 (-13.95%)
Mutual labels:  artificial-intelligence
Decoupled Multimodal Learning
A decoupled, generative, unsupervised, multimodal neural architecture
Stars: ✭ 40 (-6.98%)
Mutual labels:  artificial-intelligence
Online Relationship Learning
Unsupervised ML algorithm for predictive modeling and time-series analysis
Stars: ✭ 34 (-20.93%)
Mutual labels:  artificial-intelligence
Pytorch Cpp
C++ Implementation of PyTorch Tutorials for Everyone
Stars: ✭ 1,014 (+2258.14%)
Mutual labels:  artificial-intelligence
Deepaudioclassification
Finding the genre of a song with Deep Learning
Stars: ✭ 969 (+2153.49%)
Mutual labels:  artificial-intelligence
Jfuzzylite
jfuzzylite: a fuzzy logic control library in Java
Stars: ✭ 39 (-9.3%)
Mutual labels:  artificial-intelligence
Xplain
🌎 Complex Topics Explained For Your Level And Background. ✏️
Stars: ✭ 44 (+2.33%)
Mutual labels:  artificial-intelligence
Computervision Recipes
Best Practices, code samples, and documentation for Computer Vision.
Stars: ✭ 8,214 (+19002.33%)
Mutual labels:  artificial-intelligence
Hardhat Detector
A convolutional neural network implementation of a script that detects whether an individual is wearing a hardhat or not.
Stars: ✭ 41 (-4.65%)
Mutual labels:  artificial-intelligence

Contrastive learning in Pytorch, made simple

PyPI version

It seems we have lift-off for self-supervised learning on images.

This is a simple to use Pytorch wrapper to enable contrastive self-supervised learning on any visual neural network. At the moment, it contains enough settings for one to train on either of the schemes used in SimCLR or CURL.

You can wrap any neural network that accepts a visual input, be it a resnet, policy network, or the discriminator of a GAN. The rest is taken care of.

Issues

It has surfaced that the results of CURL are not reproducible. It is recommended that you go with the SimCLR settings until further notice.

Install

$ pip install contrastive-learner

Usage

SimCLR (projection head with normalized temperature-scaled cross-entropy loss)

import torch
from contrastive_learner import ContrastiveLearner
from torchvision import models

resnet = models.resnet50(pretrained=True)

learner = ContrastiveLearner(
    resnet,
    image_size = 256,
    hidden_layer = 'avgpool',  # layer name where output is hidden dimension. this can also be an integer specifying the index of the child
    project_hidden = True,     # use projection head
    project_dim = 128,         # projection head dimensions, 128 from paper
    use_nt_xent_loss = True,   # the above mentioned loss, abbreviated
    temperature = 0.1,         # temperature
    augment_both = True        # augment both query and key
)

opt = torch.optim.Adam(learner.parameters(), lr=3e-4)

def sample_batch_images():
    return torch.randn(20, 3, 256, 256)

for _ in range(100):
    images = sample_batch_images()
    loss = learner(images)
    opt.zero_grad()
    loss.backward()
    opt.step()

CURL (with momentum averaged key encoder)

import torch
from contrastive_learner import ContrastiveLearner
from torchvision import models

resnet = models.resnet50(pretrained=True)

learner = ContrastiveLearner(
    resnet,
    image_size = 256,
    hidden_layer = 'avgpool',
    use_momentum = True,         # use momentum for key encoder
    momentum_value = 0.999,
    project_hidden = False,      # no projection heads
    use_bilinear = True,         # in paper, logits is bilinear product of query / key
    use_nt_xent_loss = False,    # use regular contrastive loss
    augment_both = False         # in curl, only the key is augmented
)

opt = torch.optim.Adam(learner.parameters(), lr=3e-4)

def sample_batch_images():
    return torch.randn(20, 3, 256, 256)

for _ in range(100):
    images = sample_batch_images()
    loss = learner(images)
    opt.zero_grad()
    loss.backward()
    opt.step()
    learner.update_moving_average() # update moving average of key encoder

Advanced

If you want to accumulate queries and keys to do contrastive loss on a bigger batch, use the accumulate keyword on the forward pass.

for _ in range(100):
    for _ in range(5):
        images = sample_batch_images()
        _ = learner(images, accumulate=True)  # accumulate queries and keys
    loss = learner.calculate_loss()           # calculate similarity on all accumulated
    opt.zero_grad()
    loss.backward()
    opt.step()

By default, this will use the augmentations recommended in the SimCLR paper, mainly color jitter, gaussian blur, and random resize crop. However, if you would like to specify your own augmentations, you can simply pass in a augment_fn in the constructor. Augmentations must work in the tensor space. If you decide to use torchvision augmentations, make sure the function converts first to PIL .toPILImage() and then back to tensors .ToTensor()

custom_augment_fn = nn.Sequential(
    kornia.augmentations.RandomHorizontalFlip()
)

learner = ContrastiveLearner(
    resnet,
    image_size = 256,
    hidden_layer = -2,
    project_hidden = True,
    project_dim = 128,
    use_nt_xent_loss = True,
    augment_fn = custom_augment_fn
)

Citations

@misc{chen2020simple,
    title   = {A Simple Framework for Contrastive Learning of Visual Representations},
    author  = {Ting Chen and Simon Kornblith and Mohammad Norouzi and Geoffrey Hinton},
    year    = {2020}
}
@misc{srinivas2020curl,
    title   = {CURL: Contrastive Unsupervised Representations for Reinforcement Learning},
    author  = {Aravind Srinivas and Michael Laskin and Pieter Abbeel},
    year    = {2020}
}
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].