中文环境下使用 huggingface 模型替换 OpenAI的Embedding 接口

科技资讯 投稿 5700 0 评论

    搜索(其中结果按与查询字符串的相关性排名)
  • 聚类(其中文本字符串按相似性分组)
  • 推荐(推荐具有相关文本字符串的项目)
  • 异常检测(识别出相关性不大的异常值)
  • 多样性测量(分析相似性分布)
  • 分类(其中文本字符串按其最相似的标签分类)

嵌入是浮点数的向量(列表)。两个向量之间的距离衡量它们的相关性。小距离表示高相关性,大距离表示低相关性。 但是OpenAI的文本嵌入接口对中文的支持并不好,社区经过实践,对中文支持比较好的模型是Hugging face上的 ganymedenil/text2vec-large-chinese。具体可以参见:https://huggingface.co/GanymedeNil/text2vec-large-chinese/discussions/3,作者采用的训练数据集是 中文STS-B数据集。它将句子映射到 768 维密集向量空间,可用于任务 如句子嵌入、文本匹配或语义搜索。

我们首先构建一个Docker,执行命令 docker image build -t hf_model_server .,最新的构建会有问题,我把它独立成一个repo :https://github.com/mlnethub/hugging-face-http-server。

docker run -p 5000:5000 -d hf_model_server

image

具体用法参考单元测试代码HuggingFaceEmbeddingGenerationTests

using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.SemanticKernel.Connectors.AI.HuggingFace.TextEmbedding;
using Xunit;

/// <summary>
/// Unit tests for <see cref="HuggingFaceTextEmbeddingGeneration"/> class.
/// </summary>
public class HuggingFaceEmbeddingGenerationTests : IDisposable
{
     private const string Endpoint = "http://localhost:5000/embeddings";
     private const string Model = @"GanymedeNil/text2vec-large-chinese";

     {
         StatusCode = HttpStatusCode.OK,
     };

     /// Verifies that <see cref="HuggingFaceTextEmbeddingGeneration.GenerateEmbeddingsAsync"/>
     /// returns expected list of generated embeddings without errors.
     /// </summary>
     [Fact]
     public async Task ItReturnsEmbeddingsCorrectlyAsync()
     {
         // Arrange
         const int ExpectedEmbeddingCount = 1;
         const int ExpectedVectorCount = 8;
         List<string> data = new() { "test_string_1", "test_string_2", "test_string_3" };

        // Act
         var embeddings = await service.GenerateEmbeddingsAsync(data);

         Assert.NotNull(embeddings);
         Assert.Equal(ExpectedEmbeddingCount, embeddings.Count);
         Assert.Equal(ExpectedVectorCount, embeddings.First().Count);
     }

     /// Initializes <see cref="HuggingFaceTextEmbeddingGeneration"/> with mocked <see cref="HttpClientHandler"/>.
     /// </summary>
     /// <param name="testResponse">Test response for <see cref="HttpClientHandler"/> to return.</param>
     private HuggingFaceTextEmbeddingGeneration CreateService(string testResponse)
     {
         this._response.Content = new StringContent(testResponse);

        return new HuggingFaceTextEmbeddingGeneration(new Uri(Endpoint), Model, httpClientHandler);
     }

     {
         this.Dispose(true);
         GC.SuppressFinalize(this);
     }

     {
         if (disposing)
         {
             this._response.Dispose();
         }
     }
}

编程笔记 » 中文环境下使用 huggingface 模型替换 OpenAI的Embedding 接口

赞同 (29) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽