如何从 MMF 文件加载 python 中的稀疏矩阵

How to load sparse matrix in python from MMF file

我需要加载稀疏矩阵形式 (MMF) 文件的数据,然后对该矩阵执行线性代数运算。 MMF 文件格式如下:

1 1 8.530175905456780E+008
7 1 1.257919566068602E+008
12 1 3.841933299769016E+002
13 1 1.257919566068601E+008
18 1 -3.841933299769017E+002
67 1 -1.214247928031784E+008
68 1 3.613935214862212E+007
72 1 9.604833249423183E+001
73 1 -3.094511662733424E+008
79 1 -1.214247928031783E+008
80 1 -3.613935214862211E+007
84 1 -9.604833249423186E+001
2 2 8.530175905456780E+008
8 2 -3.094511662733424E+008
14 2 -3.094511662733426E+008
67 2 3.613935214862212E+007
68 2 -1.214247928031784E+008
72 2 9.604833249423183E+001
74 2 1.257919566068602E+008
78 2 3.841933299769016E+002
79 2 -3.613935214862212E+007
80 2 -1.214247928031783E+008
84 2 9.604833249423183E+001
........

最大尺寸为 6500。

来自 scipymmread 的文档:

https://docs.scipy.org/doc/scipy/reference/generated/scipy.io.mmread.html

scipy.io.mmread(source)[source]

Reads the contents of a Matrix Market file-like ‘source’ into a matrix.

Parameters sourcestr or file-like Matrix Market filename (extensions .mtx, .mtz.gz) or open file-like object.

Returns andarray or coo_matrix Dense or sparse matrix depending on the matrix format in the Matrix Market file.

Scipy 应该 return 一个稀疏矩阵,如果这是文件的格式。

尝试:

import scipy

sparse_mat = scipy.io.mmread('matrix_file_name.mtx')

好吧,我使用以下代码(其中 n 是矩阵大小)解决了这个问题:

import numpy as np
from numpy import *
from matplotlib.pyplot import *
import re
import scipy.linalg as la
data=loadtxt('matKSMMF.txt',skiprows=8)
s = len (data)
print(s)
n=6567
kmat = [[0 for _ in range(n)] for _ in range(n)]
for x in range (s):
    m=data[x:x+1,:]
    kmat[int (m[0,0])-1][int (m[0,1])-1]=m[0,2]
K=np.array(kmat)
print (K)