我尝试使用以下代码来获取以lil_matrix存储的稀疏矩阵的对角线之和:
sm1 = np.sum(board.diagonal(k=i1-row1))
sm2 = np.sum(board.diagonal(k=i2-row2))
然而,这给了我一个
TypeError: sparse matrix length is ambiguous; use getnnz() or shape[0]
type(board)
返回<class 'scipy.sparse._lil.lil_matrix'>
row1, row2, i1, i2
都是整数。有趣的是,如果我调用print(np.sum(board.diagonal(k=i1-row1))
,它会在抛出类型错误之前打印正确的结果。
我怀疑这个错误与向csr矩阵的转换有关,因为错误消息中提到了return self.tocsr().diagonal(k=k)
,调用board.tocsr()
也会抛出同样的错误。
提前感谢!
下面是完整的错误日志:
Traceback (most recent call last):
File "/usr/lib/python3.8/code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "/snap/pycharm-professional/285/plugins/python/helpers/pydev/_pydev_bundle/pydev_umd.py", line 198, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "/snap/pycharm-professional/285/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/home/noah/PycharmProjects/nQueens/sa_sparse.py", line 94, in <module>
y.run()
File "/home/noah/PycharmProjects/nQueens/sa_sparse.py", line 63, in run
self.swap(newSol)
File "/home/noah/PycharmProjects/nQueens/sa_sparse.py", line 34, in swap
newCost = self.calcFastCost(board.board, row1, row2)
File "/home/noah/PycharmProjects/nQueens/sa_sparse.py", line 47, in calcFastCost
sm1 = np.sum(board.diagonal(k=i1-row1))
File "/home/noah/nQueens/lib/python3.8/site-packages/scipy/sparse/_base.py", line 1214, in diagonal
return self.tocsr().diagonal(k=k)
File "/home/noah/nQueens/lib/python3.8/site-packages/scipy/sparse/_lil.py", line 459, in tocsr
_csparsetools.lil_get_lengths(self.rows, indptr[1:])
File "_csparsetools.pyx", line 111, in scipy.sparse._csparsetools.lil_get_lengths
File "_csparsetools.pyx", line 117, in scipy.sparse._csparsetools._lil_get_lengths_int32
File "/home/noah/nQueens/lib/python3.8/site-packages/scipy/sparse/_base.py", line 345, in __len__
raise TypeError("sparse matrix length is ambiguous; use getnnz()"
TypeError: sparse matrix length is ambiguous; use getnnz() or shape[0]
1条答案
按热度按时间sdnqo3pr1#
您的
scipy
版本是什么?在当前设置中,我可以创建一个lil
并获得对角线:转换为
csr
没有问题,对角线也没有问题:但是询问
len
时,会给予错误:对于这个
lil
,其他的步骤就可以了:lil将值存储在两个对象dtype数组中:
如果我通过删除一个
rows
元素来破坏矩阵,我会得到一个非常不同的错误。看起来错误发生在
tocsr
中,在这个块中,它从rows
元素的长度创建indptr
:lil_get_lengths
是经过编译的代码,它遍历rows
的元素,并将它们的长度放入第二个参数中。