存储稀疏 Numpy 数组

The*_*ain 0 python arrays numpy matrix sparse-matrix

我有一个 20,000 x 20,000 Numpy 矩阵,我希望通过文件存储,其中平均体积只有 12 个值。

仅存储以下格式的值的最有效方法是什么

if array[i][j] == 1:
   file.write("{} {} {{}}\n".format(i, j)
Run Code Online (Sandbox Code Playgroud)

其中 (i, j) 是数组的索引?

Aks*_*gal 5

您可以使用scipy密集 numpy 数组创建稀疏矩阵,该数组仅存储索引中具有非零条目的值。

import scipy
import pickle

I = np.eye(10000)  #Had 10000 nonzero values along diagonal
S = scipy.sparse.csr_matrix(I)
S
Run Code Online (Sandbox Code Playgroud)
<10000x10000 sparse matrix of type '<class 'numpy.float64'>'
    with 10000 stored elements in Compressed Sparse Row format>
Run Code Online (Sandbox Code Playgroud)

这是高度内存效率的,您可以pickle在需要时转储/加载这个稀疏矩阵。

#Pickle dump
file = open("S.pickle",'wb') #160kb
pickle.dump(S, file)

#Pickle load
file = open("S.pickle",'rb') 
S = pickle.load(file)
Run Code Online (Sandbox Code Playgroud)

要获取密集表示,您可以简单地使用.toarray()获取 NumPy 数组或.todense()获取矩阵类型对象。

S.toarray()
Run Code Online (Sandbox Code Playgroud)
array([[1., 0., 0., ..., 0., 0., 0.],
       [0., 1., 0., ..., 0., 0., 0.],
       [0., 0., 1., ..., 0., 0., 0.],
       ...,
       [0., 0., 0., ..., 1., 0., 0.],
       [0., 0., 0., ..., 0., 1., 0.],
       [0., 0., 0., ..., 0., 0., 1.]])
Run Code Online (Sandbox Code Playgroud)