numpy python matplotlib plot稀疏矩阵模式

jbose2ul  于 12个月前  发布在  Python
关注(0)|答案(3)|浏览(94)

给定一个稀疏二进制矩阵A(csr,coo,whatever),我想画一个图,这样我就可以看到,如果A(i,j)= 1,图中的位置(i,j)=白色,如果A(i,j)= 0,图中的位置(i,j)=黑色;
对于密集的numpy数组,matshow将完成这项工作。然而,我的稀疏矩阵的维数(比如100000 x 1000000)太大,无法转换为密集数组。我想知道我如何在稀疏矩阵中绘制模式。
谢谢

8fsztsew

8fsztsew1#

你可以使用coo_matrixplot()和一些调整来获得一个很好的结果:

import matplotlib.pyplot as plt
from scipy.sparse import coo_matrix

def plot_coo_matrix(m):
    if not isinstance(m, coo_matrix):
        m = coo_matrix(m)
    fig = plt.figure()
    ax = fig.add_subplot(111, facecolor='black')
    ax.plot(m.col, m.row, 's', color='white', ms=1)
    ax.set_xlim(0, m.shape[1])
    ax.set_ylim(0, m.shape[0])
    ax.set_aspect('equal')
    for spine in ax.spines.values():
        spine.set_visible(False)
    ax.invert_yaxis()
    ax.set_aspect('equal')
    ax.set_xticks([])
    ax.set_yticks([])
    return ax

请注意,y轴是颠倒的,第一行位于图的顶部。举个例子:

import numpy as np
from scipy.sparse import coo_matrix

shape = (100000, 100000)
rows = np.int_(np.round_(shape[0]*np.random.random(1000)))
cols = np.int_(np.round_(shape[1]*np.random.random(1000)))
vals = np.ones_like(rows)

m = coo_matrix((vals, (rows, cols)), shape=shape)
ax = plot_coo_matrix(m)
ax.figure.show()

crcmnpdw

crcmnpdw3#

请参见matspy

pip install matspy

大型矩阵是没有问题的,数千万个非零的间谍图只需要不到半秒。举个小例子:

from matspy import spy
import scipy

n = 9000
A = scipy.sparse.random(n, n, density=0.001) + scipy.sparse.eye(n)

spy(A)

如果要进一步修改绘图,请改用fig, ax = matspy.spy_to_mpl(A)

更大的例子:

spy()在我的笔记本电脑上绘图花了0.42秒:

mat = scipy.sparse.eye(10_000_000).tocsr()
spy(mat)

相关问题