nan_euclidean_distances审查:两个零距离,为何拼不出零距离
配图为AI生成概念示意图,非软件截图。
AI写样本检索代码时,可能把“与同一个参照样本距离都为零”当成两条记录等价的证据。如果距离来自nan_euclidean_distances,这个推断可以被三个样本直接推翻:A到B为零,B到C也为零,A到C却大于零。
每一对样本实际比较哪些坐标
本文锁定scikit-learn 1.8.0,使用浮点数组和np.nan。根据官方文档,函数只保留一对样本共同观测到的坐标,再按总维数与共同观测维数的比例缩放平方差,最后开方。
设总维数为p,共同观测坐标集合为J,且J非空,则d(x,y)=√[(p/|J|)Σ(j∈J)(xⱼ−yⱼ)²],其中求和仅遍历共同观测坐标。这里真正需要审查的是:换一对样本,J可能跟着变化。算法没有先把所有样本补成一套固定的完整向量,再统一计算普通欧氏距离。
三行数据构造精确反例
令A=[0,0,缺失],B=[缺失,0,0],C=[1,缺失,0]。A与B只在第二个坐标可比,两者都是0;B与C只在第三个坐标可比,也都是0。A与C却只比较第一个坐标,差值为1。
总维数为3,每一对都只有一个共同观测坐标,所以得到d(A,B)=0、d(B,C)=0、d(A,C)=√3。三角不等式要求最后一个距离不超过前两个之和,这里显然不成立。反例使用默认的squared=False,并不是把平方距离误当成通常距离。
同样,零距离仅说明这一对实际参与比较的坐标一致,不能证明完整记录一致。沿着零距离边合并样本,可能把A和C并入同组;如果业务把这种分组解释为“组内两两零距离”,含义已经错了。
运行代码核对公式与边界
下面既调用公开API,也用直接筛选共同坐标的独立函数重算,避免只凭一张输出表猜测。保存为test.py,按首行安装依赖后运行。
# python -m pip install numpy==2.3.5 scikit-learn==1.8.0
import numpy as np
import sklearn
from numpy.testing import assert_allclose, assert_array_equal
from sklearn.metrics.pairwise import euclidean_distances, nan_euclidean_distances
assert sklearn.__version__ == "1.8.0", sklearn.__version__
def manual_distance(x, y):
common = ~np.isnan(x) & ~np.isnan(y)
count = int(common.sum())
if count == 0:
return np.nan
delta = x[common] - y[common]
return np.sqrt(len(x) / count * np.dot(delta, delta))
points = np.array([
[0.0, 0.0, np.nan], # A
[np.nan, 0.0, 0.0], # B
[1.0, np.nan, 0.0], # C
])
original = points.copy()
distance = nan_euclidean_distances(points, squared=False)
manual = np.array([[manual_distance(x, y) for y in points] for x in points])
expected = np.array([[0, 0, np.sqrt(3)], [0, 0, 0], [np.sqrt(3), 0, 0]])
assert_allclose(distance, manual, rtol=0, atol=1e-12)
assert_allclose(distance, expected, rtol=0, atol=1e-12)
assert_allclose(distance, distance.T)
assert_array_equal(np.isnan(points), np.isnan(original))
assert_allclose(points, original, equal_nan=True)
assert distance[0, 2] > distance[0, 1] + distance[1, 2]
squared = nan_euclidean_distances(points, squared=True)
assert_allclose(squared, distance**2, rtol=0, atol=1e-12)
# No shared observed coordinate gives NaN, not zero or infinity.
no_overlap = np.array([[1.0, np.nan, np.nan], [np.nan, 2.0, np.nan]])
undefined = nan_euclidean_distances(no_overlap)
assert np.isnan(undefined[0, 1]) and np.isnan(undefined[1, 0])
all_missing_self = nan_euclidean_distances(np.full((1, 3), np.nan))[0, 0]
assert np.isnan(all_missing_self)
assert np.isnan(manual_distance(no_overlap[0], no_overlap[1]))
# With complete data, this reduces to ordinary Euclidean distance.
complete = np.array([[0.0, 0.0, 0.0], [3.0, 0.0, 0.0], [3.0, 4.0, 0.0]])
assert_allclose(nan_euclidean_distances(complete), euclidean_distances(complete))
# A shared, fixed missingness pattern uses one common projection and scale.
fixed_mask = complete.copy()
fixed_mask[:, 2] = np.nan
fixed_distance = nan_euclidean_distances(fixed_mask)
projected = euclidean_distances(complete[:, :2]) * np.sqrt(3.0 / 2.0)
assert_allclose(fixed_distance, projected, rtol=0, atol=1e-12)
assert fixed_distance[0, 2] <= fixed_distance[0, 1] + fixed_distance[1, 2]
print(f"NumPy={np.__version__}, scikit-learn={sklearn.__version__}")
print("point_order= ['A', 'B', 'C']")
print("pairwise_distance=", np.round(distance, 6).tolist())
print("AB_plus_BC=", float(distance[0, 1] + distance[1, 2]))
print("AC=", round(float(distance[0, 2]), 6))
print("triangle_inequality_violated=", bool(distance[0, 2] > distance[0, 1] + distance[1, 2]))
print("no_overlap_is_nan=", bool(np.isnan(undefined[0, 1])))
print("all_missing_self_is_nan=", bool(np.isnan(all_missing_self)))
print("fixed_mask_distance=", np.round(fixed_distance, 6).tolist())
print("Pair-specific coordinates, manual formula, NaN boundaries and controls: PASS")实际输出
NumPy=2.3.5, scikit-learn=1.8.0 point_order= ['A', 'B', 'C'] pairwise_distance= [[0.0, 0.0, 1.732051], [0.0, 0.0, 0.0], [1.732051, 0.0, 0.0]] AB_plus_BC= 0.0 AC= 1.732051 triangle_inequality_violated= True no_overlap_is_nan= True all_missing_self_is_nan= True fixed_mask_distance= [[0.0, 3.674235, 6.123724], [3.674235, 0.0, 4.898979], [6.123724, 4.898979, 0.0]] Pair-specific coordinates, manual formula, NaN boundaries and controls: PASS
没有共同坐标时,返回值不是零
两条记录如果没有任何共同观测坐标,函数返回NaN。代码还检查了一条完全缺失的记录与自身比较,同样得到NaN。因此不能无条件假定这类矩阵的对角线全为0,也不能把NaN自动替换成0,再解释成“完全相同”。
NaN在这里表示该对比较没有可用坐标,并非已经测得很近或很远。下游如何处理,应依照任务约定明确决定;随手填成零会把缺乏比较依据变成最强相似信号。
固定缺失模式的对照说明了什么
另一组样本统一缺失第三列,前两列完整。此时所有样本对都使用相同投影,缩放因子恒为√(3/2),结果就是二维欧氏距离整体乘同一常数。代码验证了这个关系及对应三角不等式;完全没有缺失时,也与普通euclidean_distances一致。
对照说明不能把问题简单归咎于“出现了缩放系数”。反例中各对样本依赖的共同坐标不同,才失去了统一完整几何空间的直接解释。这里的零与√3来自明确算式,不是浮点舍入造成的小幅误差。
给距离消费者增加语义测试
版本源码实现了逐对共同观测计数与缩放,这符合接口约定。发现反例并不意味着函数计算错了,而是调用方不能仅凭名字中的euclidean就继承所有普通欧氏空间结论。
如果自定义索引、剪枝或合并逻辑依赖三角不等式或零距离的传递性,应先核对输入距离是否具备这些性质。对称、非负、对角为零仍然不够:主实验矩阵满足这些表面检查,却依然违反三角不等式。
本例证明的是该规则在一般缺失模式下不保证上述性质,并不是说每份含缺失的数据都会违反它。代码审查应保留这种小型对抗用例,区分接口定义、实际观测信息和下游算法所需的数学前提。


