"""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()
本例需在 Windows、Python 3.12.14。numpy 2.5.4;sklearn 1.9.1。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12.14。numpy 2.5.4;sklearn 1.9.1。
入口文件:projects/ai-math-cosine-similarity-lab/text-cosine.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
text-cosine.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14。numpy 2.5.4;sklearn 1.9.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a44.zip