[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

你可能感兴趣的:(model-pytorch,numpy,python,机器学习)