"""Compare norms, cosine rankings and distinct kinds of normalization."""
import json
import platform
import sys
import numpy as np
cases = []
def check(name, inputs, expected, actual):
assert expected == actual, (name, expected, actual)
cases.append(dict(name=name,input=inputs,expected=expected,actual=actual,passed=True))
def unit_rows(values):
values = np.asarray(values,dtype=float)
norms = np.linalg.norm(values,axis=-1,keepdims=True)
if (norms == 0).any():
raise ValueError("cosine requires nonzero rows")
return values/norms
v,w = np.array([-3,4,0]),np.array([-6,8,0])
check("l1_and_l2", v.tolist(), [7,5,5],
[int(np.linalg.norm(v,ord=1)),int(np.linalg.norm(v,ord=2)),int(np.linalg.norm(v))])
check("unit_rows_same_direction", [v.tolist(),w.tolist()], [[-0.6,0.8,0],[-0.6,0.8,0],[1,1]],
[unit_rows(v).tolist(),unit_rows(w).tolist(),np.linalg.norm(unit_rows([v,w]),axis=1).tolist()])
normals = np.array([[3,4],[-4,3],[-3,-4]])
anchor = unit_rows(normals[0])
check("cosine_boundary_directions", normals.tolist(), [1,0,-1],
(unit_rows(normals) @ anchor).round(12).tolist())
check("positive_scale_changes_dot", [v.tolist(),w.tolist()], [25,50,1],
[int(v@v),int(v@w), round(float(unit_rows(v)@unit_rows(w)),12)])
try:
unit_rows([[3,4],[0,0]])
except ValueError as error:
check("zero_row_rejected", [[3,4],[0,0]], "cosine requires nonzero rows", str(error))
else:
raise AssertionError("zero row accepted")
data = np.array([[2,1],[5,0],[-1,2]])
normalized=unit_rows(data)
matrix=normalized@normalized.T
check("batch_cosine_matrix", data.tolist(),
[[1,0.894,0],[0.894,1,-0.447],[0,-0.447,1]], matrix.round(3).tolist())
historical = [[2,5,1,8,3],[3,6,2,7,4],[9,1,8,1,9]]
original_rounds=unit_rows(historical)
check("source_matrix_values_recomputed", historical,
[[1,0.978,0.431],[0.978,1,0.571],[0.431,0.571,1]],
(original_rounds@original_rounds.T).round(3).tolist())
query = np.array([1,0])
docs = np.array([[1,0],[10,8]])
check("ranking_can_change_with_normalization", [query.tolist(),docs.tolist()], [[1,0],[0,1]],
[np.argsort(-(docs@query)).tolist(), np.argsort(-(unit_rows(docs)@unit_rows(query))).tolist()])
distances = np.linalg.norm(normalized-normalized[0],axis=1)**2
check("unit_squared_distance_identity", data.tolist(), [0,0.211145618,2],
distances.round(9).tolist())
assert np.allclose(distances,2-2*matrix[0])
check("squared_penalty_and_gradient", [[3,-2],0.5], [6.5,[3,-2]],
[0.5*float(np.array([3,-2])@np.array([3,-2])),(2*0.5*np.array([3,-2])).tolist()])
torch_version = None
if "--torch" in sys.argv:
import torch
torch.set_num_threads(1)
torch_version=str(torch.__version__)
batch=torch.tensor([[1.,4.],[3.,4.],[5.,4.]])
bn=torch.nn.BatchNorm1d(2,eps=1e-5,affine=False,track_running_stats=False)
native=bn(batch).numpy()
array=batch.numpy()
expected=(array-array.mean(axis=0))/np.sqrt(array.var(axis=0)+1e-5)
check("batch_norm_feature_stats", array.tolist(),
[True,[0,0],[0.999996,0],True],
[bool(np.allclose(native,expected,atol=1e-6)),native.mean(axis=0).round(6).tolist(),
[round(float(x),6) for x in native.var(axis=0)],
bool(np.allclose(np.linalg.norm(native,axis=1),[1.224743,0,1.224743],atol=1e-6))])
cases[-1]["observed_l2_norms"] = np.linalg.norm(native,axis=1).tolist()
adam_results=[]
for cls in (torch.optim.Adam,torch.optim.AdamW):
weight=torch.nn.Parameter(torch.tensor([2.]))
optimizer=cls([weight],lr=0.1,weight_decay=0.1)
weight.grad=torch.zeros_like(weight)
optimizer.step()
adam_results.append(round(float(weight.detach()),2))
check("coupled_decay_and_adamw", [2,0.1,0.1,0], [1.9,1.98], adam_results)
print(json.dumps(dict(version=platform.python_version(),library_versions={"numpy":np.__version__,"torch":torch_version},
cases=cases),ensure_ascii=False))
本例需在 Windows、Python 3.12.14、NumPy 2.5.4、PyTorch 2.10.0+cpu、Chromium。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12.14、NumPy 2.5.4、PyTorch 2.10.0+cpu、Chromium。
入口文件:projects/ai-math-cosine-lab/cosine-numerics.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
cosine-numerics.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14、NumPy 2.5.4、PyTorch 2.10.0+cpu、Chromium。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a43.zip