如何基于sklearn余弦相似度匹配相关文档
向量检索是目前 RAG匹配文档最重要的实现方式之一,其有效性和性能关系到RAG的可用性。
这里尝试通过sklearn余弦相似计算,示例向量相似度方法匹配文档的过程。
示例过程仅使用numpy、sklearn等最基础手段展示文档匹配过程。
1 向量生成
这里使用ollama部署bge-m3模型生成向量,代码示例如下所示
from langchain_ollama import OllamaEmbeddings
embeddings = OllamaEmbeddings(
base_url="http://localhost:11434",
model="bge-m3")
doc_result = embeddings.embed_documents(
[
"Hi there!",
"Oh, hello!",
"What's your name?",
"My friends call me World",
"Hello World!"
]
);
print(len(doc_result[0]))
bge-m3能生成1024维度的向量,这里使用langchain_ollama访问向量模型。
ollama和langchain均可以无成本直接获取。
参考连接如下
https://blog.csdn.net/liliang199/article/details/153262667
2 相似计算
这里使用sklearn和numpy处理向量并相似度。
sklearn是基础机器学习库,numpy是机器学习经常使用的数据处理工具。
相似计算程序示例如下。
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
candidates = [
"Hi there!",
"Oh, hello!",
"What's your name?",
"My friends call me World",
"Hello World!"
]
question = "tell me your name"
inputs = candidates + [question]
embs = embeddings.embed_documents(inputs)
c_vecs = np.array(embs[:-1])
q_emb = np.array(embs[-1:])
sims = cosine_similarity(q_emb, c_vecs)[0]
indices = sims.argsort()[::-1]
for i, index in enumerate(indices):
print(f"similarity: {sims[i]}, text: {candidates[index]}")
输出如下,cosine准确计算出 "tell me your name"与待选项的相似程度。
与"What's your name?"最相似,相似度为0.62;与“Hello world”相似度最低,得分0.58。
similarity: 0.621278318142269, text: What's your name?
similarity: 0.6078044869667034, text: My friends call me World
similarity: 0.7745126954196969, text: Hi there!
similarity: 0.6450441249466959, text: Oh, hello!
similarity: 0.5852270474647374, text: Hello World!
3 文档匹配
这里使用上述相似度计算方法,尝试匹配与输入问题相似的文档。
具体过程为:
1)计算问题和待匹配文档的向量
2)用余弦相似度的方法计算问题向量和文档向量的相似度,并进行排序
3)然后输出topk结果,依据topk结果进行相似文档匹配
示例代码如下所示。
def get_matched_docs(question, candidates, topk=3):
inputs = candidates + [question]
embs = embeddings.embed_documents(inputs)
c_vecs = np.array(embs[:-1])
q_emb = np.array(embs[-1:])
sims = cosine_similarity(q_emb, c_vecs)[0]
indices = sims.argsort()[::-1]
return [(sims[i], candidates[index])for i, index in enumerate(indices[:topk])]
candidates = [
"Hi there!",
"Oh, hello!",
"What's your name?",
"My friends call me World",
"Hello World!"
]
question = "tell me your name"
topk=3
get_matched_docs(question, candidates, topk=3)
输出示例如下,输出即位匹配的topk相似文档。
[(np.float64(0.621278318142269), "What's your name?"),
(np.float64(0.6078044869667034), 'My friends call me World'),
(np.float64(0.7745126954196969), 'Hi there!')]
这里通过sklearn和numpy,示例相似度文档匹配过程。
在实际生产环境,需要选择更高效可靠的向量库比如Faiss、Chroma、Milvus实现。
reference
---
RAG向量相似度、距离计算方法探索和示例
https://blog.csdn.net/liliang199/article/details/151623063
python调用远程服务器的ollama embedding模型
https://blog.csdn.net/liliang199/article/details/153262667
使用langchain支持openai的向量化embedding
https://zhuanlan.zhihu.com/p/669738297
Python计算余弦相似性(cosine similarity)方法汇总
为武汉地区的开发者提供学习、交流和合作的平台。社区聚集了众多技术爱好者和专业人士,涵盖了多个领域,包括人工智能、大数据、云计算、区块链等。社区定期举办技术分享、培训和活动,为开发者提供更多的学习和交流机会。
更多推荐



所有评论(0)