Skip to main content

Image similarity, metric learning loss functions for TensorFlow 2+.

Project description

tf-metric-learning

TensorFlow 2.2 Python 3.6

Overview

Minimalistic open-source library for metric learning written in TensorFlow2, TF-Addons, Numpy, OpenCV(CV2) and Annoy. This repository contains a TensorFlow2+/tf.keras implementation some of the loss functions and miners. This repository was inspired by pytorch-metric-learning.

Installation

pip install tensorflow
pip install annoy
pip install tf-metric-learning

Features

  • All the loss functions are implemented as tf.keras.layers.Layer
  • Callbacks for Computing Recall, Visualize Embeddings in TensorBoard Projector
  • Simple Mining mechanism with Annoy
  • Combine multiple loss functions/layers in one model

Open-source repos

This library contains code that has been adapted and modified from the following great open-source repos, without them this will be not possible (THANK YOU):

TODO

  • Discriminative layer optimizer (different learning rates) for Loss with weights (Proxy, SoftTriple, ...) TODO
  • Some Tests 😇
  • Improve and add more minerss

Examples

import tensorflow as tf
import numpy as np
from tf_metric_learning.layers import SoftTripleLoss

num_class, num_centers, embedding_size = 10, 2, 256

inputs = tf.keras.Input(shape=(embedding_size), name="embeddings")
input_label = tf.keras.layers.Input(shape=(1,), name="labels")
output_tensor = SoftTripleLoss(num_class, num_centers, embedding_size)(inputs, input_label)

model = tf.keras.Model(inputs=[inputs, input_label], outputs=output_tensor)
model.compile(optimizer="adam")

data = {"embeddings" : np.asarray([np.zeros(256) for i in range(1000)]), "labels": np.zeros(1000, dtype=np.float32)}
model.fit(data, None, epochs=10, batch_size=10)

More complex scenarios:

Features

Loss functions

Miners

  • MaximumLossMiner [TODO]
  • TripletAnnoyMiner ✅

Evaluators

  • AnnoyEvaluator Callback: for evaluation Recall@K, you will need to install Spotify annoy library.
import tensorflow as tf
from tf_metric_learning.utils.recall import AnnoyEvaluatorCallback

evaluator = AnnoyEvaluatorCallback(
    base_network,
    {"images": test_images[:divide], "labels": test_labels[:divide]}, # images stored to index
    {"images": test_images[divide:], "labels": test_labels[divide:]}, # images to query
    normalize_fn=lambda images: images / 255.0,
    normalize_eb=True,
    eb_size=embedding_size,
    freq=1,
)

Visualizations

  • Tensorboard Projector Callback
import tensorflow as tf
from tf_metric_learning.utils.projector import TBProjectorCallback

def normalize_images(images):
    return images/255.0

(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.cifar10.load_data()
...

projector = TBProjectorCallback(
    base_model,
    "tb/projector",
    test_images, # list of images
    np.squeeze(test_labels),
    normalize_eb=True,
    normalize_fn=normalize_images
)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tf-metric-learning-0.1.2.tar.gz (16.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tf_metric_learning-0.1.2-py3-none-any.whl (29.5 kB view details)

Uploaded Python 3

File details

Details for the file tf-metric-learning-0.1.2.tar.gz.

File metadata

  • Download URL: tf-metric-learning-0.1.2.tar.gz
  • Upload date:
  • Size: 16.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/47.1.0 requests-toolbelt/0.9.1 tqdm/4.49.0 CPython/3.8.5

File hashes

Hashes for tf-metric-learning-0.1.2.tar.gz
Algorithm Hash digest
SHA256 2dabdaebe54af97fba11a11f71d2c6510103ab4d72569d7079accd3f2a551ec5
MD5 b8af19ec6dde20dc1349b91f507cd0ca
BLAKE2b-256 3e285f9c96c06097ef5f30df51bc5309ce4c9ae4a4c71da31f2c21c742255006

See more details on using hashes here.

File details

Details for the file tf_metric_learning-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: tf_metric_learning-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 29.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/47.1.0 requests-toolbelt/0.9.1 tqdm/4.49.0 CPython/3.8.5

File hashes

Hashes for tf_metric_learning-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 e65fa7284720c4a40ae873486f9fa42a725e6ce783ce8937c3f4bfc10f3bba8f
MD5 457628b3366ef1c17ec5104f4677b853
BLAKE2b-256 26c2701eeebdeb27f2b909710a541322ce59bd4d916b4dba496b46a50d376c32

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page