如何编写脚本以使用函数 scipy.io.mmread 从 mtx 文件读取矩阵?

Tom*_*Tom 6 python matrix sparse-matrix

我得到了一个文件(称为matrix.mtx),打开后如下所示:

%%MatrixMarket matrix coordinate real symmetric  
132 132 1890  
1 1  1.9960268182200e+03  
2 1  5.6751562001600e+02  
3 1  7.7541907594400e+02  
6 1 -8.0165406828800e+02  
7 1 -1.3864718750000e+03  
13 1 -1.2338727484800e+00  
18 1 -5.9225891927100e+02  
19 1 -4.9040995231500e+02  
20 1 -4.8997371242200e+02  
Run Code Online (Sandbox Code Playgroud)

... 依此类推

我需要编写一个脚本,使用函数 scipy.io.mmread 从文件 matrix.mtx 中读取矩阵。该函数将以稀疏格式存储矩阵。它说矩阵以矩阵市场格式存储。我无法让它工作,任何帮助将不胜感激。

Sam*_*vre 6

使用以下更简单的矩阵,也存储在 中matrix.mtx

%%MatrixMarket matrix coordinate real symmetric
3 3 6
1 1  1.9960268182200e+03
2 1  5.6751562001600e+02
3 1  7.7541907594400e+02
2 2 -8.0165406828800e+02
3 2 -1.3864718750000e+03
3 3 -5.9225891927100e+02
Run Code Online (Sandbox Code Playgroud)

以下将文件读入稀疏矩阵

In [1]: from scipy.io import mmread

In [2]: a = mmread('matrix.mtx')

In [3]: a
Out[3]:
<3x3 sparse matrix of type '<type 'numpy.float64'>'
    with 9 stored elements in COOrdinate format>
Run Code Online (Sandbox Code Playgroud)

然后可以将其转换为稠密矩阵

In [4]: a.todense()
Out[4]:
matrix([[ 1996.02681822,   567.51562002,   775.41907594],
        [  567.51562002,  -801.65406829, -1386.471875  ],
        [  775.41907594, -1386.471875  ,  -592.25891927]])
Run Code Online (Sandbox Code Playgroud)

或一个数组

In [5]: a.toarray()
Out[5]:
array([[ 1996.02681822,   567.51562002,   775.41907594],
       [  567.51562002,  -801.65406829, -1386.471875  ],
       [  775.41907594, -1386.471875  ,  -592.25891927]])
Run Code Online (Sandbox Code Playgroud)