semantic_similarity.py 的默认算分逻辑AI 直接判断(唯一方法)
用户输入: "深度学习" vs "神经网络"
↓
发送给 AI 的 Prompt:
从语意角度,判断【深度学习】和【神经网络】的相似度,从0-1打分,输出json格式
```json
{
"说明": "简明扼要说明理由",
"相似度": 0.0,
}
```
↓
AI 理解语义后返回:
{
"说明": "两者都是人工智能领域的核心概念,深度学习是基于神经网络的...",
"相似度": 0.85
}
text_embedding.py 的默认算分逻辑AI 直接判断 (method="ai_direct")
与 semantic_similarity.py 完全相同!
用户输入: "深度学习" vs "神经网络"
↓
发送给 AI 的 Prompt:
请计算以下两个文本的语义相似度,输出 0-1 之间的分数。
文本A:【深度学习】
文本B:【神经网络】
输出格式:
```json
{
"similarity": 0.0,
"method": "semantic_analysis",
"explanation": "相似度判断的理由"
}
```
↓
AI 返回结果后,转换为兼容格式:
{
"说明": "相似度判断的理由",
"相似度": 0.85
}
除了默认的 AI 直接判断,还支持基于向量的计算方法:
ai_direct (默认,推荐)⭐原理: AI 直接理解语义并打分
优点:
缺点:
适用场景:
示例:
result = await compare_phrases("深度学习", "神经网络", method="ai_direct")
# 相似度: 0.85
# 说明: "两者都是AI领域的核心概念..."
cosine (余弦相似度)原理:
数学公式:
相似度 = cos(θ) = (A·B) / (|A| × |B|)
其中:
- A, B 是两个向量
- A·B 是点积
- |A|, |B| 是向量的模(长度)
取值范围: -1 到 1
优点:
缺点:
适用场景:
示例:
result = await compare_phrases("深度学习", "神经网络", method="cosine", dim=128)
# 相似度: 0.78
# 说明: "基于 cosine 方法计算的向量相似度"
euclidean (欧氏距离)原理:
数学公式:
距离 = √[(a1-b1)² + (a2-b2)² + ... + (an-bn)²]
相似度 = 1 / (1 + 距离) # 归一化到 0-1
取值范围: 0 到 1
优点:
缺点:
适用场景:
示例:
result = await compare_phrases("深度学习", "神经网络", method="euclidean", dim=128)
# 相似度: 0.65
# 说明: "基于 euclidean 方法计算的向量相似度"
manhattan (曼哈顿距离)原理: 类似走城市街道,只能沿坐标轴方向移动
数学公式:
距离 = |a1-b1| + |a2-b2| + ... + |an-bn|
相似度 = 1 / (1 + 距离) # 归一化到 0-1
取值范围: 0 到 1
优点:
缺点:
适用场景:
示例:
result = await compare_phrases("深度学习", "神经网络", method="manhattan", dim=128)
# 相似度: 0.62
# 说明: "基于 manhattan 方法计算的向量相似度"
dot_product (点积)原理: 计算两个向量的点积,用 sigmoid 归一化
数学公式:
点积 = a1×b1 + a2×b2 + ... + an×bn
相似度 = 1 / (1 + e^(-点积)) # sigmoid 归一化
取值范围: 0 到 1
优点:
缺点:
适用场景:
示例:
result = await compare_phrases("深度学习", "神经网络", method="dot_product", dim=128)
# 相似度: 0.71
# 说明: "基于 dot_product 方法计算的向量相似度"
ai_direct > cosine > euclidean ≈ manhattan ≈ dot_product
dot_product > manhattan > euclidean > cosine >> ai_direct
ai_direct (需要调用 AI) >> 向量方法 (首次需要生成向量)
# 测试短语
phrase_a = "深度学习"
phrase_b = "神经网络"
# 不同方法的结果(示例)
┌──────────────┬──────────┬────────────────────────────┐
│ 方法 │ 相似度 │ 说明 │
├──────────────┼──────────┼────────────────────────────┤
│ ai_direct │ 0.850 │ AI 深度理解,最准确 │
│ cosine │ 0.780 │ 向量夹角,次准确 │
│ euclidean │ 0.650 │ 欧氏距离 │
│ manhattan │ 0.620 │ 曼哈顿距离 │
│ dot_product │ 0.710 │ 点积 │
└──────────────┴──────────┴────────────────────────────┘
1. 默认使用 ai_direct ⭐
# 不传 method 参数,默认就是 ai_direct
result = await compare_phrases("深度学习", "神经网络")
原因:
2. 批量计算时可以考虑 cosine
# 如果要计算大量相似度,可以先生成所有向量
model = SentenceModel(dim=128)
# 生成向量(只需一次)
vectors = await model.encode(all_texts)
# 然后用 cosine 快速计算
for i in range(len(all_texts)):
for j in range(i+1, len(all_texts)):
result = await compare_phrases(
all_texts[i], all_texts[j],
method="cosine"
)
semantic_similarity.py{说明, 相似度}text_embedding.py 的 compare_phrases(){说明, 相似度} (完全兼容)ai_direct - AI 判断(默认)⭐cosine - 余弦相似度euclidean - 欧氏距离manhattan - 曼哈顿距离dot_product - 点积ai_direct,不需要指定 methodcosinesemantic_similarity.compare_phrases()