简体   繁体   English

在Python中使用SciPy创建稀疏矩阵

[英]Creating a sparse matrix with SciPy in Python

I am trying to create a sparse matrix by reading the documentation. 我正在尝试通过阅读文档来创建稀疏矩阵。

So, according to the documentation ( https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html ): 因此,根据文档( https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html ):

在此处输入图片说明

When I try: 当我尝试:

csr_matrix((data = np.array([1, 1, 1, 1, 1, 1]), indices = np.array(2, 3, 4, 5, 7, 7), indptr = np.array([0, 1, 2, 3, 2, 1])))

I get an exception: 我有一个例外:

File "", line 1 csr_matrix((data = np.array([1, 1, 1, 1, 1, 1]), indices = np.array(2, 3, 4, 5, 7, 7), indptr = np.array([0, 1, 2, 3, 2, 1]))) ^ SyntaxError: invalid syntax 文件“”,第1行csr_matrix((data = np.array([1,1,1,1,1,1]),index = np.array(2,3,4,5,7,7),indptr = np.array([0,1,2,3,2,1])))^ SyntaxError:语法无效

When I try: 当我尝试:

csr_matrix((np.array([1, 1, 1, 1, 1, 1]), np.array(2, 3, 4, 5, 7, 7), np.array([0, 1, 2, 3, 2, 1])))

again an error message results: 再次出现错误消息:

ValueError: only 2 non-keyword arguments accepted ValueError:仅接受2个非关键字参数

My intention here is to create a matrix which has ones in the columns with indexes 我的目的是创建一个在索引列中有一个矩阵的矩阵
2, 3, 4, 5, 7, 7 2,3,4,5,7,7
where the corresponding rows have indexes 相应行具有索引的位置
0, 1, 2, 3, 2, 1 0、1、2、3、2、1

(ie, (0, 2) , (1, 3) , (2, 4) etc). (即(0,2),(1、3),(2、4)等)。

You should be all set with 你应该都准备好了

from scipy.sparse import csr_matrix
import numpy as np

my_csr = csr_matrix((np.array([1,1,1,1,1,1]), (np.array([0, 1, 2, 3, 2, 1]), np.array([2, 3, 4, 5, 7, 7]))), shape = (8,8))

Note that you need to specify the shape of the matrix (here I set the matrix to be a square 8x8 matrix via the parameter shape ). 请注意,您需要指定矩阵的形状(此处通过参数shape将矩阵设置为正方形8x8矩阵)。 Note also the order of the arrays and the use of round brackets! 注意数组的顺序和圆括号的使用!

You can verify that this is satisfactory by converting to a dense format: 您可以通过转换为密集格式来验证是否令人满意:

my_csr.toarray()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM