SiameseNetwork<T>
Models & Types · AiDotNet.NeuralNetworks
Implements a Siamese Neural Network for comparing pairs of inputs and determining their similarity.
Inheritance: NeuralNetworkBase<T> → DeclaredModelLayoutBase<T> → SiameseNetwork<T>
Implements: IAuxiliaryLossLayer<T>
For Beginners
A Siamese Network is a special type of neural network designed to compare two inputs and determine how similar they are to each other.
Imagine you have two photos and want to know if they show the same person. A Siamese Network processes both photos through identical neural networks (like twins, hence the name “Siamese”), creates a compact representation (called an “embedding”) of each photo, and then compares these representations to determine similarity.
Common applications include:
- Face recognition (are these two faces the same person?)
- Signature verification (is this signature authentic?)
- Document similarity (how similar are these two texts?)
- Product recommendations (finding similar products)
The key advantage of Siamese Networks is that they can learn to recognize similarity even for inputs they’ve never seen before during training.
Example
var architecture = new NeuralNetworkArchitecture<float>(inputFeatures: 8, outputSize: 4);
var options = new SiameseNetworkOptions { EmbeddingSize = 64 };
var input = Tensor<float>.CreateRandom(new[] { 1, 128 });
var trainX = Tensor<float>.CreateRandom(4, 8);
var trainY = Tensor<float>.CreateRandom(4, 2);
var result = new AiModelBuilder<float, Tensor<float>, Tensor<float>>()
.ConfigureModel(new SiameseNetwork<float>(architecture))
.Build(trainX, trainY);
var embedding = result.Predict(input);
Constructors
| Constructor | Summary |
|---|---|
SiameseNetwork() |
Initializes a new instance of the SiameseNetwork class. |
SiameseNetwork(NeuralNetworkArchitecture<T> architecture, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>> optimizer, ILossFunction<T> lossFunction, SiameseNetworkOptions options) |
Properties
| Property | Summary |
|---|---|
T AuxiliaryLossWeight { get; set; } |
Gets or sets the weight for the contrastive auxiliary loss. |
T ContrastiveMargin { get; set; } |
Gets or sets the margin for contrastive loss. |
bool UseAuxiliaryLoss { get; set; } |
Gets or sets whether auxiliary loss (contrastive/triplet loss) should be used during training. |
Methods
| Method | Summary |
|---|---|
Dictionary<string, string> GetAuxiliaryLossDiagnostics() |
Gets diagnostic information about the contrastive auxiliary loss. |
Dictionary<string, string> GetDiagnostics() |
Gets diagnostic information about this component’s state and behavior. |
ModelMetadata<T> GetModelMetadata() |
Serializes Siamese network-specific data to a binary writer. |
T ComputeAuxiliaryLoss() |
Computes the auxiliary loss (contrastive loss) for similarity learning. |
Tensor<T> ForwardForTraining(Tensor<T> input) |
Defines the Siamese forward graph for tape-based training. |