Python empty csr_matrix抛出ValueError:无法从大小为零的索引数组推断维度
以下是python SSCCE:Python empty csr_matrix抛出ValueError:无法从大小为零的索引数组推断维度,python,scipy,sparse-matrix,Python,Scipy,Sparse Matrix,以下是python SSCCE: import scipy.sparse data = [] row = [] col = [] csr = scipy.sparse.csr_matrix((data, (row, col))) #error happens here print(type(csr)) print(csr) 我正在用python2.7运行它,我得到一个错误: raise ValueError('cannot infer dimensions from zero sized i
import scipy.sparse
data = []
row = []
col = []
csr = scipy.sparse.csr_matrix((data, (row, col))) #error happens here
print(type(csr))
print(csr)
我正在用python2.7运行它,我得到一个错误:
raise ValueError('cannot infer dimensions from zero sized index arrays')
ValueError: cannot infer dimensions from zero sized index arrays
当我向他们提供如下值时,它可以正常工作:
csr = scipy.sparse.csr_matrix(([10,20,30], ([0,0,0],[0,1,2])))
csr = scipy.sparse.csr_matrix(([10,20], ([0,0],[0,1])))
csr = scipy.sparse.csr_matrix(([10], ([0],[0])))
或者像这样:
csr = scipy.sparse.csr_matrix(([10,20,30], ([0,0,0],[0,1,2])))
csr = scipy.sparse.csr_matrix(([10,20], ([0,0],[0,1])))
csr = scipy.sparse.csr_matrix(([10], ([0],[0])))
我阅读了以下文件:
及
但这似乎不能解释为什么我不能制作一个包含零项的csr矩阵
这个错误是怎么回事?我猜scipy.sparse.csr.csr_矩阵类型在实例化时必须至少有一个值?这似乎是一个愚蠢的限制 Scipy稀疏矩阵具有确定的形状,例如(m,n),其中m是行数,n是列数。例如,在编写时,
csr_矩阵([1,2],([0,3],[1,4])
,csr_矩阵
根据行和列索引的最大值推断形状。但是当您编写csr_矩阵(([],([],[]))
时,函数无法知道矩阵的形状应该是什么(我猜它在默认情况下不会创建形状为(0,0)的矩阵)
一种处理方法是给出一个显式的形状
:
In [241]: csr_matrix(([], ([], [])), shape=(3, 3))
Out[241]:
<3x3 sparse matrix of type '<class 'numpy.float64'>'
with 0 stored elements in Compressed Sparse Row format>
In [480]: sparse.csr_matrix(([],([],[])),shape=(1000,1000))
Out[480]:
<1000x1000 sparse matrix of type '<class 'numpy.float64'>'
with 0 stored elements in Compressed Sparse Row format>
In [481]: M=_
In [482]: M[34,334]=1000
/usr/lib/python3/dist-packages/scipy/sparse/compressed.py:730: SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient.
SparseEfficiencyWarning)
[241]中的:csr_矩阵([],([],[]),形状=(3,3))
Out[241]:
您可以从空的密集矩阵或通过给定形状参数生成空的稀疏矩阵:
In [477]: from scipy import sparse
In [478]: sparse.csr_matrix([])
Out[478]:
<1x0 sparse matrix of type '<class 'numpy.float64'>'
with 0 stored elements in Compressed Sparse Row format>
In [479]: sparse.csr_matrix(([],([],[])),shape=(0,0))
Out[479]:
<0x0 sparse matrix of type '<class 'numpy.float64'>'
with 0 stored elements in Compressed Sparse Row format>
但考虑到插入值或连接新矩阵的效率低下,我不明白你为什么要制造这样的生物
当第一个参数是元组时,sparse.coo_matrix
中的相关代码:
try:
obj, (row, col) = arg1
except (TypeError, ValueError):
raise TypeError('invalid input format')
if shape is None:
if len(row) == 0 or len(col) == 0:
raise ValueError('cannot infer dimensions from zero '
'sized index arrays')
M = np.max(row) + 1
N = np.max(col) + 1
self.shape = (M, N)
实际上,您可能应该给出一个明确的形状,而不是让SciPy猜测,即使数组不是空的。您可以创建一个空的csr_矩阵,如下所示:
csr=SciPy.sparse.csr_矩阵((0,0))
。但是,它不会从空列表中推断出这一点。这就是问题所在,为什么它必须推断出某些地方出了问题,而不是我们正确地不需要任何元素?答案是因为事情就是这样,处理好它。