scipy.spatial.distance.euclidean 和 scipy.spatial.- distance_matrix 没有返回相同的结果

scipy.spatial.distance.euclidean and scipy.spatial.- distance_matrix not returning the same result

我正在使用凝聚聚类技术对车辆数据集进行聚类。我使用了两种方法来计算距离矩阵,一种是使用 scipy.spatial.distance.euclidean 另一种是使用 scipy.spatial-distance_matrix.

所以根据我的理解,我应该在这两种情况下得到相同的结果。我想我得到了,但是当我比较某些元素的两种方法的输出时,我得到的输出是错误的。为什么会这样?

重现步骤:

!wget -O cars_clus.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/cars_clus.csv
filename = 'cars_clus.csv'

#Read csv
pdf = pd.read_csv(filename)

# Clean the data
pdf[[ 'sales', 'resale', 'type', 'price', 'engine_s',
       'horsepow', 'wheelbas', 'width', 'length', 'curb_wgt', 'fuel_cap',
       'mpg', 'lnsales']] = pdf[['sales', 'resale', 'type', 'price', 'engine_s',
       'horsepow', 'wheelbas', 'width', 'length', 'curb_wgt', 'fuel_cap',
       'mpg', 'lnsales']].apply(pd.to_numeric, errors='coerce')
pdf = pdf.dropna()
pdf = pdf.reset_index(drop=True)

# selecting the feature set
featureset = pdf[['engine_s',  'horsepow', 'wheelbas', 'width', 'length', 'curb_wgt', 'fuel_cap', 'mpg']]

# Normalised using minmax
from sklearn.preprocessing import MinMaxScaler
x = featureset.values #returns a numpy array
min_max_scaler = MinMaxScaler()
feature_mtx = min_max_scaler.fit_transform(x)

计算距离矩阵。

#M1 : Using scipy's euclidean

import scipy
leng = feature_mtx.shape[0]
D = scipy.zeros([leng,leng])
for i in range(leng):
    for j in range(leng):
        D[i,j] = scipy.spatial.distance.euclidean(feature_mtx[i], feature_mtx[j])
print(pd.DataFrame(D).head())

# M2 : using scipy.spatial's distance_matrix

from scipy.spatial import distance_matrix
dist_matrix = distance_matrix(feature_mtx,feature_mtx))
print(pd.DataFrame(dist_matrix).head())

如您所见,即使我比较两个矩阵时结果相同,我也无法为每个元素都得到 true

# Comparing

pd.DataFrame(dist_matrix == D).head()

根据 Graipher 的回答,您可以试试这个:

comp = np.isclose(dist_matrix, D)
pd.DataFrame(comp).head()

现在回答您的问题,为什么会发生这种情况。 这是浮点数的内部表示方式造成的问题,它使用固定数量的二进制数字来表示十进制数。一些十进制数不能准确地用二进制表示,从而导致小的舍入误差。 人们常常对这样的结果感到非常惊讶:

>>> 1.2-1.0
0.199999999999999996

这不是错误。这是浮点数的内部表示方式造成的问题,它使用固定数量的二进制数字来表示十进制数。一些十进制数不能准确地用二进制表示,导致小的舍入误差。

浮点数只有 32 或 64 位精度,因此数字在某些点被截断