【问题标题】:Is there a specific use of pdist function of scipy for some particular indexes?对于某些特定索引,scipy 的 pdist 函数是否有特定用途?
【发布时间】:2016-08-17 11:22:05
【问题描述】:

我的问题是关于 scipy.spatial.distance 的 pdist 函数的使用。尽管我必须计算 1x64 向量与存储在 2D 数组中的其他数百万个 1x64 向量中的每一个之间的汉明距离,但我无法使用 pdist。因为它返回同一二维数组内任意两个向量之间的汉明距离。我想知道是否有任何方法可以让它计算特定索引向量与所有其他向量之间的汉明距离。

这是我当前的代码,我现在使用 1000x64,因为大数组会出现内存错误。

import numpy as np
from scipy.spatial.distance import pdist


ph = np.load('little.npy')

print pdist(ph, 'hamming').shape

输出是

(499500,)

little.npy 有一个 1000x64 的数组。例如,如果我只想查看 31. vector 和所有其他的汉明距离。我该怎么办?

【问题讨论】:

    标签: python scipy pdist


    【解决方案1】:

    您可以使用cdist。例如,

    In [101]: from scipy.spatial.distance import cdist
    
    In [102]: x
    Out[102]: 
    array([[0, 1, 1, 1, 1, 0, 0, 0],
           [0, 0, 1, 0, 0, 0, 1, 0],
           [0, 0, 0, 1, 1, 1, 0, 0],
           [1, 0, 1, 1, 0, 1, 1, 0],
           [1, 0, 1, 1, 0, 1, 1, 1],
           [0, 1, 0, 1, 0, 0, 0, 1],
           [1, 0, 0, 0, 0, 1, 0, 0],
           [1, 1, 1, 1, 1, 1, 1, 1],
           [1, 1, 0, 0, 1, 1, 1, 0],
           [1, 0, 0, 1, 1, 0, 0, 1]])
    
    In [103]: index = 3
    
    In [104]: cdist(x[index:index+1], x, 'hamming')
    Out[104]: 
    array([[ 0.625,  0.375,  0.5  ,  0.   ,  0.125,  0.75 ,  0.375,  0.375,
             0.5  ,  0.625]])
    

    这给出了索引 3 处的行与所有其他行(包括索引 3 处的行)之间的汉明距离。 结果是一个二维数组,只有一行。您可能想立即拉出该行,因此结果为 1D:

    In [105]: cdist(x[index:index+1], x, 'hamming')[0]
    Out[105]: 
    array([ 0.625,  0.375,  0.5  ,  0.   ,  0.125,  0.75 ,  0.375,  0.375,
            0.5  ,  0.625])
    

    我使用了x[index:index+1] 而不是x[index],所以输入是一个二维数组(只有一行):

    In [106]: x[index:index+1]
    Out[106]: array([[1, 0, 1, 1, 0, 1, 1, 0]])
    

    如果你使用x[index],你会得到一个错误。

    【讨论】:

    • 是的,我发现 cdist 对我正在做的事情非常有用。谢谢!
    猜你喜欢
    • 2011-04-02
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    • 1970-01-01
    • 2021-05-15
    • 2017-12-30
    • 2011-11-26
    • 2017-07-07
    相关资源
    最近更新 更多