您可以使用索引列表简单地索引 csr 矩阵。首先我们创建一个矩阵,看看它:
>>> 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))