Python创建一个空的稀疏矩阵

Ton*_*ous 3 python matlab numpy scipy python-3.x

我试图将一些真实数据解析为一个.mat要在我的脚本中加载的对象.

我收到此错误:

TypeError:'coo_matrix'对象不支持项目分配

我找到了coo_matrix.但是,我无法为其分配值.

data.txt中

10 45
11 12 
4 1
Run Code Online (Sandbox Code Playgroud)

我想得到一个大小为100x100的稀疏矩阵.并指定1

Mat(10, 45) = 1
Mat(11, 12) = 1
Mat(4, 1) = 1
Run Code Online (Sandbox Code Playgroud)

import numpy as np
from scipy.sparse import coo_matrix

def pdata(pathToFile):
    M = coo_matrix(100, 100)
    with open(pathToFile) as f:
        for line in f:
            s = line.split()
            x, y = [int(v) for v in s]
            M[x, y] = 1     
    return M

if __name__ == "__main__":
    M = pdata('small.txt')  
Run Code Online (Sandbox Code Playgroud)

有什么建议吗?

sas*_*cha 5

使用支持高效索引的稀疏格式,如dok_matrix

这是用于逐步构造稀疏矩阵的有效结构.

...

允许对单个元素进行有效的O(1)访问.不允许重复.一旦构建,就可以有效地转换为coo_matrix.

最后一句可以推广为:如果需要,可以有效地转换为所有其他常见格式.

from scipy.sparse import dok_matrix

M = dok_matrix((100, 100))  # extra brackets needed as mentioned in comments
                            # thanks Daniel!
M[0,3] = 5
Run Code Online (Sandbox Code Playgroud)


hpa*_*ulj 2

coo_matrix使用 (data, (rows, cols))` 参数格式构造此矩阵:

In [2]: from scipy import sparse
In [3]: from scipy import io
In [4]: data=np.array([[10,45],[11,12],[4,1]])
In [5]: data
Out[5]: 
array([[10, 45],
       [11, 12],
       [ 4,  1]])
In [6]: rows = data[:,0]
In [7]: cols = data[:,1]
In [8]: data = np.ones(rows.shape, dtype=int)
In [9]: M = sparse.coo_matrix((data, (rows, cols)), shape=(100,100))
In [10]: M
Out[10]: 
<100x100 sparse matrix of type '<class 'numpy.int32'>'
    with 3 stored elements in COOrdinate format>
In [11]: print(M)
  (10, 45)  1
  (11, 12)  1
  (4, 1)    1
Run Code Online (Sandbox Code Playgroud)

如果您将其保存到 .mat 文件以便在 MATLAB 中使用,它将以以下csc格式保存(已将其从 .mat 文件转换而来coo):

In [13]: io.savemat('test.mat',{'M':M})
In [14]: d = io.loadmat('test.mat')
In [15]: d
Out[15]: 
{'M': <100x100 sparse matrix of type '<class 'numpy.int32'>'
    with 3 stored elements in Compressed Sparse Column format>,
 '__globals__': [],
 '__header__': b'MATLAB 5.0 MAT-file Platform: posix, Created on: Mon Aug  7 08:45:12 2017',
 '__version__': '1.0'}
Run Code Online (Sandbox Code Playgroud)

cooformat 不实现项目分配。 csrcsc执行它,但会抱怨。但它们是计算的正常格式。 lildok是迭代分配的最佳格式。