如何从scipy.sparse.csr.csr_matrix和列表中进行子采样?
我有一个 scipy.sparse.csr.csr_matrix
,它用来表示文档中的单词,还有一个列表的列表,每个索引对应矩阵中的每一行的类别。
我遇到的问题是,我需要从这些数据中随机选择 N 行。
比如说,如果我的矩阵长这样:
[1:3 2:3 4:4]
[1:5 2:5 5:4]
而我的列表的列表长这样:
((20,40) (80,50))
如果我需要随机抽取一个值,可能会得到这样的结果:
[1:3 2:3 4:4]
((20,40))
我查阅了 scipy 的文档,但找不到用索引列表生成新的 csr 矩阵的方法。
1 个回答
6
你可以通过使用一个索引列表来简单地访问一个稀疏矩阵。首先,我们创建一个矩阵,然后看看它的样子:
>>> m = csr_matrix([[0,0,1,0], [4,3,0,0], [3,0,0,8]])
<3x4 sparse matrix of type '<type 'numpy.int64'>'
with 5 stored elements in Compressed Sparse Row format>
>>> print m.toarray()
[[0 0 1 0]
[4 3 0 0]
[3 0 0 8]]
当然,我们可以很容易地只查看第一行:
>>> m[0]
<1x4 sparse matrix of type '<type 'numpy.int64'>'
with 1 stored elements in Compressed Sparse Row format>
>>> print m[0].toarray()
[[0 0 1 0]]
但我们也可以通过使用列表 [0,2]
作为索引,一次查看第一行和第三行:
>>> m[[0,2]]
<2x4 sparse matrix of type '<type 'numpy.int64'>'
with 3 stored elements in Compressed Sparse Row format>
>>> print m[[0,2]].toarray()
[[0 0 1 0]
[3 0 0 8]]
现在,你可以使用 numpy 的 choice
生成 N
个不重复的随机索引:
i = np.random.choice(np.arange(m.shape[0]), N, replace=False)
然后你可以从原始矩阵 m
中提取这些索引:
sub_m = m[i]
要从你的分类列表中提取这些索引,首先需要将其转换为数组,然后就可以用列表 i
进行索引:
sub_c = np.asarray(categories)[i]
如果你想要返回一个列表的列表,只需使用:
sub_c.tolist()
或者,如果你真正想要的是一个元组的元组,我想你需要手动处理:
tuple(map(tuple, sub_c))