2017-07-16 49 views
1

我試圖計算下面的值,並在數組大小不相似時得到錯誤。我知道我可以爲不同大小的數組手動執行此操作,但可以幫助我更正此代碼。ValueError:操作數無法與形狀一起廣播(3,)(6,)

import scipy 
from scipy.stats import pearsonr, spearmanr 
from scipy.spatial import distance 
x = [5,3,2.5] 
y = [4,3,2,4,3.5,4] 
pearsonr(x,y) 
:Error 
scipy.spatial.distance.euclidean(x, y) 
:Error 
spearmanr(x,y) 
:Error 
scipy.spatial.distance.jaccard(x, y) 
:Error 
+0

在這些情況下,'x'和'y'是什麼? – MSeifert

+0

x = [5,3,2.5] y = [4,3,2,4,3.5,4] – Victor

回答

1

對於陣列必須爲2維的距離,即使每個子陣列只包含一個元件,例如:

def make2d(lst): 
    return [[i] for i in lst] 

>>> scipy.spatial.distance.cdist(make2d([5,3,2.5]), make2d([4,3,2,4,3.5,4])) 
array([[ 1. , 2. , 3. , 1. , 1.5, 1. ], 
     [ 1. , 0. , 1. , 1. , 0.5, 1. ], 
     [ 1.5, 0.5, 0.5, 1.5, 1. , 1.5]]) 

可以選擇不同的度量(比如jaccard):

>>> scipy.spatial.distance.cdist(make2d([5,3,2.5]), make2d([4,3,2,4,3.5,4]), metric='jaccard') 
array([[ 1., 1., 1., 1., 1., 1.], 
     [ 1., 0., 1., 1., 1., 1.], 
     [ 1., 1., 1., 1., 1., 1.]]) 

但是對於統計函數,我不知道你想如何工作,這種排序 - 根據定義需要相同長度的數組。您可能需要查閱這些文檔。

相關問題