{"id":13603263,"url":"https://github.com/shibing624/text2vec","last_synced_at":"2025-05-12T13:22:20.632Z","repository":{"id":41165396,"uuid":"221121871","full_name":"shibing624/text2vec","owner":"shibing624","description":"text2vec, text to vector. 文本向量表征工具，把文本转化为向量矩阵，实现了Word2Vec、RankBM25、Sentence-BERT、CoSENT等文本表征、文本相似度计算模型，开箱即用。","archived":false,"fork":false,"pushed_at":"2025-05-01T05:21:00.000Z","size":16151,"stargazers_count":4706,"open_issues_count":15,"forks_count":409,"subscribers_count":31,"default_branch":"master","last_synced_at":"2025-05-01T05:35:08.761Z","etag":null,"topics":["embeddings","nlp","sentence-embeddings","similarity","text-similarity","text2vec","word2vec"],"latest_commit_sha":null,"homepage":"https://pypi.org/project/text2vec/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/shibing624.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":"CITATION.cff","codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2019-11-12T03:27:57.000Z","updated_at":"2025-05-01T05:21:05.000Z","dependencies_parsed_at":"2024-01-12T10:27:19.806Z","dependency_job_id":"fa8744a8-4ea4-42bb-9022-985c97ff0dff","html_url":"https://github.com/shibing624/text2vec","commit_stats":{"total_commits":358,"total_committers":4,"mean_commits":89.5,"dds":"0.016759776536312887","last_synced_commit":"2164ebd42f42f1353b784383554397fce0de89b1"},"previous_names":[],"tags_count":26,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shibing624%2Ftext2vec","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shibing624%2Ftext2vec/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shibing624%2Ftext2vec/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shibing624%2Ftext2vec/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/shibing624","download_url":"https://codeload.github.com/shibing624/text2vec/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253745201,"owners_count":21957321,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["embeddings","nlp","sentence-embeddings","similarity","text-similarity","text2vec","word2vec"],"created_at":"2024-08-01T18:01:59.737Z","updated_at":"2025-05-12T13:22:20.607Z","avatar_url":"https://github.com/shibing624.png","language":"Python","readme":"[**🇨🇳中文**](https://github.com/shibing624/text2vec/blob/master/README.md) | [**🌐English**](https://github.com/shibing624/text2vec/blob/master/README_EN.md) | [**📖文档/Docs**](https://github.com/shibing624/text2vec/wiki) | [**🤖模型/Models**](https://huggingface.co/shibing624) \n\n\u003cdiv align=\"center\"\u003e\n  \u003ca href=\"https://github.com/shibing624/text2vec\"\u003e\n    \u003cimg src=\"https://github.com/shibing624/text2vec/blob/master/docs/t2v-logo.png\" height=\"150\" alt=\"Logo\"\u003e\n  \u003c/a\u003e\n\u003c/div\u003e\n\n-----------------\n\n# Text2vec: Text to Vector\n[![PyPI version](https://badge.fury.io/py/text2vec.svg)](https://badge.fury.io/py/text2vec)\n[![Downloads](https://static.pepy.tech/badge/text2vec)](https://pepy.tech/project/text2vec)\n[![Contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg)](CONTRIBUTING.md)\n[![License Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)\n[![python_version](https://img.shields.io/badge/Python-3.5%2B-green.svg)](requirements.txt)\n[![GitHub issues](https://img.shields.io/github/issues/shibing624/text2vec.svg)](https://github.com/shibing624/text2vec/issues)\n[![Wechat Group](https://img.shields.io/badge/wechat-group-green.svg?logo=wechat)](#Contact)\n\n\n**Text2vec**: Text to Vector, Get Sentence Embeddings. 文本向量化，把文本(包括词、句子、段落)表征为向量矩阵。\n\n**text2vec**实现了Word2Vec、RankBM25、BERT、Sentence-BERT、CoSENT等多种文本表征、文本相似度计算模型，并在文本语义匹配（相似度计算）任务上比较了各模型的效果。\n\n### News\n[2023/09/20] v1.2.9版本: 支持多卡推理（多进程实现多GPU、多CPU推理），新增命令行工具（CLI），可以脚本执行批量文本向量化，详见[Release-v1.2.9](https://github.com/shibing624/text2vec/releases/tag/1.2.9)\n\n[2023/09/03] v1.2.4版本: 支持FlagEmbedding模型训练，发布了中文匹配模型[shibing624/text2vec-bge-large-chinese](https://huggingface.co/shibing624/text2vec-bge-large-chinese)，用CoSENT方法监督训练，基于`BAAI/bge-large-zh-noinstruct`用中文匹配数据集训练得到，并在中文测试集评估相对于原模型效果有提升，短文本区分度上提升明显，详见[Release-v1.2.4](https://github.com/shibing624/text2vec/releases/tag/1.2.4)\n\n[2023/07/17] v1.2.2版本: 支持多卡训练，发布了多语言匹配模型[shibing624/text2vec-base-multilingual](https://huggingface.co/shibing624/text2vec-base-multilingual)，用CoSENT方法训练，基于`sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2`用人工挑选后的多语言STS数据集[shibing624/nli-zh-all/text2vec-base-multilingual-dataset](https://huggingface.co/datasets/shibing624/nli-zh-all/tree/main/text2vec-base-multilingual-dataset)训练得到，并在中英文测试集评估相对于原模型效果有提升，详见[Release-v1.2.2](https://github.com/shibing624/text2vec/releases/tag/1.2.2)\n\n[2023/06/19] v1.2.1版本: 更新了中文匹配模型`shibing624/text2vec-base-chinese-nli`为新版[shibing624/text2vec-base-chinese-sentence](https://huggingface.co/shibing624/text2vec-base-chinese-sentence)，针对CoSENT的loss计算对排序敏感特点，人工挑选并整理出高质量的有相关性排序的STS数据集[shibing624/nli-zh-all/text2vec-base-chinese-sentence-dataset](https://huggingface.co/datasets/shibing624/nli-zh-all/tree/main/text2vec-base-chinese-sentence-dataset)，在各评估集表现相对之前有提升；发布了适用于s2p的中文匹配模型[shibing624/text2vec-base-chinese-paraphrase](https://huggingface.co/shibing624/text2vec-base-chinese-paraphrase)，详见[Release-v1.2.1](https://github.com/shibing624/text2vec/releases/tag/1.2.1)\n\n[2023/06/15] v1.2.0版本: 发布了中文匹配模型[shibing624/text2vec-base-chinese-nli](https://huggingface.co/shibing624/text2vec-base-chinese-nli)，基于`nghuyong/ernie-3.0-base-zh`模型，使用了中文NLI数据集[shibing624/nli_zh](https://huggingface.co/datasets/shibing624/nli_zh)全部语料训练的CoSENT文本匹配模型，在各评估集表现提升明显，详见[Release-v1.2.0](https://github.com/shibing624/text2vec/releases/tag/1.2.0)\n\n[2022/03/12] v1.1.4版本: 发布了中文匹配模型[shibing624/text2vec-base-chinese](https://huggingface.co/shibing624/text2vec-base-chinese)，基于中文STS训练集训练的CoSENT匹配模型。详见[Release-v1.1.4](https://github.com/shibing624/text2vec/releases/tag/1.1.4)\n\n\n**Guide**\n- [Features](#Features)\n- [Evaluation](#Evaluation)\n- [Install](#install)\n- [Usage](#usage)\n- [Contact](#Contact)\n- [References](#references)\n\n\n## Features\n### 文本向量表示模型\n- [Word2Vec](https://github.com/shibing624/text2vec/blob/master/text2vec/word2vec.py)：通过腾讯AI Lab开源的大规模高质量中文[词向量数据（800万中文词轻量版）](https://pan.baidu.com/s/1La4U4XNFe8s5BJqxPQpeiQ) (文件名：light_Tencent_AILab_ChineseEmbedding.bin 密码: tawe）实现词向量检索，本项目实现了句子（词向量求平均）的word2vec向量表示\n- [SBERT(Sentence-BERT)](https://github.com/shibing624/text2vec/blob/master/text2vec/sentencebert_model.py)：权衡性能和效率的句向量表示模型，训练时通过有监督训练BERT和softmax分类函数，文本匹配预测时直接取句子向量做余弦，句子表征方法，本项目基于PyTorch复现了Sentence-BERT模型的训练和预测\n- [CoSENT(Cosine Sentence)](https://github.com/shibing624/text2vec/blob/master/text2vec/cosent_model.py)：CoSENT模型提出了一种排序的损失函数，使训练过程更贴近预测，模型收敛速度和效果比Sentence-BERT更好，本项目基于PyTorch实现了CoSENT模型的训练和预测\n- [BGE(BAAI general embedding)](https://github.com/shibing624/text2vec/blob/master/text2vec/bge_model.py)：BGE模型按照[retromae](https://github.com/staoxiao/RetroMAE)方法进行预训练，[参考论文](https://aclanthology.org/2022.emnlp-main.35.pdf)，再使用对比学习finetune微调训练模型，本项目基于PyTorch实现了BGE模型的微调训练和预测\n\n\n详细文本向量表示方法见wiki: [文本向量表示方法](https://github.com/shibing624/text2vec/wiki/%E6%96%87%E6%9C%AC%E5%90%91%E9%87%8F%E8%A1%A8%E7%A4%BA%E6%96%B9%E6%B3%95)\n## Evaluation\n\n文本匹配\n\n#### 英文匹配数据集的评测结果：\n\n\n| Arch   | BaseModel                                        | Model                                                                                                                | English-STS-B | \n|:-------|:------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------|:-------------:|\n| GloVe  | glove                                           | Avg_word_embeddings_glove_6B_300d                                                                                    |     61.77     |\n| BERT   | bert-base-uncased                               | BERT-base-cls                                                                                                        |     20.29     |\n| BERT   | bert-base-uncased                               | BERT-base-first_last_avg                                                                                             |     59.04     |\n| BERT   | bert-base-uncased                               | BERT-base-first_last_avg-whiten(NLI)                                                                                 |     63.65     |\n| SBERT  | sentence-transformers/bert-base-nli-mean-tokens | SBERT-base-nli-cls                                                                                                   |     73.65     |\n| SBERT  | sentence-transformers/bert-base-nli-mean-tokens | SBERT-base-nli-first_last_avg                                                                                        |     77.96     |\n| CoSENT | bert-base-uncased                               | CoSENT-base-first_last_avg                                                                                           |     69.93     |\n| CoSENT | sentence-transformers/bert-base-nli-mean-tokens | CoSENT-base-nli-first_last_avg                                                                                       |     79.68     |\n| CoSENT | sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2 | [shibing624/text2vec-base-multilingual](https://huggingface.co/shibing624/text2vec-base-multilingual)                |     80.12     |\n\n#### 中文匹配数据集的评测结果：\n\n\n| Arch   | BaseModel                    | Model           | ATEC  |  BQ   | LCQMC | PAWSX | STS-B |  Avg  | \n|:-------|:----------------------------|:--------------------|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|\n| SBERT  | bert-base-chinese           | SBERT-bert-base     | 46.36 | 70.36 | 78.72 | 46.86 | 66.41 | 61.74 |\n| SBERT  | hfl/chinese-macbert-base    | SBERT-macbert-base  | 47.28 | 68.63 | 79.42 | 55.59 | 64.82 | 63.15 |\n| SBERT  | hfl/chinese-roberta-wwm-ext | SBERT-roberta-ext   | 48.29 | 69.99 | 79.22 | 44.10 | 72.42 | 62.80 |\n| CoSENT | bert-base-chinese           | CoSENT-bert-base    | 49.74 | 72.38 | 78.69 | 60.00 | 79.27 | 68.01 |\n| CoSENT | hfl/chinese-macbert-base    | CoSENT-macbert-base | 50.39 | 72.93 | 79.17 | 60.86 | 79.30 | 68.53 |\n| CoSENT | hfl/chinese-roberta-wwm-ext | CoSENT-roberta-ext  | 50.81 | 71.45 | 79.31 | 61.56 | 79.96 | 68.61 |\n\n说明：\n- 结果评测指标：spearman系数\n- 为评测模型能力，结果均只用该数据集的train训练，在test上评估得到的表现，没用外部数据\n- `SBERT-macbert-base`模型，是用SBert方法训练，运行[examples/training_sup_text_matching_model.py](https://github.com/shibing624/text2vec/blob/master/examples/training_sup_text_matching_model.py)代码可训练模型\n- `sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2`模型是用SBert训练，是`paraphrase-MiniLM-L12-v2`模型的多语言版本，支持中文、英文等\n\n\n### Release Models\n- 本项目release模型的中文匹配评测结果：\n\n| Arch       | BaseModel                                                   | Model                                                                                                                                             | ATEC  |  BQ   | LCQMC | PAWSX | STS-B | SOHU-dd | SOHU-dc |    Avg    |  QPS  |\n|:-----------|:------------------------------------------------------------|:--------------------------------------------------------------------------------------------------------------------------------------------------|:-----:|:-----:|:-----:|:-----:|:-----:|:-------:|:-------:|:---------:|:-----:|\n| Word2Vec   | word2vec                                                    | [w2v-light-tencent-chinese](https://modelscope.cn/models/lili666/text2vec-word2vec-tencent-chinese)                                               | 20.00 | 31.49 | 59.46 | 2.57  | 55.78 |  55.04  |  20.70  |   35.03   | 23769 |\n| SBERT      | xlm-roberta-base                                            | [sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2](https://huggingface.co/sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2) | 18.42 | 38.52 | 63.96 | 10.14 | 78.90 |  63.01  |  52.28  |   46.46   | 3138  |\n| CoSENT     | hfl/chinese-macbert-base                                    | [shibing624/text2vec-base-chinese](https://huggingface.co/shibing624/text2vec-base-chinese)                                                       | 31.93 | 42.67 | 70.16 | 17.21 | 79.30 |  70.27  |  50.42  |   51.61   | 3008  |\n| CoSENT     | hfl/chinese-lert-large                                      | [GanymedeNil/text2vec-large-chinese](https://huggingface.co/GanymedeNil/text2vec-large-chinese)                                                   | 32.61 | 44.59 | 69.30 | 14.51 | 79.44 |  73.01  |  59.04  |   53.12   | 2092  |\n| CoSENT     | nghuyong/ernie-3.0-base-zh                                  | [shibing624/text2vec-base-chinese-sentence](https://huggingface.co/shibing624/text2vec-base-chinese-sentence)                                     | 43.37 | 61.43 | 73.48 | 38.90 | 78.25 |  70.60  |  53.08  |   59.87   | 3089  |\n| CoSENT     | nghuyong/ernie-3.0-base-zh                                  | [shibing624/text2vec-base-chinese-paraphrase](https://huggingface.co/shibing624/text2vec-base-chinese-paraphrase)                                 | 44.89 | 63.58 | 74.24 | 40.90 | 78.93 |  76.70  |  63.30  | **63.08** | 3066  |\n| CoSENT     | sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2 | [shibing624/text2vec-base-multilingual](https://huggingface.co/shibing624/text2vec-base-multilingual)                                             | 32.39 | 50.33 | 65.64 | 32.56 | 74.45 |  68.88  |  51.17  |   53.67   | 3138  |\n| CoSENT     | BAAI/bge-large-zh-noinstruct                                | [shibing624/text2vec-bge-large-chinese](https://huggingface.co/shibing624/text2vec-bge-large-chinese)                                             | 38.41 | 61.34 | 71.72 | 35.15 | 76.44 |  71.81  |  63.15  |   59.72   |  844  |\n\n\n说明：\n- 结果评测指标：spearman系数\n- `shibing624/text2vec-base-chinese`模型，是用CoSENT方法训练，基于`hfl/chinese-macbert-base`在中文STS-B数据训练得到，并在中文STS-B测试集评估达到较好效果，运行[examples/training_sup_text_matching_model.py](https://github.com/shibing624/text2vec/blob/master/examples/training_sup_text_matching_model.py)代码可训练模型，模型文件已经上传HF model hub，中文通用语义匹配任务推荐使用\n- `shibing624/text2vec-base-chinese-sentence`模型，是用CoSENT方法训练，基于`nghuyong/ernie-3.0-base-zh`用人工挑选后的中文STS数据集[shibing624/nli-zh-all/text2vec-base-chinese-sentence-dataset](https://huggingface.co/datasets/shibing624/nli-zh-all/tree/main/text2vec-base-chinese-sentence-dataset)训练得到，并在中文各NLI测试集评估达到较好效果，运行[examples/training_sup_text_matching_model_jsonl_data.py](https://github.com/shibing624/text2vec/blob/master/examples/training_sup_text_matching_model_jsonl_data.py)代码可训练模型，模型文件已经上传HF model hub，中文s2s(句子vs句子)语义匹配任务推荐使用\n- `shibing624/text2vec-base-chinese-paraphrase`模型，是用CoSENT方法训练，基于`nghuyong/ernie-3.0-base-zh`用人工挑选后的中文STS数据集[shibing624/nli-zh-all/text2vec-base-chinese-paraphrase-dataset](https://huggingface.co/datasets/shibing624/nli-zh-all/tree/main/text2vec-base-chinese-paraphrase-dataset)，数据集相对于[shibing624/nli-zh-all/text2vec-base-chinese-sentence-dataset](https://huggingface.co/datasets/shibing624/nli-zh-all/tree/main/text2vec-base-chinese-sentence-dataset)加入了s2p(sentence to paraphrase)数据，强化了其长文本的表征能力，并在中文各NLI测试集评估达到SOTA，运行[examples/training_sup_text_matching_model_jsonl_data.py](https://github.com/shibing624/text2vec/blob/master/examples/training_sup_text_matching_model_jsonl_data.py)代码可训练模型，模型文件已经上传HF model hub，中文s2p(句子vs段落)语义匹配任务推荐使用\n- `shibing624/text2vec-base-multilingual`模型，是用CoSENT方法训练，基于`sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2`用人工挑选后的多语言STS数据集[shibing624/nli-zh-all/text2vec-base-multilingual-dataset](https://huggingface.co/datasets/shibing624/nli-zh-all/tree/main/text2vec-base-multilingual-dataset)训练得到，并在中英文测试集评估相对于原模型效果有提升，运行[examples/training_sup_text_matching_model_jsonl_data.py](https://github.com/shibing624/text2vec/blob/master/examples/training_sup_text_matching_model_jsonl_data.py)代码可训练模型，模型文件已经上传HF model hub，多语言语义匹配任务推荐使用\n- `shibing624/text2vec-bge-large-chinese`模型，是用CoSENT方法训练，基于`BAAI/bge-large-zh-noinstruct`用人工挑选后的中文STS数据集[shibing624/nli-zh-all/text2vec-base-chinese-paraphrase-dataset](https://huggingface.co/datasets/shibing624/nli-zh-all/tree/main/text2vec-base-chinese-paraphrase-dataset)训练得到，并在中文测试集评估相对于原模型效果有提升，在短文本区分度上提升明显，运行[examples/training_sup_text_matching_model_jsonl_data.py](https://github.com/shibing624/text2vec/blob/master/examples/training_sup_text_matching_model_jsonl_data.py)代码可训练模型，模型文件已经上传HF model hub，中文s2s(句子vs句子)语义匹配任务推荐使用\n- `w2v-light-tencent-chinese`是腾讯词向量的Word2Vec模型，CPU加载使用，适用于中文字面匹配任务和缺少数据的冷启动情况\n- 各预训练模型均可以通过transformers调用，如MacBERT模型：`--model_name hfl/chinese-macbert-base` 或者roberta模型：`--model_name uer/roberta-medium-wwm-chinese-cluecorpussmall`\n- 为测评模型的鲁棒性，加入了未训练过的SOHU测试集，用于测试模型的泛化能力；为达到开箱即用的实用效果，使用了搜集到的各中文匹配数据集，数据集也上传到HF datasets[链接见下方](#数据集)\n- 中文匹配任务实验表明，pooling最优是`EncoderType.FIRST_LAST_AVG`和`EncoderType.MEAN`，两者预测效果差异很小\n- 中文匹配评测结果复现，可以下载中文匹配数据集到`examples/data`，运行 [tests/model_spearman.py](https://github.com/shibing624/text2vec/blob/master/tests/model_spearman.py) 代码复现评测结果\n- QPS的GPU测试环境是Tesla V100，显存32GB\n\n模型训练实验报告：[实验报告](https://github.com/shibing624/text2vec/blob/master/docs/model_report.md)\n## Demo\n\nOfficial Demo: https://www.mulanai.com/product/short_text_sim/\n\nHuggingFace Demo: https://huggingface.co/spaces/shibing624/text2vec\n\n![](https://github.com/shibing624/text2vec/blob/master/docs/hf.png)\n\nrun example: [examples/gradio_demo.py](https://github.com/shibing624/text2vec/blob/master/examples/gradio_demo.py) to see the demo:\n```shell\npython examples/gradio_demo.py\n```\n\n## Install\n```shell\npip install torch # conda install pytorch\npip install -U text2vec\n```\n\nor\n\n```shell\npip install torch # conda install pytorch\npip install -r requirements.txt\n\ngit clone https://github.com/shibing624/text2vec.git\ncd text2vec\npip install --no-deps .\n```\n\n## Usage\n\n### 文本向量表征\n\n基于`pretrained model`计算文本向量：\n\n```zsh\n\u003e\u003e\u003e from text2vec import SentenceModel\n\u003e\u003e\u003e m = SentenceModel()\n\u003e\u003e\u003e m.encode(\"如何更换花呗绑定银行卡\")\nEmbedding shape: (768,)\n```\n\nexample: [examples/computing_embeddings_demo.py](https://github.com/shibing624/text2vec/blob/master/examples/computing_embeddings_demo.py)\n\n```python\nimport sys\n\nsys.path.append('..')\nfrom text2vec import SentenceModel\nfrom text2vec import Word2Vec\n\n\ndef compute_emb(model):\n    # Embed a list of sentences\n    sentences = [\n        '卡',\n        '银行卡',\n        '如何更换花呗绑定银行卡',\n        '花呗更改绑定银行卡',\n        'This framework generates embeddings for each input sentence',\n        'Sentences are passed as a list of string.',\n        'The quick brown fox jumps over the lazy dog.'\n    ]\n    sentence_embeddings = model.encode(sentences)\n    print(type(sentence_embeddings), sentence_embeddings.shape)\n\n    # The result is a list of sentence embeddings as numpy arrays\n    for sentence, embedding in zip(sentences, sentence_embeddings):\n        print(\"Sentence:\", sentence)\n        print(\"Embedding shape:\", embedding.shape)\n        print(\"Embedding head:\", embedding[:10])\n        print()\n\n\nif __name__ == \"__main__\":\n    # 中文句向量模型(CoSENT)，中文语义匹配任务推荐，支持fine-tune继续训练\n    t2v_model = SentenceModel(\"shibing624/text2vec-base-chinese\")\n    compute_emb(t2v_model)\n\n    # 支持多语言的句向量模型（CoSENT），多语言（包括中英文）语义匹配任务推荐，支持fine-tune继续训练\n    sbert_model = SentenceModel(\"shibing624/text2vec-base-multilingual\")\n    compute_emb(sbert_model)\n\n    # 中文词向量模型(word2vec)，中文字面匹配任务和冷启动适用\n    w2v_model = Word2Vec(\"w2v-light-tencent-chinese\")\n    compute_emb(w2v_model)\n\n```\n\noutput:\n```\n\u003cclass 'numpy.ndarray'\u003e (7, 768)\nSentence: 卡\nEmbedding shape: (768,)\n\nSentence: 银行卡\nEmbedding shape: (768,)\n ... \n```\n\n- 返回值`embeddings`是`numpy.ndarray`类型，shape为`(sentences_size, model_embedding_size)`，三个模型任选一种即可，推荐用第一个。\n- `shibing624/text2vec-base-chinese`模型是CoSENT方法在中文STS-B数据集训练得到的，模型已经上传到huggingface的\n模型库[shibing624/text2vec-base-chinese](https://huggingface.co/shibing624/text2vec-base-chinese)，\n是`text2vec.SentenceModel`指定的默认模型，可以通过上面示例调用，或者如下所示用[transformers库](https://github.com/huggingface/transformers)调用，\n模型自动下载到本机路径：`~/.cache/huggingface/transformers`\n- `w2v-light-tencent-chinese`是通过gensim加载的Word2Vec模型，使用腾讯词向量计算各字词的词向量，句子向量通过单词词\n向量取平均值得到，模型自动下载到本机路径：`~/.text2vec/datasets/light_Tencent_AILab_ChineseEmbedding.bin`\n- `text2vec`支持多卡推理(计算文本向量): [examples/computing_embeddings_multi_gpu_demo.py](https://github.com/shibing624/text2vec/blob/master/examples/computing_embeddings_multi_gpu_demo.py)\n\n#### Usage (HuggingFace Transformers)\nWithout [text2vec](https://github.com/shibing624/text2vec), you can use the model like this: \n\nFirst, you pass your input through the transformer model, then you have to apply the right pooling-operation on-top of the contextualized word embeddings.\n\nexample: [examples/use_origin_transformers_demo.py](https://github.com/shibing624/text2vec/blob/master/examples/use_origin_transformers_demo.py)\n\n```python\nimport os\nimport torch\nfrom transformers import AutoTokenizer, AutoModel\n\nos.environ[\"KMP_DUPLICATE_LIB_OK\"] = \"TRUE\"\n\n\n# Mean Pooling - Take attention mask into account for correct averaging\ndef mean_pooling(model_output, attention_mask):\n    token_embeddings = model_output[0]  # First element of model_output contains all token embeddings\n    input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()\n    return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)\n\n\n# Load model from HuggingFace Hub\ntokenizer = AutoTokenizer.from_pretrained('shibing624/text2vec-base-chinese')\nmodel = AutoModel.from_pretrained('shibing624/text2vec-base-chinese')\nsentences = ['如何更换花呗绑定银行卡', '花呗更改绑定银行卡']\n# Tokenize sentences\nencoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')\n\n# Compute token embeddings\nwith torch.no_grad():\n    model_output = model(**encoded_input)\n# Perform pooling. In this case, max pooling.\nsentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])\nprint(\"Sentence embeddings:\")\nprint(sentence_embeddings)\n```\n\n#### Usage (sentence-transformers)\n[sentence-transformers](https://github.com/UKPLab/sentence-transformers) is a popular library to compute dense vector representations for sentences.\n\nInstall sentence-transformers:\n```shell\npip install -U sentence-transformers\n```\nThen load model and predict:\n```python\nfrom sentence_transformers import SentenceTransformer\n\nm = SentenceTransformer(\"shibing624/text2vec-base-chinese\")\nsentences = ['如何更换花呗绑定银行卡', '花呗更改绑定银行卡']\n\nsentence_embeddings = m.encode(sentences)\nprint(\"Sentence embeddings:\")\nprint(sentence_embeddings)\n```\n\n#### `Word2Vec`词向量\n\n提供`Word2Vec`词向量，轻量版腾讯词向量`light_Tencent_AILab_ChineseEmbedding.bin`，二进制文件，111M，是简化后的高频143613个词，每个词向量还是200维（跟原版一样），运行程序，自动下载到 `~/.text2vec/datasets/light_Tencent_AILab_ChineseEmbedding.bin`\n\n模型地址：[Modelscope](https://modelscope.cn/models/lili666/text2vec-word2vec-tencent-chinese/summary) | [百度云盘-密码:tawe](https://pan.baidu.com/s/1La4U4XNFe8s5BJqxPQpeiQ) | [谷歌云盘](https://drive.google.com/u/0/uc?id=1iQo9tBb2NgFOBxx0fA16AZpSgc-bG_Rp\u0026export=download)\n\n### 命令行模式（CLI）\n\n支持批量获取文本向量\n\ncode: [cli.py](https://github.com/shibing624/text2vec/blob/master/text2vec/cli.py)\n\n```\n\u003e text2vec -h                                    \nusage: text2vec [-h] --input_file INPUT_FILE [--output_file OUTPUT_FILE] [--model_type MODEL_TYPE] [--model_name MODEL_NAME] [--encoder_type ENCODER_TYPE]\n                [--batch_size BATCH_SIZE] [--max_seq_length MAX_SEQ_LENGTH] [--chunk_size CHUNK_SIZE] [--device DEVICE]\n                [--show_progress_bar SHOW_PROGRESS_BAR] [--normalize_embeddings NORMALIZE_EMBEDDINGS]\n\ntext2vec cli\n\noptional arguments:\n  -h, --help            show this help message and exit\n  --input_file INPUT_FILE\n                        input file path, text file, required\n  --output_file OUTPUT_FILE\n                        output file path, output csv file, default text_embs.csv\n  --model_type MODEL_TYPE\n                        model type: sentencemodel, word2vec, default sentencemodel\n  --model_name MODEL_NAME\n                        model name or path, default shibing624/text2vec-base-chinese\n  --encoder_type ENCODER_TYPE\n                        encoder type: MEAN, CLS, POOLER, FIRST_LAST_AVG, LAST_AVG, default MEAN\n  --batch_size BATCH_SIZE\n                        batch size, default 32\n  --max_seq_length MAX_SEQ_LENGTH\n                        max sequence length, default 256\n  --chunk_size CHUNK_SIZE\n                        chunk size to save partial results, default 1000\n  --device DEVICE       device: cpu, cuda, default None\n  --show_progress_bar SHOW_PROGRESS_BAR\n                        show progress bar, default True\n  --normalize_embeddings NORMALIZE_EMBEDDINGS\n                        normalize embeddings, default False\n  --multi_gpu MULTI_GPU\n                        multi gpu, default False\n```\n\nrun：\n\n```shell\npip install text2vec -U\ntext2vec --input_file input.txt --output_file out.csv --batch_size 128 --multi_gpu True\n```\n\n\u003e 输入文件（required）：`input.txt`，format：一句话一行的句子文本。\n\n## 下游任务\n### 1. 句子相似度计算\n\nexample: [examples/semantic_text_similarity_demo.py](https://github.com/shibing624/text2vec/blob/master/examples/semantic_text_similarity_demo.py)\n\n```python\nimport sys\n\nsys.path.append('..')\nfrom text2vec import Similarity\n\n# Two lists of sentences\nsentences1 = ['如何更换花呗绑定银行卡',\n              'The cat sits outside',\n              'A man is playing guitar',\n              'The new movie is awesome']\n\nsentences2 = ['花呗更改绑定银行卡',\n              'The dog plays in the garden',\n              'A woman watches TV',\n              'The new movie is so great']\n\nsim_model = Similarity()\nfor i in range(len(sentences1)):\n    for j in range(len(sentences2)):\n        score = sim_model.get_score(sentences1[i], sentences2[j])\n        print(\"{} \\t\\t {} \\t\\t Score: {:.4f}\".format(sentences1[i], sentences2[j], score))\n```\n\noutput:\n```shell\n如何更换花呗绑定银行卡 \t\t 花呗更改绑定银行卡 \t\t Score: 0.9477\n如何更换花呗绑定银行卡 \t\t The dog plays in the garden \t\t Score: -0.1748\n如何更换花呗绑定银行卡 \t\t A woman watches TV \t\t Score: -0.0839\n如何更换花呗绑定银行卡 \t\t The new movie is so great \t\t Score: -0.0044\nThe cat sits outside \t\t 花呗更改绑定银行卡 \t\t Score: -0.0097\nThe cat sits outside \t\t The dog plays in the garden \t\t Score: 0.1908\nThe cat sits outside \t\t A woman watches TV \t\t Score: -0.0203\nThe cat sits outside \t\t The new movie is so great \t\t Score: 0.0302\nA man is playing guitar \t\t 花呗更改绑定银行卡 \t\t Score: -0.0010\nA man is playing guitar \t\t The dog plays in the garden \t\t Score: 0.1062\nA man is playing guitar \t\t A woman watches TV \t\t Score: 0.0055\nA man is playing guitar \t\t The new movie is so great \t\t Score: 0.0097\nThe new movie is awesome \t\t 花呗更改绑定银行卡 \t\t Score: 0.0302\nThe new movie is awesome \t\t The dog plays in the garden \t\t Score: -0.0160\nThe new movie is awesome \t\t A woman watches TV \t\t Score: 0.1321\nThe new movie is awesome \t\t The new movie is so great \t\t Score: 0.9591\n```\n\n\u003e 句子余弦相似度值`score`范围是[-1, 1]，值越大越相似。\n\n### 2. 文本匹配搜索\n\n一般在文档候选集中找与query最相似的文本，常用于QA场景的问句相似匹配、文本相似检索等任务。\n\n\nexample: [examples/semantic_search_demo.py](https://github.com/shibing624/text2vec/blob/master/examples/semantic_search_demo.py)\n\n```python\nimport sys\n\nsys.path.append('..')\nfrom text2vec import SentenceModel, cos_sim, semantic_search\n\nembedder = SentenceModel()\n\n# Corpus with example sentences\ncorpus = [\n    '花呗更改绑定银行卡',\n    '我什么时候开通了花呗',\n    'A man is eating food.',\n    'A man is eating a piece of bread.',\n    'The girl is carrying a baby.',\n    'A man is riding a horse.',\n    'A woman is playing violin.',\n    'Two men pushed carts through the woods.',\n    'A man is riding a white horse on an enclosed ground.',\n    'A monkey is playing drums.',\n    'A cheetah is running behind its prey.'\n]\ncorpus_embeddings = embedder.encode(corpus)\n\n# Query sentences:\nqueries = [\n    '如何更换花呗绑定银行卡',\n    'A man is eating pasta.',\n    'Someone in a gorilla costume is playing a set of drums.',\n    'A cheetah chases prey on across a field.']\n\nfor query in queries:\n    query_embedding = embedder.encode(query)\n    hits = semantic_search(query_embedding, corpus_embeddings, top_k=5)\n    print(\"\\n\\n======================\\n\\n\")\n    print(\"Query:\", query)\n    print(\"\\nTop 5 most similar sentences in corpus:\")\n    hits = hits[0]  # Get the hits for the first query\n    for hit in hits:\n        print(corpus[hit['corpus_id']], \"(Score: {:.4f})\".format(hit['score']))\n```\noutput:\n```shell\nQuery: 如何更换花呗绑定银行卡\nTop 5 most similar sentences in corpus:\n花呗更改绑定银行卡 (Score: 0.9477)\n我什么时候开通了花呗 (Score: 0.3635)\nA man is eating food. (Score: 0.0321)\nA man is riding a horse. (Score: 0.0228)\nTwo men pushed carts through the woods. (Score: 0.0090)\n\n======================\nQuery: A man is eating pasta.\nTop 5 most similar sentences in corpus:\nA man is eating food. (Score: 0.6734)\nA man is eating a piece of bread. (Score: 0.4269)\nA man is riding a horse. (Score: 0.2086)\nA man is riding a white horse on an enclosed ground. (Score: 0.1020)\nA cheetah is running behind its prey. (Score: 0.0566)\n\n======================\nQuery: Someone in a gorilla costume is playing a set of drums.\nTop 5 most similar sentences in corpus:\nA monkey is playing drums. (Score: 0.8167)\nA cheetah is running behind its prey. (Score: 0.2720)\nA woman is playing violin. (Score: 0.1721)\nA man is riding a horse. (Score: 0.1291)\nA man is riding a white horse on an enclosed ground. (Score: 0.1213)\n\n======================\nQuery: A cheetah chases prey on across a field.\nTop 5 most similar sentences in corpus:\nA cheetah is running behind its prey. (Score: 0.9147)\nA monkey is playing drums. (Score: 0.2655)\nA man is riding a horse. (Score: 0.1933)\nA man is riding a white horse on an enclosed ground. (Score: 0.1733)\nA man is eating food. (Score: 0.0329)\n```\n\n \n\n## 下游任务支持库\n**similarities库[推荐]**\n\n文本相似度计算和文本匹配搜索任务，推荐使用 [similarities库](https://github.com/shibing624/similarities) ，兼容本项目release的\nWord2vec、SBERT、Cosent类语义匹配模型，还支持亿级图文搜索，支持**文本语义去重**，**图片去重**等功能。\n\n安装：\n```pip install -U similarities```\n\n句子相似度计算：\n```python\nfrom similarities import BertSimilarity\n\nm = BertSimilarity()\nr = m.similarity('如何更换花呗绑定银行卡', '花呗更改绑定银行卡')\nprint(f\"similarity score: {float(r)}\")  # similarity score: 0.855146050453186\n```\n\n## Models\n\n### CoSENT model\n\nCoSENT（Cosine Sentence）文本匹配模型，在Sentence-BERT上改进了CosineRankLoss的句向量方案\n\n\nNetwork structure:\n\nTraining:\n\n\u003cimg src=\"docs/cosent_train.png\" width=\"300\" /\u003e\n\n\nInference:\n\n\u003cimg src=\"docs/inference.png\" width=\"300\" /\u003e\n\n#### CoSENT 监督模型\n训练和预测CoSENT模型：\n\n- 在中文STS-B数据集训练和评估`CoSENT`模型\n\nexample: [examples/training_sup_text_matching_model.py](https://github.com/shibing624/text2vec/blob/master/examples/training_sup_text_matching_model.py)\n\n```shell\ncd examples\npython training_sup_text_matching_model.py --model_arch cosent --do_train --do_predict --num_epochs 10 --model_name hfl/chinese-macbert-base --output_dir ./outputs/STS-B-cosent\n```\n\n- 在蚂蚁金融匹配数据集ATEC上训练和评估`CoSENT`模型\n\n支持这些中文匹配数据集的使用：'ATEC', 'STS-B', 'BQ', 'LCQMC', 'PAWSX'，具体参考HuggingFace datasets [https://huggingface.co/datasets/shibing624/nli_zh](https://huggingface.co/datasets/shibing624/nli_zh)\n```shell\npython training_sup_text_matching_model.py --task_name ATEC --model_arch cosent --do_train --do_predict --num_epochs 10 --model_name hfl/chinese-macbert-base --output_dir ./outputs/ATEC-cosent\n```\n\n- 在自有中文数据集上训练模型\n\nexample: [examples/training_sup_text_matching_model_mydata.py](https://github.com/shibing624/text2vec/blob/master/examples/training_sup_text_matching_model_mydata.py)\n\n单卡训练：\n```shell\nCUDA_VISIBLE_DEVICES=0 python training_sup_text_matching_model_mydata.py --do_train --do_predict\n```\n\n多卡训练：\n```shell\nCUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2  training_sup_text_matching_model_mydata.py --do_train --do_predict --output_dir outputs/STS-B-text2vec-macbert-v1 --batch_size 64 --bf16 --data_parallel \n```\n\n训练集格式参考[examples/data/STS-B/STS-B.valid.data](https://github.com/shibing624/text2vec/blob/master/examples/data/STS-B/STS-B.valid.data)\n\n```shell\nsentence1   sentence2   label\n一个女孩在给她的头发做发型。\t一个女孩在梳头。\t2\n一群男人在海滩上踢足球。\t一群男孩在海滩上踢足球。\t3\n一个女人在测量另一个女人的脚踝。\t女人测量另一个女人的脚踝。\t5\n```\n\n`label`可以是0，1标签，0代表两个句子不相似，1代表相似；也可以是0-5的评分，评分越高，表示两个句子越相似。模型都能支持。\n\n\n- 在英文STS-B数据集训练和评估`CoSENT`模型\n\nexample: [examples/training_sup_text_matching_model_en.py](https://github.com/shibing624/text2vec/blob/master/examples/training_sup_text_matching_model_en.py)\n\n```shell\ncd examples\npython training_sup_text_matching_model_en.py --model_arch cosent --do_train --do_predict --num_epochs 10 --model_name bert-base-uncased  --output_dir ./outputs/STS-B-en-cosent\n```\n\n#### CoSENT 无监督模型\n- 在英文NLI数据集训练`CoSENT`模型，在STS-B测试集评估效果\n\nexample: [examples/training_unsup_text_matching_model_en.py](https://github.com/shibing624/text2vec/blob/master/examples/training_unsup_text_matching_model_en.py)\n\n```shell\ncd examples\npython training_unsup_text_matching_model_en.py --model_arch cosent --do_train --do_predict --num_epochs 10 --model_name bert-base-uncased --output_dir ./outputs/STS-B-en-unsup-cosent\n```\n\n\n### Sentence-BERT model\n\nSentence-BERT文本匹配模型，表征式句向量表示方案\n\nNetwork structure:\n\nTraining:\n\n\u003cimg src=\"docs/sbert_train.png\" width=\"300\" /\u003e\n\n\nInference:\n\n\u003cimg src=\"docs/sbert_inference.png\" width=\"300\" /\u003e\n\n#### SentenceBERT 监督模型\n- 在中文STS-B数据集训练和评估`SBERT`模型\n\nexample: [examples/training_sup_text_matching_model.py](https://github.com/shibing624/text2vec/blob/master/examples/training_sup_text_matching_model.py)\n\n```shell\ncd examples\npython training_sup_text_matching_model.py --model_arch sentencebert --do_train --do_predict --num_epochs 10 --model_name hfl/chinese-macbert-base --output_dir ./outputs/STS-B-sbert\n```\n- 在英文STS-B数据集训练和评估`SBERT`模型\n\nexample: [examples/training_sup_text_matching_model_en.py](https://github.com/shibing624/text2vec/blob/master/examples/training_sup_text_matching_model_en.py)\n\n```shell\ncd examples\npython training_sup_text_matching_model_en.py --model_arch sentencebert --do_train --do_predict --num_epochs 10 --model_name bert-base-uncased --output_dir ./outputs/STS-B-en-sbert\n```\n\n#### SentenceBERT 无监督模型\n- 在英文NLI数据集训练`SBERT`模型，在STS-B测试集评估效果\n\nexample: [examples/training_unsup_text_matching_model_en.py](https://github.com/shibing624/text2vec/blob/master/examples/training_unsup_text_matching_model_en.py)\n\n```shell\ncd examples\npython training_unsup_text_matching_model_en.py --model_arch sentencebert --do_train --do_predict --num_epochs 10 --model_name bert-base-uncased --output_dir ./outputs/STS-B-en-unsup-sbert\n```\n\n### BERT-Match model\nBERT文本匹配模型，原生BERT匹配网络结构，交互式句向量匹配模型\n\nNetwork structure:\n\nTraining and inference:\n\n\u003cimg src=\"docs/bert-fc-train.png\" width=\"300\" /\u003e\n\n训练脚本同上[examples/training_sup_text_matching_model.py](https://github.com/shibing624/text2vec/blob/master/examples/training_sup_text_matching_model.py)。\n\n\n\n### BGE model\n\n#### BGE 监督模型\n- 在中文STS-B数据集训练和评估`BGE`模型\n\nexample: [examples/training_bge_model_mydata.py](https://github.com/shibing624/text2vec/blob/master/examples/training_bge_model_mydata.py)\n\n```shell\ncd examples\npython training_bge_model_mydata.py --model_arch bge --do_train --do_predict --num_epochs 4 --output_dir ./outputs/STS-B-bge-v1 --batch_size 4 --save_model_every_epoch --bf16\n```\n\n- 自建BGE训练集\n\nBGE模型微调训练，使用对比学习训练模型，输入数据的格式是一个三元组' (query, positive, negative) '\n\n```shell\ncd examples/data\npython build_zh_bge_dataset.py\npython hard_negatives_mine.py\n```\n1. `build_zh_bge_dataset.py` 基于中文STS-B生成三元组训练集，格式如下：\n```json lines\n{\"query\":\"一个男人正在往锅里倒油。\",\"pos\":[\"一个男人正在往锅里倒油。\"],\"neg\":[\"亲俄军队进入克里米亚乌克兰海军基地\",\"配有木制家具的优雅餐厅。\",\"马雅瓦蒂要求总统统治查谟和克什米尔\",\"非典还夺去了多伦多地区44人的生命，其中包括两名护士和一名医生。\",\"在一次采访中，身为犯罪学家的希利说，这里和全国各地的许多议员都对死刑抱有戒心。\",\"豚鼠吃胡萝卜。\",\"狗嘴里叼着一根棍子在水中游泳。\",\"拉里·佩奇说Android很重要，不是关键\",\"法国、比利时、德国、瑞典、意大利和英国为印度计划向缅甸出售的先进轻型直升机提供零部件和技术。\",\"巴林赛马会在动乱中进行\"]}\n```\n2. `hard_negatives_mine.py` 使用faiss相似匹配，挖掘难负例。\n\n\n### 模型蒸馏（Model Distillation）\n\n由于text2vec训练的模型可以使用[sentence-transformers](https://github.com/UKPLab/sentence-transformers)库加载，此处复用其模型蒸馏方法[distillation](https://github.com/UKPLab/sentence-transformers/tree/master/examples/training/distillation)。\n\n1. 模型降维，参考[dimensionality_reduction.py](https://github.com/UKPLab/sentence-transformers/blob/master/examples/training/distillation/dimensionality_reduction.py)使用PCA对模型输出embedding降维，可减少milvus等向量检索数据库的存储压力，还能轻微提升模型效果。\n2. 模型蒸馏，参考[model_distillation.py](https://github.com/UKPLab/sentence-transformers/blob/master/examples/training/distillation/model_distillation.py)使用蒸馏方法，将Teacher大模型蒸馏到更少layers层数的student模型中，在权衡效果的情况下，可大幅提升模型预测速度。\n\n### 模型部署\n\n提供两种部署模型，搭建服务的方法： 1）基于Jina搭建gRPC服务【推荐】；2）基于FastAPI搭建原生Http服务。\n\n#### Jina服务\n采用C/S模式搭建高性能服务，支持docker云原生，gRPC/HTTP/WebSocket，支持多个模型同时预测，GPU多卡处理。\n\n- 安装：\n```pip install jina```\n\n- 启动服务：\n\nexample: [examples/jina_server_demo.py](examples/jina_server_demo.py)\n```python\nfrom jina import Flow\n\nport = 50001\nf = Flow(port=port).add(\n    uses='jinahub://Text2vecEncoder',\n    uses_with={'model_name': 'shibing624/text2vec-base-chinese'}\n)\n\nwith f:\n    # backend server forever\n    f.block()\n```\n\n该模型预测方法（executor）已经上传到[JinaHub](https://hub.jina.ai/executor/eq45c9uq)，里面包括docker、k8s部署方法。\n\n- 调用服务：\n\n\n```python\nfrom jina import Client\nfrom docarray import Document, DocumentArray\n\nport = 50001\n\nc = Client(port=port)\n\ndata = ['如何更换花呗绑定银行卡',\n        '花呗更改绑定银行卡']\nprint(\"data:\", data)\nprint('data embs:')\nr = c.post('/', inputs=DocumentArray([Document(text='如何更换花呗绑定银行卡'), Document(text='花呗更改绑定银行卡')]))\nprint(r.embeddings)\n```\n\n批量调用方法见example: [examples/jina_client_demo.py](https://github.com/shibing624/text2vec/blob/master/examples/jina_client_demo.py)\n\n\n#### FastAPI服务\n\n- 安装：\n```pip install fastapi uvicorn```\n\n- 启动服务：\n\nexample: [examples/fastapi_server_demo.py](https://github.com/shibing624/text2vec/blob/master/examples/fastapi_server_demo.py)\n```shell\ncd examples\npython fastapi_server_demo.py\n```\n\n- 调用服务：\n```shell\ncurl -X 'GET' \\\n  'http://0.0.0.0:8001/emb?q=hello' \\\n  -H 'accept: application/json'\n```\n\n\n## Dataset\n\n- 本项目release的数据集：\n\n| Dataset                    | Introduce                                                                | Download Link                                                                                                                                                                                                                                                                                         |\n|:---------------------------|:-------------------------------------------------------------------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| shibing624/nli-zh-all      | 中文语义匹配数据合集，整合了文本推理，相似，摘要，问答，指令微调等任务的820万高质量数据，并转化为匹配格式数据集                | [https://huggingface.co/datasets/shibing624/nli-zh-all](https://huggingface.co/datasets/shibing624/nli-zh-all)                                                                                                                                                                                        |\n| shibing624/snli-zh         | 中文SNLI和MultiNLI数据集，翻译自英文SNLI和MultiNLI                                    | [https://huggingface.co/datasets/shibing624/snli-zh](https://huggingface.co/datasets/shibing624/snli-zh)                                                                                                                                                                                              |\n| shibing624/nli_zh          | 中文语义匹配数据集，整合了中文ATEC、BQ、LCQMC、PAWSX、STS-B共5个任务的数据集                        | [https://huggingface.co/datasets/shibing624/nli_zh](https://huggingface.co/datasets/shibing624/nli_zh) \u003c/br\u003e or \u003c/br\u003e [百度网盘(提取码:qkt6)](https://pan.baidu.com/s/1d6jSiU1wHQAEMWJi7JJWCQ) \u003c/br\u003e or \u003c/br\u003e [github](https://github.com/shibing624/text2vec/releases/download/1.1.2/senteval_cn.zip) \u003c/br\u003e |\n| shibing624/sts-sohu2021    | 中文语义匹配数据集，2021搜狐校园文本匹配算法大赛数据集                                            | [https://huggingface.co/datasets/shibing624/sts-sohu2021](https://huggingface.co/datasets/shibing624/sts-sohu2021)                                                                                                                                                                                    |\n| ATEC                       | 中文ATEC数据集，蚂蚁金服Q-Qpair数据集                                                 | [ATEC](https://github.com/IceFlameWorm/NLP_Datasets/tree/master/ATEC)                                                                                                                                                                                                                                 |\n| BQ                         | 中文BQ(Bank Question)数据集，银行Q-Qpair数据集                                      | [BQ](http://icrc.hitsz.edu.cn/info/1037/1162.htm)                                                                                                                                                                                                                                                     |\n| LCQMC                      | 中文LCQMC(large-scale Chinese question matching corpus)数据集，Q-Qpair数据集      | [LCQMC](http://icrc.hitsz.edu.cn/Article/show/171.html)                                                                                                                                                                                                                                               |\n| PAWSX                      | 中文PAWS(Paraphrase Adversaries from Word Scrambling)数据集，Q-Qpair数据集        | [PAWSX](https://arxiv.org/abs/1908.11828)                                                                                                                                                                                                                                                             |\n| STS-B                      | 中文STS-B数据集，中文自然语言推理数据集，从英文STS-B翻译为中文的数据集                                 | [STS-B](https://github.com/pluto-junzeng/CNSD)                                                                                                                                                                                                                                                        |\n\n\n常用英文匹配数据集：\n\n- 英文匹配数据集：multi_nli: https://huggingface.co/datasets/multi_nli\n- 英文匹配数据集：snli: https://huggingface.co/datasets/snli\n- https://huggingface.co/datasets/metaeval/cnli\n- https://huggingface.co/datasets/mteb/stsbenchmark-sts\n- https://huggingface.co/datasets/JeremiahZ/simcse_sup_nli\n- https://huggingface.co/datasets/MoritzLaurer/multilingual-NLI-26lang-2mil7\n\n\n数据集使用示例：\n```shell\npip install datasets\n```\n\n```python\nfrom datasets import load_dataset\n\ndataset = load_dataset(\"shibing624/nli_zh\", \"STS-B\") # ATEC or BQ or LCQMC or PAWSX or STS-B\nprint(dataset)\nprint(dataset['test'][0])\n```\n\noutput:\n```shell\nDatasetDict({\n    train: Dataset({\n        features: ['sentence1', 'sentence2', 'label'],\n        num_rows: 5231\n    })\n    validation: Dataset({\n        features: ['sentence1', 'sentence2', 'label'],\n        num_rows: 1458\n    })\n    test: Dataset({\n        features: ['sentence1', 'sentence2', 'label'],\n        num_rows: 1361\n    })\n})\n{'sentence1': '一个女孩在给她的头发做发型。', 'sentence2': '一个女孩在梳头。', 'label': 2}\n```\n\n## Contact\n\n- Issue(建议)：[![GitHub issues](https://img.shields.io/github/issues/shibing624/text2vec.svg)](https://github.com/shibing624/text2vec/issues)\n- 邮件我：xuming: xuming624@qq.com\n- 微信我：加我*微信号：xuming624, 备注：姓名-公司-NLP* 进NLP交流群。\n\n\u003cimg src=\"docs/wechat.jpeg\" width=\"200\" /\u003e\n\n\n## Citation\n\n如果你在研究中使用了text2vec，请按如下格式引用：\n\nAPA:\n```latex\nXu, M. Text2vec: Text to vector toolkit (Version 1.1.2) [Computer software]. https://github.com/shibing624/text2vec\n```\n\nBibTeX:\n```latex\n@misc{Text2vec,\n  author = {Ming Xu},\n  title = {Text2vec: Text to vector toolkit},\n  year = {2023},\n  publisher = {GitHub},\n  journal = {GitHub repository},\n  howpublished = {\\url{https://github.com/shibing624/text2vec}},\n}\n```\n\n## License\n\n\n授权协议为 [The Apache License 2.0](LICENSE)，可免费用做商业用途。请在产品说明中附加text2vec的链接和授权协议。\n\n\n## Contribute\n项目代码还很粗糙，如果大家对代码有所改进，欢迎提交回本项目，在提交之前，注意以下两点：\n\n - 在`tests`添加相应的单元测试\n - 使用`python -m pytest -v`来运行所有单元测试，确保所有单测都是通过的\n\n之后即可提交PR。\n\n## References\n- [将句子表示为向量（上）：无监督句子表示学习（sentence embedding）](https://www.cnblogs.com/llhthinker/p/10335164.html)\n- [将句子表示为向量（下）：无监督句子表示学习（sentence embedding）](https://www.cnblogs.com/llhthinker/p/10341841.html)\n- [A Simple but Tough-to-Beat Baseline for Sentence Embeddings[Sanjeev Arora and Yingyu Liang and Tengyu Ma, 2017]](https://openreview.net/forum?id=SyK00v5xx)\n- [四种计算文本相似度的方法对比[Yves Peirsman]](https://zhuanlan.zhihu.com/p/37104535)\n- [Improvements to BM25 and Language Models Examined](http://www.cs.otago.ac.nz/homepages/andrew/papers/2014-2.pdf)\n- [CoSENT：比Sentence-BERT更有效的句向量方案](https://kexue.fm/archives/8847)\n- [谈谈文本匹配和多轮检索](https://zhuanlan.zhihu.com/p/111769969)\n- [Sentence-transformers](https://www.sbert.net/examples/applications/computing-embeddings/README.html)\n- [One Embedder, Any Task: Instruction-Finetuned Text Embeddings](https://arxiv.org/abs/2212.09741)\n","funding_links":[],"categories":["Python","深度学习大类","文本匹配 文本检索 文本相似度"],"sub_categories":["MLSYS","其他_文本生成、文本对话"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fshibing624%2Ftext2vec","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fshibing624%2Ftext2vec","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fshibing624%2Ftext2vec/lists"}