python - 成对距离在稀疏矩阵上失败,并显示无信息的错误消息

标签 python scipy scikit-learn sparse-matrix

from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from scipy.spatial import distance

X = CountVectorizer().fit_transform(docs)
X = TfidfTransformer(use_idf=False).fit_transform(X)
print (X.shape) #prints (100, 1760)

但是,当我尝试计算对距离时,我收到此错误:

distance.pdist(X, metric='cosine')

ValueError: A 2-dimensional array must be passed.

形状表明 X 是一个二维数组,这可能是什么问题?

=====2017 年 7 月 6 日更新======

这是 scipy 中的一个错误,sklearn 对稀疏矩阵有正确的实现。

我在这里提议对 scipy 存储库进行代码更改:

https://github.com/scipy/scipy/pull/7566

=====2018 年 2 月 23 日更新======

如果您来到这里,您可能也遇到了这个问题。

自从我提出的一行修复被推送到 scipy 存储库以来,已经过去 8 个多月了。

请评论herehere ,以获得 scipy 维护者的一些关注。

最佳答案

pdist 开头为:

def pdist(X, metric='euclidean', p=2, w=None, V=None, VI=None):
    ....
    X = np.asarray(X, order='c')

    # The C code doesn't do striding.
    X = _copy_array_if_base_present(X)

    s = X.shape
    if len(s) != 2:
        raise ValueError('A 2-dimensional array must be passed.')

但是如果我创建一个 scipy.sparse 矩阵并应用 asarray 我不会得到二维数组:

In [258]: from scipy import sparse
In [259]: M = sparse.random(100,100, format='csr')
In [260]: M
Out[260]: 
<100x100 sparse matrix of type '<class 'numpy.float64'>'
    with 100 stored elements in Compressed Sparse Row format>
In [263]: np.asarray(M)
Out[263]: 
array(<100x100 sparse matrix of type '<class 'numpy.float64'>'
    with 100 stored elements in Compressed Sparse Row format>, dtype=object)
In [264]: _.shape
Out[264]: ()

pdist 并非设计用于接受稀疏矩阵。稀疏矩阵不是 ndarray 的子类。你必须先使其稠密。

In [266]: np.asarray(M.toarray()).shape
Out[266]: (100, 100)

http://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.pairwise_distances.html

关于python - 成对距离在稀疏矩阵上失败,并显示无信息的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44936494/

相关文章:

python - 解析和验证 YAML 配置文件的最佳方式

python - SQLAlchemy - 延迟多个组

python - 在 python 中绘制带有错误带的图形

python - 逻辑回归python求解器的定义

python - sklearn MinMaxScaler() 与 groupby pandas

python - 我的ROC曲线的一个区域位于随机线下方,如何修改混淆矩阵?

Python 3 FancyURLopener cookie 处理

python - 插值大数据Python

python - scipy odeint 中的当前迭代

python - Scikit Learn - K-Means - 弯头 - 标准