last ...
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
using System;
|
||||
using xCommons.Extensions;
|
||||
using System.Numerics.Tensors;
|
||||
using xExceptions.Constants;
|
||||
|
||||
namespace xAiModels.Helpers
|
||||
{
|
||||
public static class VectorHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Normalize a Vector ...
|
||||
/// </summary>
|
||||
/// <param name="vector"></param>
|
||||
public static void Normalize(float[] vector)
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (vector.IsNull() || !vector.HasChild())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
float sum = 0f;
|
||||
foreach (var value in vector)
|
||||
{
|
||||
sum += value * value;
|
||||
}
|
||||
|
||||
//
|
||||
float norm = MathF.Sqrt(sum);
|
||||
if (norm <= 1e-9f)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
for (int i = 0; i < vector.Length; i++)
|
||||
{
|
||||
vector[i] /= norm;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Similarity Check ...
|
||||
/// </summary>
|
||||
/// <param name="a"></param>
|
||||
/// <param name="b"></param>
|
||||
/// <returns></returns>
|
||||
public static float CosineSimilarity(
|
||||
float[] a,
|
||||
float[] b
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (a.Length != b.Length)
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
// Check Similarity ...
|
||||
var result = TensorPrimitives
|
||||
.CosineSimilarity(
|
||||
a.AsSpan(),
|
||||
b.AsSpan()
|
||||
);
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user