python - 如何从巨大的(scipy.sparse)矩阵计算对角线度矩阵?

标签 python numpy scipy sparse-matrix

给定一个 100 万维的二次矩阵,我想计算对角线度矩阵。

对角度矩阵定义为对角矩阵,每行的非零值计数作为条目。

矩阵,我们称之为A,格式为scipy.sparse.csr_matrix

如果我的机器有足够的能量,我会做

diagonal_degrees = []
for row in A:
    diagonal_degrees.append(numpy.sum(row!=0))

我什至试过了,但结果是

ValueError: array is too big.

所以我尝试利用scipy的稀疏结构。我是这样想的:

diagonal_degrees = []
CSC_format = A.tocsc() # A is in scipys CSR format.
for i in range(CSC_format.shape[0]):
    row = CSC_format.getrow(i)
    diagonal_degrees.append(numpy.sum(row!=0))

我有两个问题:

  1. 有没有更有效的方法,我可能忽略了?
  2. 虽然 docs of scipy sparse state :

All conversions among the CSR, CSC, and COO formats are efficient, linear-time operations.

为什么我会得到一个

SparseEfficiencyWarning: changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient.

从 CSR 转变为 CSC 时?

最佳答案

如果您只需要计算非零元素,则有 nonzero可能有用的方法。

确切的代码是(在 Joe Kingtonmatehat 的帮助下):

diag_deg, _ = np.histogram(x.nonzero()[0], np.arange(x.shape[0]+1))

# generating a diagonal matrix with diag_deg
dim = x.shape[0]
diag_mat = np.zeros((dim**2, ))
diag_mat[np.arange(0, dim**2, dim+1)] = diag_deg
diag_mat.reshape((dim, dim))

尽管对于大型数组(dim ~ 100 万),如 Aufwind 所述, np.zeros((dim**2, )) 给出异常:ValueError: Maximum allowed dimension exceeded。另一种解决方法是使用稀疏矩阵:

diag_mat = sparse.coo_matrix((dim, dim))
diag_mat.setdiag(diag_deg)

关于python - 如何从巨大的(scipy.sparse)矩阵计算对角线度矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8905723/

相关文章:

python - 使用奇特的索引从 numpy 矩阵的每一列获取一个值

python - 如何将csv文件转换为字符级one-hot-encode矩阵?

python - 做多重积分时, 'takes 0 positional arguments but 1 was given'

Python SciPy : optimization issue fmin_cobyla : one constraint is not respected

python - 在 resnet 模型中拟合图像时出现尺寸问题

python - 什么时候应该使用 os.name vs. sys.platform vs. platform.system()?

python - numpy python 上的反向对角线

python - 构建 OpenCV cmake 错误 : could NOT find PythonInterp

python - 如何忽略 numpy 数组中的 NaN 数据点并在 Python 中生成规范化数据?

python - 使用 SciPy 规则网格在 Python 中进行快速二维插值以进行分散/不规则评估