簡體   English   中英

scipy的pdist函數是否對某些特定索引有特定用途?

[英]Is there a specific use of pdist function of scipy for some particular indexes?

我的問題是關於scipy.spatial.distance的pdist函數的使用。 盡管我必須計算1x64向量與2D數組中存儲的其他百萬個1x64向量中的每一個之間的漢明距離,但是我無法使用pdist來實現。 因為它返回同一2D數組內任意兩個向量之間的漢明距離。 我想知道是否有任何方法可以計算特定索引向量與所有其他向量之間的漢明距離。

這是我當前的代碼,我現在使用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和所有其他漢明距離。 我該怎么辦?

您可以使用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]因此輸入是2D數組(只有一行):

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

如果使用x[index]則會出現錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM