我试图将一些真实的数据解析到一个.mat对象中,以便在我的matlab脚本中加载。
我得到了这个错误:
TypeError:'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') 有什么建议吗?
发布于 2017-08-07 15:48:38
使用coo_matrix构造此矩阵,使用(data,(row,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如果您将它保存到一个.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格式不实现项分配。csr和csc确实实现了它,但会抱怨。但它们是计算的正常格式。lil和dok是迭代分配的最佳格式。
发布于 2017-08-07 13:23:03
使用稀疏格式,它支持高效的索引,如矩阵
这是一种增量构造稀疏矩阵的有效结构。 ..。 允许有效访问单个元素的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] = 5https://stackoverflow.com/questions/45547924
复制相似问题