scipy.sparse.csr_matrix 行过滤 - 如何正确实现它?

scipy.sparse.csr_matrix row filtering - how to properly achieve it?

我正在和一些 scipy.sparse.csr_matrixes 一起工作。老实说,我手头的那个来自 Scikit-learn 的 TfidfVectorizer:

vectorizer = TfidfVectorizer(min_df=0.0005)
textsMet2 = vectorizer.fit_transform(textsMet)

好的,这是一个矩阵:

textsMet2
<999x1632 sparse matrix of type '<class 'numpy.float64'>'
    with 5042 stored elements in Compressed Sparse Row format>

现在我只想获取那些包含任何非零元素的行。所以很明显我选择了简单的索引:

 textsMet2[(textsMet2.sum(axis=1)>0),:]

并得到一个错误:

文件 "D:\Apps\Python\lib\site-packages\scipy\sparse\sputils.py",第 327 行,在 _boolean_index_to_array 中 提高 IndexError('invalid index shape') IndexError:索引形状无效

如果我删除索引的最后一部分,我会得到一些奇怪的东西:

textsMet2[(textsMet2.sum(axis=1)>0)]
<1x492 sparse matrix of type '<class 'numpy.float64'>'
with 1 stored elements in Compressed Sparse Row format>

为什么它只显示 1 行矩阵?

再一次,我想获取此矩阵中具有任何非零元素的所有行。有人知道怎么做吗?

你需要ravel你的面具。这是我目前正在处理的事情的一些代码:

    tr_matrix = pipeline.fit_transform(train_text, y_train, **fit_params)

    # remove documents with too few features
    to_keep_train = tr_matrix.sum(axis=1) >= config['min_train_features']
    to_keep_train = np.ravel(np.array(to_keep_train))
    logging.info('%d/%d train documents have enough features', 
                 sum(to_keep_train), len(y_train))
    tr_matrix = tr_matrix[to_keep_train, :]

这有点不雅,但可以完成工作。

这将删除 0 行和 0 列。

X = X[np.array(np.sum(X,axis=1)).ravel() != 0,:]
X = X[:,np.array(np.sum(X,axis=0)).ravel() != 0]