Files
myAi/Apis/rag-api/Data/Repositories/VectorSerializer.cs
T
claude 75bc9509c5
Build and Push Docker Images / build (push) Successful in 4m35s
Changes
2026-05-14 14:12:29 +03:00

32 lines
919 B
C#

namespace Api.Data.Repositories;
public static class VectorSerializer
{
public static byte[] ToBytes(float[] vector)
{
var bytes = new byte[vector.Length * sizeof(float)];
Buffer.BlockCopy(vector, 0, bytes, 0, bytes.Length);
return bytes;
}
public static float[] FromBytes(byte[] bytes)
{
var vector = new float[bytes.Length / sizeof(float)];
Buffer.BlockCopy(bytes, 0, vector, 0, bytes.Length);
return vector;
}
public static double CosineSimilarity(float[] a, float[] b)
{
if (a.Length == 0 || a.Length != b.Length) return 0;
double dot = 0, magA = 0, magB = 0;
for (var i = 0; i < a.Length; i++)
{
dot += a[i] * b[i];
magA += a[i] * a[i];
magB += b[i] * b[i];
}
return magA == 0 || magB == 0 ? 0 : dot / (Math.Sqrt(magA) * Math.Sqrt(magB));
}
}