ContrastiveSiameseNetwork

This network “learns” the similarity metric directly. Two images are passed through the same shared-weight backbone and projection head to produce embeddings, which are L2-normalized so that cosine similarity reduces to a dot product. The network is trained so that similar images map to nearby embeddings and dissimilar images map far apart. Following diagram visualizes this:

                  ┌──────────┐    ┌────────────────┐    ┌──────────────┐
Input Image A ───►│ Backbone │───►│ Embedding Head │───►│ L2 Normalize │───► Embedding A
                  └──────────┘    └────────────────┘    └──────────────┘
                       ╎                  ╎                    ╎
                       ╎ Shared Weights   ╎                    ╎
                       ╎                  ╎                    ╎
                  ┌──────────┐    ┌────────────────┐    ┌──────────────┐
Input Image B ───►│ Backbone │───►│ Embedding Head │───►│ L2 Normalize │───► Embedding B
                  └──────────┘    └────────────────┘    └──────────────┘

                       Embedding A + Embedding B
                                   │
                                   ▼
┌─────────────────────────────────────────────────────────────────────┐
│ Contrastive Loss (training) / fixed metric, e.g. cosine (inference) │
└─────────────────────────────────────────────────────────────────────┘

Contrastive loss is used to train this network, which has the formula:

\[L = \frac{1}{2N} \sum_{i=1}^{N} \Bigl( y_i \, D_i^2 + (1 - y_i) \, \max(0, m - D_i)^2 \Bigr)\]

Example: training a Contrastive Siamese Network

See this tutorial.

API reference

class pyvisim.neural_networks.ContrastiveSiameseNetwork(backbone='resnet18', embedding_dim=128, similarity_func='cosine', transform=None, device='cpu', pretrained_backbone=True, *, normalize=True, batch_size=16)[source]

Bases: BackboneWithHead

Siamese network trained with a contrastive loss, proposed in Hadsell, R., Chopra, S., & LeCun, Y. (2006). Dimensionality Reduction by Learning an Invariant Mapping.

For more information, see the documentation: https://mechacritter.github.io/Python-Visual-Similarity/neural_networks/contrastive_siamese/contrastive_siamese.html.

References:

[1] Hadsell, R., Chopra, S., & LeCun, Y. (2006). Dimensionality Reduction by Learning an Invariant Mapping. In Proceedings of the 2006 IEEE Computer Society Conference on Computer Vision and Pattern Recognition (CVPR), Vol. 2, 1735-1742. https://doi.org/10.1109/CVPR.2006.100

param backbone:

name of feature-extraction network. See https://mechacritter.github.io/Python-Visual-Similarity/neural_networks/backbones/backbones.html.

param embedding_dim:

Dimensionality of the projected embedding space.

param similarity_func:

Name of the built-in similarity metric used to score two embeddings. One of "cosine", "euclidean", "l1" or "manhattan".

param transform:

processing transform applied to every input image. If None, the ImageNet preprocessing matching the backbone is used.

param device:

Device on which the model is placed.

param pretrained_backbone:

Whether to use a backbone pretrained on ImageNet. If you are loading the ContrastiveSiameseNetwork from a checkpoint, set this to False to avoid downloading the weights again.

param normalize:

Whether embed L2-normalizes the embeddings it returns.

param batch_size:

Maximum number of images processed in a single batch. Set to -1 to process all images as a single batch.

raises ValueError:

If embedding_dim is not a positive integer, if backbone is not a supported backbone name, or if similarity_func is not a supported similarity metric.

embed(images, *, dims='HWC', value_range=(0.0, 255.0))

Embeds one or more images into a batch of vector representations.

Each image is normalized to a canonical uint8 (H, W, C) array before feature extraction, so NumPy arrays, torch tensors and other array-like inputs are all accepted. When a batch axis is present (via dims), every image in the batch is embedded. The resulting vectors are L2-normalized row by row when normalize is True.

Parameters:
  • images (_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | Iterable[_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]]) – A single MatLike image, a batched array, or an iterable of images. Consider using an iterator for large datasets.

  • dims (str) – Axis-label string, one character per array axis in order: "H" = height (rows), "W" = width (columns), "C" = channels (e.g. RGB), "B" = batch size. For example, "HWC" is height × width × channels (NumPy/OpenCV single-image layout); "CHW" is channels × height × width (PyTorch single-image layout); "BCHW" is batch × channels × height × width (PyTorch batched layout). See pyvisim.typing.

  • value_range (tuple[float, float]) – The (low, high) range the input values live in; converted into the canonical [0, 255] range.

Returns:

vector representations of the given images, L2-normalized row by row if normalize is True.

Raises:

ValueError – If images holds no image.

Return type:

ndarray[tuple[int, …], dtype[floating[Any]]]

forward(x)[source]

Computes L2-normalized embeddings for a batch of preprocessed images.

During training, call this once per branch of a pair and feed both embedding batches to the contrastive loss.

Parameters:

x (Tensor) – Preprocessed image tensor of shape (batch, channels, H, W).

Returns:

L2-normalized embeddings of shape (batch, embedding_dim).

Return type:

Tensor

classmethod from_dict(state, **kwargs)

Rebuilds the embedder a state dictionary describes.

Called on SerializableImageEmbedder itself, it hands the state to the from_dict of the class named under "__class__", so a state can be rebuilt without knowing which embedder wrote it.

Parameters:
  • state (dict[str, Any]) – A JSON-safe embedder description.

  • kwargs (Any) – Objects the state cannot describe, forwarded to the embedder’s own from_dict.

Returns:

The reconstructed embedder.

Raises:
  • ValueError – If state names no concrete embedder class.

  • NotImplementedError – If called on a subclass that does not implement its own from_dict.

Return type:

_NeuralEmbedderT

classmethod load_from_disk(path, **kwargs)

Loads an object previously saved with save_to_disk().

Not every part of an object survives serialization: an arbitrary callable such as a torchvision transform has no portable description, so it is left out of the file. Pass such an object back here as a keyword argument.

Parameters:
  • path (str | Path) – Path to the file to load.

  • kwargs (Any) – Objects the file cannot hold, forwarded to from_dict().

Returns:

A ready-to-use instance.

Raises:
  • FileNotFoundError – If path does not exist.

  • ValueError – If the file is not a valid file of this kind or was saved by a different class.

  • TypeError – If the class does not take one of kwargs.

Return type:

_SerializableT

save_to_disk(path)

Saves the serialized state of this object to a file.

Parameters:

path (str | Path) – Target file path. Overwritten if it exists.

Returns:

The path of the written file.

Raises:

OSError – If the destination directory does not exist.

Return type:

Path

set_batch_size(batch_size)

Sets the number of items processed per batch.

Parameters:

batch_size (int) – Maximum number of images processed in a single batch. Set to -1 to process all images as a single batch.

Raises:

ValueError – If batch_size is neither -1 nor a positive integer.

Return type:

None

similarity_score(images1, images2, *, dims='HWC', value_range=(0.0, 255.0))

Compute the similarity scores matrix between two (batches of) images.

Parameters:
Returns:

The similarity score matrix of shape (len(images1), len(images2)).

Return type:

ndarray[tuple[int, …], dtype[float32]]

to_dict()

Serializes this object into a JSON-safe state dictionary.

The mapping holds the output of _state() plus the format version under "format_version" and the class name under "__class__". Arrays may be embedded as __ndarray__ nodes, which the serialization layer stores as binary tensors.

Returns:

A JSON-safe description suitable for from_dict().

Return type:

dict[str, Any]

property backbone: Module

The shared feature-extraction backbone.

property device: device

The device the model’s parameters live on.

Derived from the parameters themselves rather than cached, so it stays correct after the user moves the model with model.to(...).

property head: Module

The projection head mapping backbone features to embeddings.

property normalize: bool

Whether the embeddings returned by embed() are L2-normalized.

property similarity_func: Callable[[ndarray[tuple[int, ...], dtype[floating[Any]]], ndarray[tuple[int, ...], dtype[floating[Any]]]], ndarray[tuple[int, ...], dtype[floating[Any]]]]

The resolved similarity function callable.

property similarity_func_name: str

The name of the configured similarity metric (e.g. "cosine").

Parameters:
  • backbone (str)

  • embedding_dim (int)

  • similarity_func (str)

  • transform (Compose | None)

  • device (str | device)

  • pretrained_backbone (bool)

  • normalize (bool)

  • batch_size (int)