scipy.sparse.
save_npz#
- scipy.sparse.save_npz(file, matrix, compressed=True)[源代码]#
使用
.npz
格式将稀疏矩阵或数组保存到文件。- 参数:
- file字符串或类文件对象
要保存数据的文件名(字符串)或已打开的文件(类文件对象)。如果文件是字符串,且文件名中不包含
.npz
扩展名,则会自动添加该扩展名。- matrix: spmatrix 或 sparray
要保存的稀疏矩阵或数组。支持的格式:
csc
、csr
、bsr
、dia
或coo
。- compressed布尔值,可选
是否允许压缩文件。默认值:True
另请参阅
scipy.sparse.load_npz
使用
.npz
格式从文件加载稀疏矩阵。numpy.savez
将多个数组保存到
.npz
归档文件中。numpy.savez_compressed
将多个数组保存到压缩的
.npz
归档文件中。
示例
将稀疏矩阵保存到磁盘,然后再次加载
>>> import numpy as np >>> import scipy as sp >>> sparse_matrix = sp.sparse.csc_matrix([[0, 0, 3], [4, 0, 0]]) >>> sparse_matrix <Compressed Sparse Column sparse matrix of dtype 'int64' with 2 stored elements and shape (2, 3)> >>> sparse_matrix.toarray() array([[0, 0, 3], [4, 0, 0]], dtype=int64)
>>> sp.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix) >>> sparse_matrix = sp.sparse.load_npz('/tmp/sparse_matrix.npz')
>>> sparse_matrix <Compressed Sparse Column sparse matrix of dtype 'int64' with 2 stored elements and shape (2, 3)> >>> sparse_matrix.toarray() array([[0, 0, 3], [4, 0, 0]], dtype=int64)