代码之家  ›  专栏  ›  技术社区  ›  Himanshu Poddar

Scipy.Spatial.Distance.Eucliden和Scipy.Spatial.-距离矩阵没有返回相同的结果?

  •  0
  • Himanshu Poddar  · 技术社区  · 7 年前

    我使用聚集聚类技术来聚类车辆数据集。我用了两种方法来计算距离矩阵,一种是使用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())
    

    enter image description here

    # 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())
    

    enter image description here

    正如你所看到的,尽管当我比较两个矩阵时两个结果是相同的,但对于每个元素我都不能得到正确的结果。

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

    enter image description here

    任何帮助都将不胜感激。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Himanshu Poddar    7 年前

    在Graipher Answer的基础上,您可以尝试以下方法:

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

    现在来问你为什么会这样。 它是由浮点数的内部表示引起的问题,浮点数使用固定数量的二进制数字表示十进制数字。一些十进制数字可以用二进制精确表示,从而导致小的舍入误差。 人们经常对这样的结果感到惊讶:

    >>> 1.2-1.0
    0.199999999999999996
    

    它不是一个错误。它是由浮点数的内部表示引起的问题,浮点数使用固定数量的二进制数字表示十进制数字。一些十进制数字可以用二进制精确表示,从而导致小的舍入误差。

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

    推荐文章