-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathforset.py
107 lines (60 loc) · 1.98 KB
/
forset.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import numpy as np
import MySQLdb
conn = MySQLdb.connect(host='localhost',user='root',passwd='shiva123',db='forsit')
query1 = "select * from challenges_properties"
result = conn.query(query1)
result = conn.store_result()
challenges = result.fetch_row(maxrows=0)
challenges = np.array(challenges)
query2 = "select * from user_properties"
conn.query(query2)
result = conn.store_result()
user = result.fetch_row(maxrows=0)
user = np.array(user)
query3 = "select * from user_challenges"
conn.query(query3)
result = conn.store_result()
user_challenges = result.fetch_row(maxrows=0)
R = user_challenges
N = len(R)
M = len(R[0])
P = user
Q = challenges
print(P)
print(Q)
K = len(P[0])
nP, nQ = matrix_factorization(R, P, Q, K)
print(nP)
print(nQ)
numpy.savetxt('P_matrix.txt', nP, fmt='%f', newline='\n' )
numpy.savetxt('Q_matrix.txt', nQ, fmt='%f',newline='\n')
nR = numpy.dot(nP, nQ.T)
print(R)
print(nR)
numpy.savetxt('New_R_matrix.txt',nR, fmt='%f',newline='\n')
def norm(P):
Norm=0
for i in range(len(P)):
for j in range(len(P[0])):
Norm+=pow(P[i][j],2)
return Norm
def matrix_factorization(R,U,I,K,steps=3000,alpha=0.002,beta=0.02):
I = I.T
for step in range(steps):
for user in range(len(R)):
for item in range(len(R[0])):
if R[user][item]>0 :
eij = R[user][item]-numpy.dot(U[user,:],I[:,item])
for k in range(K):
U[user][k]+=alpha*(2*eij*I[k][item]-beta*U[user][k])
I[k][item]+=alpha*(2*eij*U[user][k]-beta*I[k][item])
currentR=numpy.dot(U,I)
current_e2=0
for i in range(len(R)):
for j in range(len(R[0])):
if R[i][j]>0:
current_e2+=pow(R[i][j] - currentR[i][j],2)
current_e2+=(beta/2)*(pwo(norm(U),2) + pow(norm(I),2));
if current_e2<0.001:
break
return U,I.T