scipy.sparse csr_matrix()

使用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
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值