【问题标题】:CSR scipy matrix does not update after updating its valuesCSR scipy 矩阵在更新其值后不更新
【发布时间】:2016-12-28 18:56:39
【问题描述】:

我在 python 中有以下代码:

import numpy as np
from scipy.sparse import csr_matrix
M = csr_matrix(np.ones([2, 2],dtype=np.int32))
print(M)
print(M.data.shape)
for i in range(np.shape(mat)[0]):
    for j in range(np.shape(mat)[1]):
        if i==j:
            M[i,j] = 0
print(M)
print(M.data.shape)

前 2 次打印的输出是:

  (0, 0)    1
  (0, 1)    1
  (1, 0)    1
  (1, 1)    1
(4,)

代码正在更改同一索引 (i==j) 的值并将该值设置为零。 执行循环后,最后 2 次打印的输出为:

  (0, 0)    0
  (0, 1)    1
  (1, 0)    1
  (1, 1)    0
(4,)

如果我正确理解了稀疏矩阵的概念,那不应该是这样。它不应该显示零值,最后 2 次打印的输出应该是这样的:

  (0, 1)    1
  (1, 0)    1
(2,)

有人对此有解释吗?我做错了吗?

【问题讨论】:

标签: python matrix scipy


【解决方案1】:

是的,您正在尝试逐个更改矩阵的元素。 :)

好的,它确实可以这样工作,但是如果您以其他方式更改内容(将 0 设置为非零),您将收到效率警告。

为了保持您的快速更改,它只更改M.data 数组中的值,而不重新计算索引。您必须调用一个单独的csr_matrix.eliminate_zeros 方法来清理矩阵。为了获得最佳速度,在循环结束时调用一次。

有一个csr_matrix.setdiag 方法可以让您一次调用设置整个对角线。它仍然需要清理。

In [1633]: M=sparse.csr_matrix(np.arange(9).reshape(3,3))
In [1634]: M
Out[1634]: 
<3x3 sparse matrix of type '<class 'numpy.int32'>'
    with 8 stored elements in Compressed Sparse Row format>
In [1635]: M.A
Out[1635]: 
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]], dtype=int32)
In [1636]: M.setdiag(0)
/usr/local/lib/python3.5/dist-packages/scipy/sparse/compressed.py:730: SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient.
  SparseEfficiencyWarning)
In [1637]: M
Out[1637]: 
<3x3 sparse matrix of type '<class 'numpy.int32'>'
    with 9 stored elements in Compressed Sparse Row format>
In [1638]: M.A
Out[1638]: 
array([[0, 1, 2],
       [3, 0, 5],
       [6, 7, 0]])
In [1639]: M.data
Out[1639]: array([0, 1, 2, 3, 0, 5, 6, 7, 0])
In [1640]: M.eliminate_zeros()
In [1641]: M
Out[1641]: 
<3x3 sparse matrix of type '<class 'numpy.int32'>'
    with 6 stored elements in Compressed Sparse Row format>
In [1642]: M.data
Out[1642]: array([1, 2, 3, 5, 6, 7])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    相关资源
    最近更新 更多