Python基于similarities實(shí)現(xiàn)文本語義相似度計(jì)算和文本匹配搜索
similarities 實(shí)現(xiàn)了多種相似度計(jì)算、匹配搜索算法,支持文本、圖像,python3開發(fā)。
安裝
pip3 install torch # conda install pytorch pip3 install -U similarities
或
git clone https://github.com/shibing624/similarities.git cd similarities python3 setup.py install
報(bào)錯(cuò)
ChineseCLIPProcessor

Traceback (most recent call last): File “xx\similarity_test1.py”,
line 9, in
from similarities import BertSimilarity File “xx\lib\site-packages\similarities_init_.py”, line 28, in
from similarities.clip_similarity import ClipSimilarity File “xx\lib\site-packages\similarities\clip_similarity.py”, line 16, in
from similarities.clip_module import ClipModule File “xx\lib\site-packages\similarities\clip_module.py”, line 18, in
from transformers import ChineseCLIPProcessor, ChineseCLIPModel, CLIPProcessor, CLIPModel ImportError: cannot import name
‘ChineseCLIPProcessor’ from ‘transformers’
(xx\lib\site-packages\transformers_init_.py)
報(bào)這個(gè)錯(cuò)的原因是transformers版本太低,升級下版本就可以了。
pip install --upgrade transformers
pydantic
另外還缺少pydantic:
pip install pydantic
樣例
# -*- coding: utf-8 -*-
"""
@author:XuMing(xuming624@qq.com)
@description: 文本語義相似度計(jì)算和文本匹配搜索
"""
import sys
sys.path.append('..')
from similarities import BertSimilarity
# 1.Compute cosine similarity between two sentences.
sentences = ['如何更換花唄綁定銀行卡',
'花唄更改綁定銀行卡']
corpus = [
'花唄更改綁定銀行卡',
'我什么時(shí)候開通了花唄',
'俄羅斯警告烏克蘭反對歐盟協(xié)議',
'暴風(fēng)雨掩埋了東北部;新澤西16英寸的降雪',
'中央情報(bào)局局長訪問以色列敘利亞會談',
'人在巴基斯坦基地的炸彈襲擊中喪生',
]
model = BertSimilarity(model_name_or_path="shibing624/text2vec-base-chinese")
print(model)
similarity_score = model.similarity(sentences[0], sentences[1])
print(f"{sentences[0]} vs {sentences[1]}, score: {float(similarity_score):.4f}")
print('-' * 50 + '\n')
# 2.Compute similarity between two list
similarity_scores = model.similarity(sentences, corpus)
print(similarity_scores.numpy())
for i in range(len(sentences)):
for j in range(len(corpus)):
print(f"{sentences[i]} vs {corpus[j]}, score: {similarity_scores.numpy()[i][j]:.4f}")
print('-' * 50 + '\n')
# 3.Semantic Search
model.add_corpus(corpus)
res = model.most_similar(queries=sentences, topn=3)
print(res)
for q_id, id_score_dict in res.items():
print('query:', sentences[q_id])
print("search top 3:")
for corpus_id, s in id_score_dict.items():
print(f'\t{model.corpus[corpus_id]}: {s:.4f}')
print('-' * 50 + '\n')
print(model.search(sentences[0], topn=3))
結(jié)果:
Similarity: BertSimilarity, matching_model: <SentenceModel: shibing624/text2vec-base-chinese, encoder_type: MEAN, max_seq_length: 256, emb_dim: 768>
2024-03-07 20:12:46.481 | DEBUG | text2vec.sentence_model:__init__:80 - Use device: cpu
如何更換花唄綁定銀行卡 vs 花唄更改綁定銀行卡, score: 0.8551
--------------------------------------------------
[[0.8551465 0.72119546 0.14502521 0.21666759 0.25171342 0.08089039]
[0.9999997 0.6807433 0.17136583 0.21621695 0.27282682 0.12791349]]
如何更換花唄綁定銀行卡 vs 花唄更改綁定銀行卡, score: 0.8551
如何更換花唄綁定銀行卡 vs 我什么時(shí)候開通了花唄, score: 0.7212
如何更換花唄綁定銀行卡 vs 俄羅斯警告烏克蘭反對歐盟協(xié)議, score: 0.1450
如何更換花唄綁定銀行卡 vs 暴風(fēng)雨掩埋了東北部;新澤西16英寸的降雪, score: 0.2167
如何更換花唄綁定銀行卡 vs 中央情報(bào)局局長訪問以色列敘利亞會談, score: 0.2517
如何更換花唄綁定銀行卡 vs 人在巴基斯坦基地的炸彈襲擊中喪生, score: 0.0809
花唄更改綁定銀行卡 vs 花唄更改綁定銀行卡, score: 1.0000
花唄更改綁定銀行卡 vs 我什么時(shí)候開通了花唄, score: 0.6807
花唄更改綁定銀行卡 vs 俄羅斯警告烏克蘭反對歐盟協(xié)議, score: 0.1714
花唄更改綁定銀行卡 vs 暴風(fēng)雨掩埋了東北部;新澤西16英寸的降雪, score: 0.2162
花唄更改綁定銀行卡 vs 中央情報(bào)局局長訪問以色列敘利亞會談, score: 0.2728
花唄更改綁定銀行卡 vs 人在巴基斯坦基地的炸彈襲擊中喪生, score: 0.1279
--------------------------------------------------
2024-03-07 20:13:03.429 | INFO | similarities.bert_similarity:add_corpus:108 - Start computing corpus embeddings, new docs: 6
Batches: 100%|██████████| 1/1 [00:10<00:00, 10.45s/it]
2024-03-07 20:13:13.889 | INFO | similarities.bert_similarity:add_corpus:120 - Add 6 docs, total: 6, emb len: 6
{0: {0: 0.8551465272903442, 1: 0.7211954593658447, 4: 0.25171342492103577}, 1: {0: 0.9999997019767761, 1: 0.6807432770729065, 4: 0.27282682061195374}}
query: 如何更換花唄綁定銀行卡
search top 3:
花唄更改綁定銀行卡: 0.8551
我什么時(shí)候開通了花唄: 0.7212
中央情報(bào)局局長訪問以色列敘利亞會談: 0.2517
query: 花唄更改綁定銀行卡
search top 3:
花唄更改綁定銀行卡: 1.0000
我什么時(shí)候開通了花唄: 0.6807
中央情報(bào)局局長訪問以色列敘利亞會談: 0.2728
--------------------------------------------------
{0: {0: 0.8551465272903442, 1: 0.7211954593658447, 4: 0.25171342492103577}}
以上就是Python基于similarities實(shí)現(xiàn)文本語義相似度計(jì)算和文本匹配搜索的詳細(xì)內(nèi)容,更多關(guān)于Python文本相似度計(jì)算的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python打包編譯工具Pyinstaller與Nuitka特性超詳細(xì)對比
應(yīng)用程序開發(fā)完畢,一般都需要對程序進(jìn)行打包后發(fā)布,除開源項(xiàng)目外,很少有發(fā)布源碼的,這篇文章主要介紹了Python打包編譯工具Pyinstaller與Nuitka特性對比的相關(guān)資料,需要的朋友可以參考下2026-03-03
Python+tkinter編寫一個(gè)最近很火的強(qiáng)制表白神器
這篇文章主要為大家詳細(xì)介紹了Python如何通過tkinter編寫一個(gè)最近很火的強(qiáng)制表白神器,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起嘗試一下2023-04-04
Python機(jī)器學(xué)習(xí)之使用Pyecharts制作可視化大屏
pyecharts是一個(gè)用于生成Echarts圖表的Python庫,Echarts是百度開源的一個(gè)數(shù)據(jù)可視化 JS 庫,可以生成一些非??犰诺膱D表,這篇文章主要給大家介紹了關(guān)于Python機(jī)器學(xué)習(xí)之Pyecharts制作可視化大屏的相關(guān)資料,需要的朋友可以參考下2021-10-10
基于Python實(shí)現(xiàn)一個(gè)AI物體識別
計(jì)算機(jī)視覺是其中的一大領(lǐng)域?,應(yīng)用場景也比較多,這篇文章主要為大家詳細(xì)介紹了如何基于Python實(shí)現(xiàn)一個(gè)AI物體識別功能,需要的小伙伴可以了解下2024-11-11
python實(shí)現(xiàn)數(shù)字炸彈游戲程序
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)數(shù)字炸彈游戲程序,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-07-07
Python使用date模塊進(jìn)行日期處理的終極指南
在處理與時(shí)間相關(guān)的數(shù)據(jù)時(shí),Python的date模塊是開發(fā)者最趁手的工具之一,本文將用通俗的語言,結(jié)合真實(shí)案例,帶您掌握date模塊的六大核心功能和使用技巧,需要的可以了解下2025-03-03
python Bamboolib庫加速Pandas數(shù)據(jù)分析過程詳解
這篇文章主要介紹了python Bamboolib庫加速Pandas數(shù)據(jù)分析過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01

