我有两个来自不同函数的变量,第一个a
是:
<class 'numpy.ndarray'>
(100,)
另外一个b
是:
<class 'numpy.ndarray'>
(100, 1)
如果我尝试通过以下方式关联它们:
from scipy.stats import pearsonr
p, r= pearsonr(a, b)
我得到:
r = max(min(r, 1.0), -1.0)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
我的问题是:
答案 0 :(得分:3)
(100,1)是长度为1的2d行数组,例如= {[[1],[2],[3],[4]]
,第二个是1d数组[1, 2, 3, 4 ]
a1 = np.array([[1],[2],[3],[4]])
a2 = np.array([1, 2, 3, 4 ])
答案 1 :(得分:2)
第一个问题的答案:a
是向量,b
是矩阵。请查看此stackoverflow链接以获取更多详细信息:Difference between numpy.array shape (R, 1) and (R,)
第二个问题的答案:
我认为将一种转换为另一种形式应该可以正常工作。对于您提供的功能,我想它需要向量,因此只需使用b = b.reshape(-1)
重塑b形状即可将其转换为单个尺寸(向量)。请看下面的示例以供参考:
>>> import numpy as np
>>> from scipy.stats import pearsonr
>>> a = np.random.random((100,))
>>> b = np.random.random((100,1))
>>> print(a.shape, b.shape)
(100,) (100, 1)
>>> p, r= pearsonr(a, b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\xyz\Appdata\Local\Continuum\Anaconda3\lib\site-packages\scipy\stats\stats.py", line 3042, in pearsonr
r = max(min(r, 1.0), -1.0)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> b = b.reshape(-1)
>>> p, r= pearsonr(a, b)
>>> print(p, r)
0.10899671932026986 0.280372238354364
答案 2 :(得分:0)
您需要在第一个函数上调用reshape函数.reshape((100,1))
。Reshape将更改np数组的“ shape”属性,这将使一维数组[1,2,3,... ,100]转换为2D数组[[1],[2],[3],... [100]]