我使用聚集聚类技术来聚类车辆数据集。我用了两种方法来计算距离矩阵,一种是使用scipy.space.distance.eucliden,另一种是使用scipy.space-distance_矩阵。因此,根据我的理解,在这两个案例中,我应该得到相同的结果。我想我得到了,但是当我比较两种方法对某些元素的输出时,我得到了错误的输出。有人能解释一下为什么会这样吗?
复制步骤:
!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())
正如你所看到的,尽管当我比较两个矩阵时两个结果是相同的,但对于每个元素我都不能得到正确的结果。
# Comparing
pd.DataFrame(dist_matrix == D).head()
任何帮助都将不胜感激。