Package: tfsim-nightly
TensorFlow Similarity: Metric Learning for HumansTensorFlow Similarity is aTensorFlowlibrary forsimilarity learningwhich includes techniques such as self-supervised learning, metric learning, similarity learning, and contrastive learning. TensorFlow Similarity is still in beta and we may push breaking changes.IntroductionTensorflow Similarity offers state-of-the-art algorithms for metric learning along with all the necessary components to research, train, evaluate, and serve similarity and contrastive based models. These components include models, losses, metrics, samplers, visualizers, and indexing subsystems to make this quick and easy.With Tensorflow Similarity you can train two main types of models:Self-supervised models: Used to learn general data representations on unlabeled data to boost the accuracy of downstream tasks where you have few labels. For example, you can pre-train a model on a large number of unlabled images using one of the supported contrastive methods supported by TensorFlow Similarity, and then fine-tune it on a small labeled dataset to achieve higher accuracy. To get started training your own self-supervised model see thisnotebook.Similarity models: Output embeddings that allow you to find and cluster similar examples such as images representing the same object within a large corpus of examples. For instance, as visible above, you can train a similarity model to find and cluster similar looking, unseen cat and dog images from theOxford IIIT Pet Datasetwhile only training on a few of the dataset classes. To get started training your own similarity model see thisnotebook.What's new[Mar 2023]: 0.17 more losses and metric and massive refactoringAdded VicReg Loss to contrastive losses.Added metrics used in retrieval papers such as Precision@KNative support for distributed training e.g SimClr now works correctly with distributed training.Multi-modal embedding initial support (CLIP)For more details and previous releases information - seethe changelogGetting StartedInstallationUse pip to install the library.NOTE: The Tensorflow extra_require key can be omitted if you already have tensorflow>=2.4 installed.pipinstall--upgrade-strategy=only-if-neededtensorflow_similarity[tensorflow]DocumentationThe detailed and narratednotebooksare a good way to get started with TensorFlow Similarity. There is likely to be one that is similar to your data or your problem (if not, let us know). You can start working with the examples immediately in Google Colab by clicking the Google Colab icon.For more information about specific functions, you cancheck the API documentationFor contributing to the project please check out thecontribution guidelinesMinimal Example: MNIST similarityClick to expand and see how to train a supervised similarity model on mnist using TF.SimilarityHere is a bare bones example demonstrating how to train a TensorFlow Similarity model on the MNIST data. This example illustrates some of the main components provided by TensorFlow Similarity and how they fit together. Please refer to thehello_world notebookfor a more detailed introduction.Preparing dataTensorFlow Similarity providesdata samplers, for various dataset types, that balance the batches to ensure smoother training.
In this example, we are using the multi-shot sampler that integrates directly from the TensorFlow dataset catalog.fromtensorflow_similarity.samplersimportTFDatasetMultiShotMemorySampler# Data sampler that generates balanced batches from MNIST datasetsampler=TFDatasetMultiShotMemorySampler(dataset_name='mnist',classes_per_batch=10)Building a Similarity modelBuilding a TensorFlow Similarity model is similar to building a standard Keras model, except the output layer is usually aMetricEmbedding()layer that enforces L2 normalization and the model is instantiated as a specialized subclassSimilarityModel()that supports additional functionality.fromtensorflow.kerasimportlayersfromtensorflow_similarity.layersimportMetricEmbeddingfromtensorflow_similarity.modelsimportSimilarityModel# Build a Similarity model using standard Keras layersinputs=layers.Input(shape=(28,28,1))x=layers.experimental.preprocessing.Rescaling(1/255)(inputs)x=layers.Conv2D(64,3,activation='relu')(x)x=layers.Flatten()(x)x=layers.Dense(64,activation='relu')(x)outputs=MetricEmbedding(64)(x)# Build a specialized Similarity modelmodel=SimilarityModel(inputs,outputs)Training model via contrastive learningTo output a metric embedding, that are searchable via approximate nearest neighbor search, the model needs to be trained using a similarity loss. Here we are using theMultiSimilarityLoss(), which is one of the most efficient loss functions.fromtensorflow_similarity.lossesimportMultiSimilarityLoss# Train Similarity model using contrastive lossmodel.compile('adam',loss=MultiSimilarityLoss())model.fit(sampler,epochs=5)Building images index and querying itOnce the model is trained, reference examples must be indexed via the model index API to be searchable. After indexing, you can use the model lookup API to search the index for the K most similar items.fromtensorflow_similarity.visualizationimportviz_neigbors_imgs# Index 100 embedded MNIST examples to make them searchablesx,sy=sampler.get_slice(0,100)model.index(x=sx,y=sy,data=sx)# Find the top 5 most similar indexed MNIST examples for a given exampleqx,qy=sampler.get_slice(3713,1)nns=model.single_lookup(qx[0])# Visualize the query example and its top 5 neighborsviz_neigbors_imgs(qx[0],qy[0],nns)Supported AlgorithmsSelf-Supervised ModelsSimCLRSimSiamBarlow TwinsSupervised LossesTriplet LossPN LossMulti Sim LossCircle LossSoft Nearest Neighbor LossMetricsTensorflow Similarity offers many of the most common metrics used forclassificationandretrievalevaluation. Including:NameTypeDescriptionPrecisionClassificationRecallClassificationF1 ScoreClassificationRecall@KRetrievalBinary NDCGRetrievalCitingPlease cite this reference if you use any part of TensorFlow similarity in your research:@article{EBSIM21,title={TensorFlow Similarity: A Usable, High-Performance Metric Learning Library},author={Elie Bursztein, James Long, Shun Lin, Owen Vallis, Francois Chollet},journal={Fixme},year={2021}}DisclaimerThis is not an official Google product.