什么是行切片 vs 什么是列切片?

What is row slicing vs What is column slicing?

是的,我读过 this and this answer,但我仍然无法理解它...这是一个基本问题。

在:

M[:, index]
M[index, :]

哪个是行切片,哪个是列切片?

对于我的问题,如果我想对像这样的列执行 advanced indexing

M[:, indexes]  # indexes is an array like [0, 4, 9]

哪种稀疏矩阵类型对于 M[:, indexes]CSR or CSC 最有效?

偶尔把顺序搞混也没关系,我的诀窍是画一个矩阵,记住索引顺序从上到下,然后从左到右:https://en.wikipedia.org/wiki/Index_notation

因此,由于 : 表示 所有 ,您知道 [:, i] 表示所有行,[i, :] 所有列。

关于你问题的第二部分:你想要 M[:, indices],所以技巧就在名称中:如果你遍历你的列(你这样做是因为你为 指定了列索引all 行),那么您需要 compressed sparse colum 格式。它在您链接的文档中是这样说的:

Advantages of the CSC format

  • ...
  • efficient column slicing

实际上 row/column slicing 也不是:这些是 row/column indexing 的例子。

  • M[index, :] 是行索引
  • M[:, index]是列索引
  • M[start:stop, :]是行切片
  • M[:, start:stop]是列切片

CSC 在检索整个列时更有效:特定列的 non-zero 值和匹配的行索引在内存中作为连续数组内部存储。

对于 CSR 和整行的检索,对偶成立。

虽然行选择 csr 比列选择快,但差别不大:

In [288]: Mbig=sparse.rand(1000,1000,.1, 'csr')
In [289]: Mbig[:1000:50,:]
Out[289]: 
<20x1000 sparse matrix of type '<class 'numpy.float64'>'
    with 2066 stored elements in Compressed Sparse Row format>
In [290]: timeit Mbig[:1000:50,:]
1000 loops, best of 3: 1.53 ms per loop
In [291]: timeit Mbig[:,:1000:50]
100 loops, best of 3: 2.04 ms per loop

In [292]: Mbig=sparse.rand(1000,1000,.1, 'csc')
In [293]: timeit Mbig[:1000:50,:]
100 loops, best of 3: 2.16 ms per loop
In [294]: timeit Mbig[:,:1000:50]
1000 loops, best of 3: 1.65 ms per loop

不值得转换格式

In [295]: timeit Mbig.tocsr()[:1000:50,:]
...
100 loops, best of 3: 2.46 ms per loop

将此与密集版本的相同切片进行对比:

In [297]: A=Mbig.A
In [298]: timeit A[:,:1000:50]
...
1000000 loops, best of 3: 557 ns per loop
In [301]: timeit A[:,:1000:50].copy()
...
10000 loops, best of 3: 52.5 µs per loop

为了使比较复杂化,使用数组索引(numpy 高级)实际上比使用 'slice':

In [308]: idx=np.r_[0:1000:50]    # expand slice into array
In [309]: timeit Mbig[idx,:]
1000 loops, best of 3: 1.49 ms per loop
In [310]: timeit Mbig[:,idx]
1000 loops, best of 3: 513 µs per loop

这里acsc的列索引有较大的速度提升

和单行或单列,csrcscgetrow/col个方法:

In [314]: timeit Mbig.getrow(500)
1000 loops, best of 3: 434 µs per loop
In [315]: timeit Mbig.getcol(500)        # 1 column from csc is fastest
10000 loops, best of 3: 78.7 µs per loop
In [316]: timeit Mbig[500,:]
1000 loops, best of 3: 505 µs per loop
In [317]: timeit Mbig[:,500]
1000 loops, best of 3: 264 µs per loop

中,我重新创建了 extractor 代码,sparse 用于获取行或列。它构造了一个新的稀疏 'vector' 的 1 和 0,并对 'select' 行或列使用矩阵乘法。