tf-metric-learning
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
Prerequirements:
pip install tensorflow
pip install tensorflow-addons
pip install annoy
pip install opencv-contrib-python
This library:
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
from tf_metric_learning.utils.constants import EMBEDDINGS, LABELS
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)({EMBEDDINGS:inputs, LABELS: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:
- Complex example with NPair Loss + Multi Similarity + Classification and Mining
- SoftTriple Training on CIFAR 10
- ProxyAnchor Loss using tf.data.Dataset
- Triplet Training with Mining
- Contrastive Training
- Classification baseline
Features
Loss functions
- MultiSimilarityLoss ✅
- ProxyAnchorLoss ✅
- SoftTripleLoss ✅
- NPairLoss ✅
- TripletLoss ✅
- ContrastiveLoss ✅
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
)
Metadata
Release files for tf-metric-learning 1.0.12
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| tf-metric-learning-1.0.12.tar.gz | 18.4 kB | Without provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| tf_metric_learning-1.0.12-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 49.8 kB
Release files / tf-metric-learning-1.0.12.tar.gz
| Download URL | tf-metric-learning-1.0.12.tar.gz |
|---|---|
| Size | 18.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
22ee0b24340399540debd37acf6254ae755be8b033ff7c31d2b0cebdce57d45b
|
|
BLAKE2b-256 checksum How to use checksums |
88b451843170a893dae7919628e55409a56564886077099b59ccc05f922e465f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.10.0
|
Release files / tf_metric_learning-1.0.12-py3-none-any.whl
| Download URL | tf_metric_learning-1.0.12-py3-none-any.whl |
|---|---|
| Size | 31.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
c472162782dc2a8e03d003f17baf702131af459f8e4e2495cc9b11bdc430e805
|
|
BLAKE2b-256 checksum How to use checksums |
9547a92e500374019b2cbdce2ee87cff7d588cf16e9fed055792fc77d9986c17
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.10.0
|
Security for tf-metric-learning 1.0.12
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.