CosineKernel<T>

Models & Types · AiDotNet.Kernels

Cosine Similarity Kernel that measures angular distance between vectors.

Implements: IKernelFunction<T>

For Beginners

The Cosine Kernel computes the cosine of the angle between two vectors. It measures similarity based on direction rather than magnitude.

In mathematical terms: k(x, x’) = (x · x’) / (||x|| × ||x’||)

Where:

  • x · x’ is the dot product
  • ||x|| is the Euclidean norm (length) of x

Properties:

  • Returns values in [-1, 1]
  • k(x, x’) = 1 when vectors point in the same direction
  • k(x, x’) = 0 when vectors are orthogonal
  • k(x, x’) = -1 when vectors point in opposite directions

This kernel is particularly useful for:

  • Text classification (TF-IDF vectors)
  • Document similarity
  • Any application where magnitude doesn’t matter, only direction

Example

using AiDotNet.Kernels;
using AiDotNet.Tensors.LinearAlgebra;

var kernel = new CosineKernel<double>();
var a = new Vector<double>(new[] { 1.0, 2.0, 3.0 });
var b = new Vector<double>(new[] { 1.5, 1.0, 2.5 });
double similarity = kernel.Calculate(a, b);
Console.WriteLine($"CosineKernel: K(a, b) = {similarity:F4}");

Constructors

Constructor Summary
CosineKernel(double outputScale) Initializes a new Cosine Kernel.

Properties

Property Summary
double OutputScale { get; } Gets the output scale.

Methods

Method Summary
T Calculate(Vector<T> x1, Vector<T> x2) Calculates the cosine similarity between two vectors.