[Numpy] csr_matrix | .todense() | .tocoo() |

csr_matrix

通过csr_matrix构建得到的是稀疏矩阵。

csr_matrix(((数据np, (行list, 列list)))

其中,数据是numpy形式,行和列是list,三者的长度要一致。
行、列一起定位数据的坐标位置。没有数据、坐标的部分,默认为0。

.todense()

将稀疏矩阵转为稠密矩阵。

.tocoo()

将稠密矩阵转为稀疏矩阵。

例子:

from scipy.sparse import *
import numpy as np

row = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2]  # 行指标(user)
col = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2]  # 列指标(items)
data1 = np.ones(11)  # len(row) = len(col) = 11
data2 = np.array([1,2,3,4,5,6,7,8,9,10,11])
team1 = csr_matrix((data1, (row, col)), shape=(3, 4))
team2 = csr_matrix((data2, (row, col)), shape=(3, 4))
print('team1:\n', team1)
print('team2:\n', team2)
print('team1(dense):\n', team1.todense())
print('team2(dense):\n', team2.todense())

team_coo1 = team1.tocoo()  # 返回稀疏矩阵的coo_matrix形式
team_coo2 = team2.tocoo()  # 返回稀疏矩阵的coo_matrix形式
print('team1(tocoo):\n', team_coo1)
print('team2(tocoo):\n', team_coo2)

输出结果:

team1:
  (0, 0)	1.0
  (0, 1)	1.0
  (0, 2)	1.0
  (0, 3)	1.0
  (1, 0)	1.0
  (1, 1)	1.0
  (1, 2)	1.0
  (1, 3)	1.0
  (2, 0)	1.0
  (2, 1)	1.0
  (2, 2)	1.0
team2:
  (0, 0)	1
  (0, 1)	2
  (0, 2)	3
  (0, 3)	4
  (1, 0)	5
  (1, 1)	6
  (1, 2)	7
  (1, 3)	8
  (2, 0)	9
  (2, 1)	10
  (2, 2)	11
team1(dense):
 [[1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 0.]]
team2(dense):
 [[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11  0]]
team1(tocoo):
  (0, 0)	1.0
  (0, 1)	1.0
  (0, 2)	1.0
  (0, 3)	1.0
  (1, 0)	1.0
  (1, 1)	1.0
  (1, 2)	1.0
  (1, 3)	1.0
  (2, 0)	1.0
  (2, 1)	1.0
  (2, 2)	1.0
team2(tocoo):
  (0, 0)	1
  (0, 1)	2
  (0, 2)	3
  (0, 3)	4
  (1, 0)	5
  (1, 1)	6
  (1, 2)	7
  (1, 3)	8
  (2, 0)	9
  (2, 1)	10
  (2, 2)	11
  • 11
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值