numpy - SciPy PearsonR ValueError : The truth value of an array with more than one element is ambiguous. 使用 a.any() 或 a.all()

标签 numpy pandas scipy scikit-learn

我在使用 SciPy 的 pearsonr 方法时遇到了一些问题。我试图让它尽可能简单(注意华丽的 N^2 循环),但我仍然遇到这个问题。我不完全明白我哪里出错了。我的数组被正确选择,并且具有相同的维度。

我运行的代码是:

from scipy import stats
from sklearn.preprocessing import LabelBinarizer, Binarizer
from sklearn.feature_extraction.text import CountVectorizer

ny_cluster = LabelBinarizer().fit_transform(ny_raw.clusterid.values)
ny_vocab = Binarizer().fit_transform(CountVectorizer().fit_transform(ny_raw.text.values))

ny_vc_phi = np.zeros((ny_vocab.shape[1], ny_cluster.shape[1]))
for i in xrange(ny_vc_phi.shape[0]):
    for j in xrange(ny_vc_phi.shape[1]):
        ny_vc_phi[i,j] = stats.pearsonr(ny_vocab[:,i].todense(), ny_cluster[:,j])[0]

产生错误的地方:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/data/TweetClusters/TweetsLocationBayesClf/<ipython-input-29-ff1c3ac4156d> in <module>()
      3 for i in xrange(ny_vc_phi.shape[0]):
      4     for j in xrange(ny_vc_phi.shape[1]):
----> 5         ny_vc_phi[i,j] = stats.pearsonr(ny_vocab[:,i].todense(), ny_cluster[:,j])[0]
      6 

/usr/lib/python2.7/dist-packages/scipy/stats/stats.pyc in pearsonr(x, y)
   2201     # Presumably, if abs(r) > 1, then it is only some small artifact of floating

   2202     # point arithmetic.

-> 2203     r = max(min(r, 1.0), -1.0)
   2204     df = n-2
   2205     if abs(r) == 1.0:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我真的不明白这个选择是怎么回事。当然,我不知道 r 变量是如何计算的,这无济于事。会不会是我弄乱了我的输入?

最佳答案

检查pearsonr 的参数是否为一维 数组。也就是说,ny_vocab[:,i].todense()ny_cluster[:,j] 都应该是一维的。尝试:

    ny_vc_phi[i,j] = stats.pearsonr(ny_vocab[:,i].todense().ravel(), ny_cluster[:,j].ravel())[0]

(我向 pearsonr 的每个参数添加了对 ravel() 的调用。)

关于numpy - SciPy PearsonR ValueError : The truth value of an array with more than one element is ambiguous. 使用 a.any() 或 a.all(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28841313/

相关文章:

python - 如何向 NumPy 数组添加额外的列?

python - 分组依据和引用移位值

numpy - 如何在 Ubuntu 上安装最新版本的 NumPy/Scipy/Matplotlib/IPython/Pandas

python - Scipy Optimize 仅返回 x0,仅完成一次迭代

Python:获取两个 3D 点之间的所有坐标或绘制 3D 线

python - 使用 --no-site-packages 在 vi​​rtualenv 中安装 pyopencv

python - 如何在 cython 的 nogil 循环下将 numpy.ndarray 分配给临时变量?

python - 在 1 行中进行两次 for 循环以创建一个新的元组列表

Python3 Pillow 获取一条线上的所有像素

python - 生成用户/项目交互