gpt4 book ai didi

python-3.x - 如何消除(Python)中稀疏矩阵中的零?

转载 作者:行者123 更新时间:2023-12-04 12:26:22 26 4
gpt4 key购买 nike

我需要一个稀疏矩阵(我使用来自 scipy.sparseCompressed Sparse Row Format (CSR) )来做一些计算。我有 (data, (row, col)) 的形式元组。不幸的是,某些行和列将全部为零,我想摆脱这些零。现在我有:

[In]:
from scipy.sparse import csr_matrix
aa = csr_matrix((1,2,3), ((0,2,2), (0,1,2))
aa.todense()
[Out]:
matrix([[1, 0, 0],
[0, 0, 0],
[0, 2, 3]], dtype=int64)

我想要:
[Out]:
matrix([[1, 0, 0],
[0, 2, 3]], dtype=int64)

使用方法后 eliminate_zeros() 在我得到的对象上 None :
[In]:
aa2 = csr_matrix.eliminate_zeros(aa)
type(aa2)
[Out]:
<class 'NoneType'>

为什么那个方法把它变成 None ?

有没有其他方法可以获得稀疏矩阵(不必是 CSR)并轻松摆脱空行/列?

我正在使用 Python 3.4.0。

最佳答案

在 CSR 格式中,摆脱全零行相对容易:

>>> import scipy.sparse as sps
>>> a = sps.csr_matrix([[1, 0, 0], [0, 0, 0], [0, 2, 3]])
>>> a.indptr
array([0, 1, 1, 3])
>>> mask = np.concatenate(([True], a.indptr[1:] != a.indptr[:-1]))
>>> mask # 1st occurrence of unique a.indptr entries
array([ True, True, False, True], dtype=bool)
>>> sps.csr_matrix((a.data, a.indices, a.indptr[mask])).A
array([[1, 0, 0],
[0, 2, 3]])

然后,您可以将稀疏数组转换为 CSC 格式,然后完全相同的技巧将摆脱所有零列。

我不确定它的表现如何,但是更易读的语法:
>>> a[a.getnnz(axis=1) != 0][:, a.getnnz(axis=0) != 0].A
array([[1, 0, 0],
[0, 2, 3]])

也有效。

关于python-3.x - 如何消除(Python)中稀疏矩阵中的零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31732433/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com