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

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

我在使用 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() 的调用。)