-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.py
69 lines (63 loc) · 2.29 KB
/
test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import numpy as np
import math
import matplotlib.pyplot as plt
# 定义矩阵分解函数
def Matrix_decomposition(R, P, Q, N, M, K, alpha=0.0002, beta=0.02):
Q = Q.T # Q 矩阵转置
loss_list = [] # 存储每次迭代计算的 loss 值
for step in range(5000):
# 更新 R^
for i in range(N):
for j in range(M):
if R[i][j] != 0:
# 计算损失函数
error = R[i][j]
for k in range(K):
error -= P[i][k] * Q[k][j]
# 优化 P,Q 矩阵的元素
for k in range(K):
P[i][k] = P[i][k] + alpha * (2 * error * Q[k][j] - beta * P[i][k])
Q[k][j] = Q[k][j] + alpha * (2 * error * P[i][k] - beta * Q[k][j])
loss = 0.0
# 计算每一次迭代后的 loss 大小,就是原来 R 矩阵里面每个非缺失值跟预测值的平方损失
for i in range(N):
for j in range(M):
if R[i][j] != 0:
# 计算 loss 公式加号的左边
data = 0
for k in range(K):
data = data + P[i][k] * Q[k][j]
loss = loss + math.pow(R[i][j] - data, 2)
# 得到完整 loss 值
for k in range(K):
loss = loss + beta / 2 * (P[i][k] * P[i][k] + Q[k][j] * Q[k][j])
loss_list.append(loss)
plt.scatter(step, loss)
# 输出 loss 值
if (step + 1) % 1000 == 0:
print("loss={:}".format(loss))
# 判断
if loss < 0.001:
print(loss)
break
plt.show()
return P, Q
if __name__ == "__main__":
N = 5
M = 4
K = 5
R = np.array([[5, 3, 0, 1],
[4, 0, 0, 1],
[1, 1, 0, 5],
[1, 0, 0, 4],
[0, 1, 5, 4]]) # N=5,M=4
print("初始评分矩阵:")
print(R)
# 定义 P 和 Q 矩阵
P = np.random.rand(N, K) # N=5,K=2
Q = np.random.rand(M, K) # M=4,K=2
print("开始矩阵分解:")
P, Q = Matrix_decomposition(R, P, Q, N, M, K)
print("矩阵分解结束。")
print("得到的预测矩阵:")
print(np.dot(P, Q))