使用scipy.sparse的稀疏矩阵csr_matrix()

创建方法

可以传入一个dense矩阵或numpy array

import scipy.sparse as sp
import numpy as np
d_A = np.array([[1, 0, 3],
                [0, 5, 6],
                [7, 0, 0]])
s_A = sp.csr_matrix(d_A)

可以创建一个空的稀疏矩阵

import scipy.sparse as sp
s = sp.csr_matrix((3, 3))
print(s.shape)
>>> (3, 3)

利用行列索引来创建

import scipy.sparse as sp
row = [0, 1, 2]
col = [0, 0, 1]
value = [1, 2, 3]
s = sp.csr_matrix((value, (row, col)), shape=[3, 3])
print(s)
>>>   (0, 0)        1
	  (1, 0)        2
	  (2, 1)        3
加法

两个稀疏矩阵相加直接加

row = [0, 1, 2]
col = [0, 0, 1]
value = [1, 2, 3]
a = sp.csr_matrix((value, (row, col)), shape=[3, 3])
b = a
c = a+b
print(c)
>>>   (0, 0)        2
	  (1, 0)        4
	  (2, 1)        6
乘法

可以是两个稀疏矩阵相乘,乘完后c还是稀疏矩阵

row = [0, 1, 2]
col = [0, 0, 1]
value = [1, 2, 3]
a = sp.csr_matrix((value, (row, col)), shape=[3, 3])
b = a
c = a.dot(b)
print(c)
>>>   (0, 0)        1
	  (1, 0)        2
	  (2, 0)        6

也可以是稀疏矩阵乘以一个稠密矩阵(顺序不能换,不能是稠密矩阵乘以稀疏矩阵,如果需要则先调换二者顺序为 sparse x dense,乘完再转置回来),乘完之后c是稠密矩阵,这类似于tensorflow中的 tf.sparse_tensor_dense_matmul 操作

row = [0, 1, 2]
col = [0, 0, 1]
value = [1, 2, 3]
a = sp.csr_matrix((value, (row, col)), shape=[3, 3])
b = a.todense()
c = a.dot(b)
print(c)
>>> [[1 0 0]
	 [2 0 0]
	 [6 0 0]]
提取行列

稀疏矩阵提取行列和稠密矩阵提取一样

row = [0, 1, 2]
col = [0, 0, 1]
value = [1, 2, 3]
a = sp.csr_matrix((value, (row, col)), shape=[3, 3])
print('a的第0行\n', a[0], '\n a的第0列\n', a[:, 0])
>>>  a的第0(0, 0)       1
	 a的第0(0, 0)       1
	   (1, 0)        2
Logo

助力广东及东莞地区开发者,代码托管、在线学习与竞赛、技术交流与分享、资源共享、职业发展,成为松山湖开发者首选的工作与学习平台

更多推荐