scipy.sparse.csr_matrix 的默认索引类型是什么?

What is the default indexing type of scipy.sparse.csr_matrix?

scipy.sparse.csr_matrix 具有 dataindicesindptr 属性。

indicesindptr的默认dtype是什么?

对于numpy,默认索引类型是numpy.intp,但这与scipy.sparse.csr_matrixindicesdtype不匹配。

Documentation 共 scipy.sparse.csr_matrix

对于我的笔记本电脑:

import numpy as np
import scipy.sparse as ss
a = ss.csr_matrix(np.arange(12).reshape(3,4), dtype=float)
print(a.indices.dtype)
print(np.intp)

结果:

int32
<class 'numpy.int64'>

sparse.compressed._cs_matrix __init__

            idx_dtype = get_index_dtype(maxval=max(M,N))
            self.data = np.zeros(0, getdtype(dtype, default=float))
            self.indices = np.zeros(0, idx_dtype)
            self.indptr = np.zeros(self._swap((M,N))[0] + 1, dtype=idx_dtype)

sparse.compressed.get_index_dtype 根据矩阵的形状在 np.int32np.int64 之间选择。如果太大而无法使用 32 进行索引,则使用 64。但请查看该功能以获取详细信息。


In [789]:  np.iinfo(np.int32).max
Out[789]: 2147483647
In [790]: a=sparse.csr_matrix((1,2147483646))
In [791]: a
Out[791]: 
<1x2147483646 sparse matrix of type '<class 'numpy.float64'>'
    with 0 stored elements in Compressed Sparse Row format>
In [792]: a.indices.dtype
Out[792]: dtype('int32')
In [793]: a=sparse.csr_matrix((1,2147483648))
In [794]: a.indices.dtype
Out[794]: dtype('int64')