python - 检查 Scipy 稀疏矩阵的密度

标签 python numpy scipy sparse-matrix

有没有好的方法来测量或检查 scipy.sparse 矩阵的密度?

例如:

import scipy.sparse
import numpy as np

row  = np.array([0,3,1,0])
col  = np.array([0,3,1,2])
data = np.array([4,5,7,9])

mat = scipy.sparse.coo_matrix((data,(row,col)), shape=(4,4))
print mat.todense()

[[4 0 9 0]
 [0 7 0 0]
 [0 0 0 0]
 [0 0 0 5]]

也许返回一些东西给我总体密度的一般统计数据,比如每行的平均占用率(即,第一行占用 2/4 值,第二行占用 1/4,第三行占用 0/4,第四行占用1/4,因此平均占用率/密度为 1/4)、stddev、方差等。也许有一个更好的密度度量可以应用,它不依赖于矩阵的大小(假设它足够大).

最佳答案

一种方法是使用 getnnz() 方法来识别给定行、列或整个矩阵中非零项的数量。

让我们从示例稀疏矩阵 sp_mat 开始。

sp_mat.todense()

matrix([[0, 1, 1, 1, 1],
        [1, 0, 1, 0, 0]])

整个矩阵中的非零元素数:

sp_mat.getnnz()
# 6

给定行中的非零元素计数:

sp_mat[0,:].getnnz()
# 4

所有行的非零元素计数:

sp_mat.getnnz(axis=1)
# array([4, 2], dtype=int32)

列中的非零元素计数:

sp_mat[:,1].getnnz()
# 1

所有列的非零元素计数:

sp_mat.getnnz(axis=0)
#  array([1, 1, 2, 1, 1])

这可以与计算密度的矩阵形状进行比较:

sp_mat.shape
# (2, 5)

关于python - 检查 Scipy 稀疏矩阵的密度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36522517/

相关文章:

python - NumPy 索引 - 索引列表的所有成对元素

python - python给我的解决方案是什么 "ValueError: setting an array element with a sequence."

python - 如何使 __add__ 的 numpy 重载独立于操作数顺序?

python - 使用 scipy 最大化目标(通过 kelly criterium)

python - 使用 scipy.weave.inline 时出错

python - 使用 Python 将列表从 MySQL 转换为 JSON 格式

python - Python 中的 Adob​​e Acrobat API

python - 在 Python 中的 Nested Json 中搜索 key

matlab - python中使用相关系数的两幅图像之间的百分比差异

performance - scipy.linalg.solve (LAPACK gesv) 在大矩阵上的时间复杂度?