环境
python -m venv text2vec-env
source text2vec-env/bin/activatepip install -U text2vec
安装
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
下载模型
from text2vec import SentenceModel
# 示例:中文文本相似度模型
model = SentenceModel('shibing624/text2vec-base-chinese') # 也支持其他模型
分析语义相似度代码
from text2vec import SentenceModel, cos_sim
# 加载模型
model = SentenceModel("shibing624/text2vec-base-chinese")
# 句子对
sentence_pairs = [
("他去上班了", "他正在上班"),
("苹果公司发布新产品", "小米推出新手机"),
("天气很好", "适合出去散步"),
("我要去买菜", "我打算逛商场"),
]
# 计算相似度
for s1, s2 in sentence_pairs:
vec1 = model.encode(s1)
vec2 = model.encode(s2)
score = cos_sim(vec1, vec2).item() # ✅ 转换为 float
print(f"[{s1}] vs [{s2}] 相似度:{score:.4f}")
结果