Пример #1
0
    public void CorrectlyCalculateCosineSimilarity(double[] vectorA, double[] vectorB, double expectedSimilarity)
    {
        var similarityFunction =
            SimilarityFunctionResolver.ResolveSimilarityFunction(SimilarityFunctionType.Cosine);

        var calculatedSimilarity = similarityFunction.Invoke(vectorA, vectorB);

        Assert.Equal(expectedSimilarity, calculatedSimilarity, 8);
    }
Пример #2
0
    /// <summary>
    /// Returns the top n most similar embeddings to the one given.
    /// </summary>
    public static IEnumerable <(IEmbedding embedding, double similarity)> GetMostSimilarEmbeddings(
        this IEnumerable <IEmbedding> embeddings,
        IEmbedding embedding,
        int n = 10,
        SimilarityFunctionType similarityFunctionType = SimilarityFunctionType.Cosine)
    {
        var similarityFunction = SimilarityFunctionResolver.ResolveSimilarityFunction(similarityFunctionType);

        var embeddingsArray = embeddings.ToArray();

        return(embeddingsArray.Where(we => we.Label != embedding.Label)
               .Select(otherEmbedding => (otherEmbedding, similarityFunction.Invoke(embedding.Vector.ToArray(), otherEmbedding.Vector.ToArray())))
               .OrderByDescending(owcs => owcs.Item2)
               .Take(n));
    }