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

问题描述 投票:0回答:1

我正在尝试通过阅读文档来创建稀疏矩阵。

所以,根据文档(https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html):

enter image description here

当我尝试:

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

我得到一个例外:

文件“”,第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:语法无效

当我尝试:

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

再次出现错误消息:

ValueError:只接受2个非关键字参数

我的目的是创建一个矩阵,其中包含带索引的列 2,3,4,5,7,7 其中相应的行具有索引 0,1,2,3,2,1

(即,(0,2),(1,3),(2,4)等)。

python scipy sparse-matrix
1个回答
0
投票

你应该全力以赴

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

请注意,您需要指定矩阵的形状(这里我通过参数shape将矩阵设置为方形8x8矩阵)。还要注意数组的顺序和圆括号的使用!

您可以通过转换为密集格式来验证这是否令人满意:

my_csr.toarray()
© www.soinside.com 2019 - 2024. All rights reserved.