Python创建一个空的稀疏矩阵 [英] Python create an empty sparse matrix

查看:338
本文介绍了Python创建一个空的稀疏矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将某些真实数据解析为.mat对象,以将其加载到我的脚本.

I am trying to parse some real data into a .mat object to be loaded in my matlab script.

我收到此错误:

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

TypeError: 'coo_matrix' object does not support item assignment

我发现

I found coo_matrix. However, I am not able to assign values to it.

data.txt

10 45
11 12 
4 1

我想要一个大小为 100x100 的稀疏矩阵.并将1分配给

I would like to get a sparse matrix of size 100x100. And to assign 1's to

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

有什么建议吗?

推荐答案

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

Constructing this matrix with coo_matrix, using the (data, (rows, cols))` parameter format:

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转换而来):

If you save it to a .mat file for use in MATLAB, it will save it in csc format (having converted it from the 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是进行迭代分配的最佳格式.

coo format does not implement item assignment. csr and csc do implement it, but will complain. But they are the normal formats for calculation. lil and dok are the best formats for iterative assignment.

这篇关于Python创建一个空的稀疏矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆