蓝色天空网mbsky.com · 知识 · 实践 · 创造AI 数学基础 · 本地阅读预览
教程 / AI / 智能开发 / AI 数学基础

用余弦相似度做文本推荐

用五条中文短文、二值词袋和余弦相似度建立可复查的检索排序。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

同一坐标系里的文本向量

例如搜索无线耳塞时,可把查询和商品说明投到同一组词或特征坐标上,再按分数排列。一般实向量中,同向、垂直、反向对应 1、0、−1。非负词袋只会落在 [0,1],这类分数描述词特征的重合,语义是否相同还需要额外证据。对于同一个向量,乘正数会保留方向。加入新的词可能同时改变模长和方向。

非零向量 a、b 的余弦相似度为 a·b ÷ (‖a‖₂‖b‖₂)。先算各对应坐标乘积的和,再用两向量的欧氏长度作归一化。零向量没有方向,示例约定涉及零向量时返回 0,并保留空查询标志。

二值词袋与中文分词

固定词表及坐标顺序,把已经分好词的短句转成多个 0 或 1 的特征。重复出现仍记 1,句子可同时激活多列。直接用子串查找会让“深度学习”同时命中“学习”。教程复算保留这种旧规则,本站检索例子使用明确的词边界。真实项目也可选择计数词袋、TF-IDF 或稠密嵌入。

运行五条预分词短句,从高到低排列分数。相同分数按输入顺序排列。单独验证无共享坐标得 0、未知词得到空向量。旧例中用 25 列子串词表,前两条按原代码的语料顺序分别约为 0.612372 和 0.566947,“深度学习”一条因包含“学习”仍得到约 0.188982。运行证据包含这三个复算值。

向量检索能说明什么

归一化查询和文档后,内积等于余弦分数。Transformer 的标准缩放点积注意力使用 QKᵀ/√dₖ,随后按需要添加掩码并做 softmax,再对 V 加权。缩放因子取决于键的维度,默认不会分别除以 Q 和 K 向量的模长。程序比较了键向量缩放对两种分数的影响。

余弦分数在检索里的五种用途

用途怎样使用与已核对范围
文本检索查询和文档用同一特征变换,本例对五条记录排序。
偏好匹配可比较用户历史聚合向量与商品向量,候选、反馈和冷启动另行处理。
嵌入检索用模型编码后再比较,能否召回近义表达要靠样本和相关性指标验证。
比较向量比对模型输出可使用相似度,需用独立数据确定适用阈值并验证误差。
召回文档片段先把知识库切片、编码和建索引,以相似度找候选。召回质量与生成事实性分别评估。

检索五条文本并验证零向量和旧例分数

python · 阅读源码
"""Run fixed Chinese text-retrieval examples locally."""
import json
from math import sqrt
import platform

import numpy as np
import sklearn
from sklearn.metrics.pairwise import cosine_similarity


DOCUMENTS = (
    "蓝牙 耳机 续航",
    "耳机 有线 监听",
    "公园 自行车 路线",
    "无线 耳塞 便携",
    "蓝牙 键盘 配对",
)
VOCABULARY = tuple(sorted(set(" ".join(DOCUMENTS).split())))
LOOKUP = {word: pos for pos, word in enumerate(VOCABULARY)}
CASES = []


def vector(tokens):
    features = np.zeros(len(VOCABULARY))
    for token in set(tokens):
        if token in LOOKUP:
            features[LOOKUP[token]] = 1
    return features


def cosine(left, right):
    scale = np.linalg.norm(left) * np.linalg.norm(right)
    return float(np.dot(left, right) / scale) if scale else 0.0


def record(name, operation, inputs, expected, actual):
    assert actual == expected, (name, expected, actual)
    CASES.append(dict(name=name, operation=operation, inputs=inputs,
                      expected=expected, actual=actual, passed=True))


def legacy_scores():
    # Rows encode the word matches observed under the legacy substring rule.
    query = {"我", "python", "学习", "人工智能"}
    rows = [
        {"我", "喜欢", "用", "python", "学习", "机器学习"},
        {"python", "是", "学习", "人工智能", "的", "好", "工具"},
        {"今天", "天气", "很", "好", "适合", "出去", "散步"},
        {"深度学习", "学习", "需要", "大量", "的", "数据", "算力"},
        {"散步", "是", "一种", "很", "好", "的", "放松", "方式"},
    ]
    return [round(len(query & row) / sqrt(len(query) * len(row)), 6) for row in rows]


def main():
    query = vector("蓝牙 耳机".split())
    docs = np.array([vector(row.split()) for row in DOCUMENTS])
    scores = [round(cosine(query, row), 6) for row in docs]
    ranking = sorted(range(len(docs)), key=lambda index: -scores[index])
    record("rank_five_documents", "binary vector encoding and stable ranking",
           {"query": "蓝牙 耳机", "documents": DOCUMENTS},
           [[0, 1, 4, 2, 3], [0.816497, 0.408248, 0.408248, 0.0, 0.0]],
           [ranking, [scores[index] for index in ranking]])
    record("binary_word_features", "repeat a word and ignore one unknown token",
           ["蓝牙", "蓝牙", "未知"], [1, True],
           [int(vector(["蓝牙", "蓝牙", "未知"]).sum()),
            bool(np.array_equal(vector(["蓝牙"]), vector(["蓝牙", "蓝牙", "未知"])))])
    empty = vector(["天文"])
    record("out_of_vocabulary_and_disjoint", "check empty and disjoint queries",
           ["天文", "公园"], [0, 0.0, 0.0],
           [int(empty.sum()), cosine(empty, docs[0]), cosine(vector(["公园"]), docs[0])])
    x, y = np.eye(2)
    record("signed_orthogonal_and_parallel_vectors", "compare same, orthogonal, opposite",
           [[1, 0], [0, 1], [-1, 0]], [1.0, 0.0, -1.0],
           [cosine(x, x), cosine(x, y), cosine(x, -x)])
    record("normalize_removes_positive_scale", "rescale the query and the first document",
           [7, 3], scores[0], round(cosine(7 * query, 3 * docs[0]), 6))
    record("literal_and_semantic_are_distinct", "observe non-overlapping terms in a synonym-like query",
           ["蓝牙 耳机", "无线 耳塞"], 0.0, scores[3])
    pairwise = cosine_similarity(np.array([query, empty]), docs)
    record("library_pairwise_comparison", "compare manual and scikit-learn pairwise scores",
           {"queries": 2, "documents": len(docs)}, [True, True],
           [bool(np.allclose(pairwise[0], scores)), bool(np.all(pairwise[1] == 0))])
    record("legacy_substring_rank_reconciled", "score the audited term memberships from the old example",
           {"dimensions": 25, "document_count": 5}, [0.612372, 0.566947, 0.0, 0.188982, 0.0],
           legacy_scores())
    keys = np.array([[1.0, 1.0], [2.0, 2.0]])
    logits = (keys @ x) / sqrt(len(x))
    record("attention_scores_are_scaled_dot_products", "compare fixed-scale logits and cosine scores",
           {"query": x.tolist(), "keys": keys.tolist()}, [[0.707107, 1.414214], [0.707107, 0.707107]],
           [np.round(logits, 6).tolist(), [round(cosine(x, key), 6) for key in keys]])
    print(json.dumps(dict(version=platform.python_version(), library_versions={
        "numpy": np.__version__, "sklearn": sklearn.__version__}, cases=CASES), ensure_ascii=False))


if __name__ == "__main__":
    main()

预期结果 · 待实际运行核验
  • “蓝牙 耳机”查询的前两条得分分别为 0.816497 和 0.408248。未知词的向量全零。
检索五条文本并验证零向量和旧例分数

所需环境:Windows、Python 3.12.14。numpy 2.5.4;sklearn 1.9.1。

当前源码 SHA256:51093a59342c7045a24b372526c6920d51df2221f6f645b1acf841435422d61f

下载本站示例源码

复跑实验

解压后按 README 运行自编程序。

下载用余弦相似度做文本推荐实验

所需环境:Windows、Python 3.12.14。numpy 2.5.4;sklearn 1.9.1。

ZIP SHA256:633ce8c34abae7d8065a75bbf7454c43a542cc1456daa52bf81277885c9491da

常见错误与边界

  • 先统一词表和分词办法,再比较向量。
  • 将零向量约定、并列顺序和阈值写入检索规则。

练习与解答

把“蓝牙”在同一条文本里写两次,二值特征会如何变化?

展开参考解答

该列仍为 1,其余条件相同时分数也保持相同。

规范与官方依据