scipy.sparse矩阵(csr_matrix())但我需要将它保存到一个文件,而不是.npz格式,而是作为一个常规的.txt.csv文件.我的问题是,我没有足够的内存将稀疏矩阵转换成常规的np.array(),然后保存到文件中.是否有一种方法可以将数据作为稀疏矩阵存储在内存中,但直接将其保存为正则矩阵,格式如下:

0 0 0
0 1 0
1 0 1

到磁盘上?或者,有没有一种方法可以在Python内部不加载到内存中的情况下"解压缩"一个.npz文件?(例如Bash中的gunzip或unzip).

推荐答案

对新问题的回答:

import numpy as np
from scipy import sparse, io
A = sparse.eye(5, format='csr') * np.pi
np.set_printoptions(precision=16, linewidth=1000)
with open('matrix.txt', 'a') as f:
    for row in A:
        f.write(str(row.toarray()[0]))
        f.write('\n')

# [3.141592653589793 0.                0.                0.                0.               ]
# [0.                3.141592653589793 0.                0.                0.               ]
# [0.                0.                3.141592653589793 0.                0.               ]
# [0.                0.                0.                3.141592653589793 0.               ]
# [0.                0.                0.                0.                3.141592653589793]

并加上开始/结束括号:

import numpy as np
from scipy import sparse, io
A = sparse.eye(5, format='csr') * np.pi
np.set_printoptions(precision=16, linewidth=1000)
with open('matrix.txt', 'a') as f:
    for i, row in enumerate(A):
        f.write('[' if (i == 0) else ' ')
        f.write(str(row.toarray()[0]))
        f.write(']' if (i == A.shape[0] - 1) else '\n')

# [[3.141592653589793 0.                0.                0.                0.               ]
#  [0.                3.141592653589793 0.                0.                0.               ]
#  [0.                0.                3.141592653589793 0.                0.               ]
#  [0.                0.                0.                3.141592653589793 0.               ]
#  [0.                0.                0.                0.                3.141592653589793]]

您可能需要根据您的数据调整set_printoptions个.


回答原始问题,这不要求矩阵写得密集.

Harwell-Boeing format是纯文本:

import numpy as np
from scipy import sparse, io
A = sparse.eye(3, format='csr') * np.pi

# Default title                                                           0       
#              3             1             1             1
# RUA                        3             3             3             0
# (40I2)          (40I2)          (3E25.16)           
#  1 2 3 4
#  1 2 3
#   3.1415926535897931E+00  3.1415926535897931E+00  3.1415926535897931E+00

io.hb_write('matrix.txt', A)  # saves as matrix.txt
A2 = io.hb_read('matrix.txt')
assert not (A2 != A).nnz  # efficient check for equality

Matrix Market:

io.mmwrite('matrix', A)  # saves as matrix.mtx

# %%MatrixMarket matrix coordinate real symmetric
# %
# 3 3 3
# 1 1 3.141592653589793e+00
# 2 2 3.141592653589793e+00
# 3 3 3.141592653589793e+00

A2 = io.mmread('matrix')
assert not (A2 != A).nnz

如果你想要一个更简单的format,尽管它涉及更多的代码:

import numpy as np
from scipy import sparse
A = sparse.eye(10, format='csr')*np.pi

np.savetxt('data.txt', A.data)
np.savetxt('indices.txt', A.indices, fmt='%i')
np.savetxt('indptr.txt', A.indptr, fmt='%i')

加载:

data = np.loadtxt('data.txt')
indices = np.loadtxt('indices.txt', dtype=np.int32)
indptr = np.loadtxt('indptr.txt', dtype=np.int32)

A2 = sparse.csr_matrix((data, indices, indptr))
assert not (A2 != A).nnz

但重要的是,你需要保存的只是csr_matrixdataindicesindptr属性.

Python相关问答推荐

Python -根据另一个数据框中的列编辑和替换数据框中的列值

Python plt.text中重叠,包adjust_text不起作用,如何修复?

计算相同形状的两个张量的SSE损失

@Property方法上的inspect.getmembers出现意外行为,引发异常

Python daskValue错误:无法识别的区块管理器dask -必须是以下之一:[]

大小为M的第N位_计数(或人口计数)的公式

在Wayland上使用setCellWidget时,try 编辑QTable Widget中的单元格时,PyQt 6崩溃

Python虚拟环境的轻量级使用

python中字符串的条件替换

使用groupby方法移除公共子字符串

在两极中过滤

在Python中使用yaml渲染(多行字符串)

使用python playwright从 Select 子菜单中 Select 值

如何在SQLAlchemy + Alembic中定义一个"Index()",在基表中的列上

利用SCIPY沿第一轴对数组进行内插

如何在Python中解析特定的文本,这些文本包含了同一行中的所有内容,

无法在盐流道中获得柱子

极点用特定值替换前n行

使用美汤对维基百科表格进行网络刮擦未返回任何内容

#将多条一维曲线计算成其二维数组(图像)表示