Python创建一个空的稀疏矩阵。

5
我正在尝试将一些真实数据解析成一个 .mat 对象,以便在我的 脚本中加载。

我遇到了这个错误:

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

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

data.txt

10 45
11 12 
4 1

我希望获得一个大小为100x100的稀疏矩阵。并将1分配给
Mat(10, 45) = 1
Mat(11, 12) = 1
Mat(4, 1) = 1

代码

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')  

任何建议请?

coo_matrix 接受数据参数。请查看其文档。 - hpaulj
2个回答

10

使用一种稀疏格式,支持高效的索引,例如 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

1
你想要 M = dok_matrix((100, 100))。这也是问题中的一个错误。 - Daniel F
1
我的书面答案已经过时了。:/ 此外,如果您绝对需要'coo'表示法,您可以在最后进行转换,即M = M.tocoo() - Uvar
np :) 在别人的代码中找到愚蠢的语法错误总是更容易。而我自己的代码中却总是找不到。 - Daniel F
@DanielF:“啊,只有三行代码……我为什么要测试呢……会出什么问题呢” :-) - sascha

2
使用(data,(rows,cols))格式,使用coo_matrix构建此矩阵:
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

如果您将其保存到.mat文件中供MATLAB使用,它将以 csc 格式保存(已从 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'}

coo格式不支持元素赋值。csrcsc格式实现了元素赋值,但会产生警告。但它们是常规的计算格式。lildok是迭代赋值的最佳格式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接