Skip to content

Use TensorPrimitives.Dot to calculate Dot Product #1264

@luisquintanilla

Description

@luisquintanilla

DotProduct is currently manually calculating DotProduct.

public class DotProduct : IDistanceMetric
{
public bool BiggerIsCloser => true;
public float Distance(float[] a, float[] b)
{
if (a.Length != b.Length)
throw new ArgumentException("Vector lengths must match");
float dotProduct = 0.0f;
for (int i = 0; i < a.Length; i++)
{
dotProduct += a[i] * b[i];
}
return dotProduct;
}
}

TensorPrimitives provides a method for calculating Dot product.

https://learn.microsoft.com/en-us/dotnet/api/system.numerics.tensors.tensorprimitives.dot?view=net-10.0-pp

TensorPrimitives is already used for CosineSimilarity, so it would be good to maintain consistency.

public class CosineSimilarity : IDistanceMetric
{
public bool BiggerIsCloser => true; // Cosine similarity: 1 = most similar, -1 = least similar
public float Distance(float[] a, float[] b)
{
if (a.Length != b.Length)
throw new ArgumentException("Vector lengths must match");
return TensorPrimitives.CosineSimilarity(a.AsSpan(), b.AsSpan());
}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Status

    Untriaged

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions