Skip to main content

A lightweight library for training and evaluating embedding models with triplet loss

Project description

TripletLib

TripletLib is a lightweight Python library for training and evaluating embedding models using triplet loss. It is designed to help you build models that learn meaningful embeddings for images, time series, or any vector data, enabling tasks like verification, retrieval, or classification based on similarity.

What is Triplet Loss?

A "triplet" is a set of 3 samples of data (anchor, positive, negative). The anchor is a data sample from a specific class, the positive is another sample from the same class, and the negative is a sample from an entirely different class. Triplet loss is a type of metric learning objective that trains an embedding model to map inputs into a vector space such that:

  • Samples from the same class (e.g., anchor and positive) are close together.
  • Samples from different classes (e.g., anchor and negative) are far apart.

This is particularly useful for tasks like biometric identification (e.g., face recognition), where traditional classification cannot generalize to unseen classes (new faces).

Features

  • Base EmbeddingModel class with a built-in training loop.
  • TripletDataset wrapper to automatically generate triplets from any dataset.
  • Utilities for evaluating embeddings with EER and AUC metrics.
  • Compatible with PyTorch and supports GPU acceleration.

Installation

You can install TripletLib via pip:

pip install tripletlib

Usage

import torch
from tripletlib.triplet_utils import EmbeddingModel, TripletDataset
from torch.utils.data import DataLoader

# Example: using a simple linear embedding model
class LinearEmbeddingModel(EmbeddingModel):
    def __init__(self, input_size, embedding_dim=64, lr=1e-3, margin=1.0, device="cpu"):
        super().__init__(embedding_dim, margin=margin, device=device)
        self.fc = torch.nn.Sequential(
            torch.nn.Linear(input_size, 128),
            torch.nn.ReLU(),
            torch.nn.Linear(128, embedding_dim)
        )
        self.optimizer = torch.optim.Adam(self.parameters(), lr=lr)

    def forward(self, x):
        x = self.fc(x)
        return torch.nn.functional.normalize(x, p=2, dim=1)

# Prepare your dataset as a list of (feature, label) tuples
train_dataset = [(torch.randn(10), label) for label in range(5) for _ in range(20)]
triplet_train = TripletDataset(train_dataset)
dataloader_train = DataLoader(triplet_train, batch_size=16, shuffle=True)

# Instantiate and train the model
model = LinearEmbeddingModel(input_size=10, embedding_dim=64, lr=1e-3)
history = model.fit(dataloader_train, epochs=5)

Examples

You can find examples of real usages in /examples, including:

  • Keystroke Dynamics: Comparing typing patterns to determine if they are from the same individual.
  • More to come...

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

tripletlib-0.1.0.tar.gz (6.0 kB view details)

Uploaded Source

Built Distribution

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

tripletlib-0.1.0-py3-none-any.whl (6.5 kB view details)

Uploaded Python 3

File details

Details for the file tripletlib-0.1.0.tar.gz.

File metadata

  • Download URL: tripletlib-0.1.0.tar.gz
  • Upload date:
  • Size: 6.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.6

File hashes

Hashes for tripletlib-0.1.0.tar.gz
Algorithm Hash digest
SHA256 cca55cd071c79d3fb3a4902c4cb503211d391524f058a223f6d37b8aaeebd7cc
MD5 ffc7415e54dde4014be0b626d6b22985
BLAKE2b-256 9c69f39eac2c230d7604ec571149e63ca217bcbbd39a2f2af5dbe133079d4c15

See more details on using hashes here.

File details

Details for the file tripletlib-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: tripletlib-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 6.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.6

File hashes

Hashes for tripletlib-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 210b3fe3a24825fd18c47748756069330c71a5ea2983e173e9156b6dce9bc84b
MD5 474bc2d3c64f4fdf5a87bb58e9d315cb
BLAKE2b-256 eb20654a93a81b2c2378ddb2fe83d90a0f9dc3ee29ee65768d24aa4009d78a51

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