Skip to main content

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

Project description

TripletLib

GitHub

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.1.tar.gz (6.1 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.1-py3-none-any.whl (6.6 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: tripletlib-0.1.1.tar.gz
  • Upload date:
  • Size: 6.1 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.1.tar.gz
Algorithm Hash digest
SHA256 1d2cfe68c5f9168ab1a77db839a17448cff9cc1be4ae5e115c05d4102572cb8c
MD5 33993ac836c73ea0ce3b2f06dd6b5cb7
BLAKE2b-256 45d3442d0c476aaf2ecc678eef18e5d749a6d8cad459fe2209aa548c2846e967

See more details on using hashes here.

File details

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

File metadata

  • Download URL: tripletlib-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 6.6 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.1-py3-none-any.whl
Algorithm Hash digest
SHA256 5064b1708a61645ea7bfd927ef4182525a7d31428d3a8bf8e0050508e27115ec
MD5 c8be945cae5640cb4d104c10ea7ba960
BLAKE2b-256 060a7c8cafbdd1c09ac691892deb83c119eeb2a7476a51e3ade77d65de87f9b6

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