-
Notifications
You must be signed in to change notification settings - Fork 0
/
IIcollaborativeWithBaseLine.py
185 lines (138 loc) · 4.72 KB
/
IIcollaborativeWithBaseLine.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
import random
import time
from numpy import linalg as LA
no_of_users = 610
no_of_movies = 10000
no_of_nearest_neighbours = 5
rating_matrix = np.zeros((no_of_users,no_of_movies))
pearson_matrix_ii = np.zeros((no_of_users,no_of_movies))
pearson_matrix_ii_test = np.zeros((no_of_users,no_of_movies))
item_item_similarity = {}
df = pd.read_csv('ratings10k.csv', delim_whitespace=False, sep=',', header=None)
df = df.drop(df.index[0])
df = df.values.tolist()
# shuffle
random.Random(4).shuffle(df)
# random.Random(4).shuffle(df2)
# divide in test and train
train, test = train_test_split(df, test_size=0.2)
for each in test: # creating rating matrix
userId = int(int(each[0]) - 1)
movieId = int(int(each[1]) - 1)
rating = float(each[2])
rating_matrix[userId][movieId] = rating
# print(rating_matrix)
def cosineSimilarity(vec1,vec2):
score = float(np.dot(vec1,vec2))
if score==0:
return 0
score /= LA.norm(vec1)
score /= LA.norm(vec2)
return score
def calSimMovies():
for movie1 in range(len(pearson_matrix_ii)):
print("similarity movie no",movie1)
ls = []
for movie2 in range(len(pearson_matrix_ii)):
ls.append(float(cosineSimilarity(pearson_matrix_ii[movie1],pearson_matrix_ii[movie2])))
# item_item_similarity[(movie1,movie2)] = float(cosineSimilarity(pearson_matrix_ii[movie1],pearson_matrix_ii[movie2]))
# item_item_similarity[(movie2,movie1)] = item_item_similarity[(movie1,movie2)]
item_item_similarity[movie1] = ls
def getIndex(movie):
movie = int(movie)
ls = item_item_similarity.get(movie)
if ls == None:
return -1
if np.sum(ls)==0:
return -1
ans = []
ls_cpy = ls[:]
ls_cpy.sort(reverse=True)
for i in range(no_of_nearest_neighbours):
ans.append(ls.index(ls_cpy[i]))
return ans
pearson_matrix_ii[:] = rating_matrix
pearson_matrix_ii_test[:] = rating_matrix
pearson_matrix_ii_test = np.array(pearson_matrix_ii_test.transpose())
pearson_matrix_ii = np.array(pearson_matrix_ii)
print(pearson_matrix_ii.shape)
pearson_matrix_ii = pearson_matrix_ii.transpose()
print(pearson_matrix_ii.shape)
print(pearson_matrix_ii)
movie_mean = np.mean(pearson_matrix_ii, axis = 1, dtype=np.float)
user_mean = np.mean(pearson_matrix_ii, axis = 0, dtype=np.float)
global_mean = np.mean(pearson_matrix_ii, dtype=float)
# movie_mean = np.sum(pearson_matrix_ii, axis = 1, dtype=np.float)
# for movie in range(len(pearson_matrix_ii)):
# count = 0
# for user in range(len(pearson_matrix_ii[0])):
# if pearson_matrix_ii[movie][user]==0:
# continue
# else:
# count += 1
# if count!=0:
# print("count",count)
# movie_mean[movie] /= count
print(movie_mean)
# print(movie_mean1)
a = time.time()
for i in range(no_of_movies):
print("centering movie",i)
for j in range(no_of_users):
if pearson_matrix_ii[i][j] != 0:
pearson_matrix_ii[i][j] -= movie_mean[i]
b = time.time()
print(pearson_matrix_ii)
print("time taken",b-a)
# print(item_item_similarity)
calSimMovies()
# print(item_item_similarity)
RMSE = float(0)
MAE = float(0)
count = 0
a = time.time()
# ls1 = item_item_similarity.keys()
# print(ls1)
# ls2 = []
for i in range(len(test)):
movie = int(int(test[i][1])-1)
# ls2.append(movie)
indices = getIndex(movie)
if indices==-1:
continue
print("found")
sim = item_item_similarity[movie]
print("Final movie",movie)
for j in range(no_of_users):
if pearson_matrix_ii_test[movie][j]==0:
continue
numerator = float(0)
denominator = float(0)
for index in range(len(indices)):
# sub = (user_mean[j] + movie_mean[index] - global_mean)
numerator += sim[index]*(pearson_matrix_ii_test[index][j] )
denominator += sim[index]
# print(numerator)
# print(denominator)
if numerator==0 or denominator==0:
# calculated_rating = 0
continue
else:
calculated_rating = numerator / denominator
baseline_estimate = (user_mean[j] + movie_mean[movie] - global_mean)
calculated_rating += baseline_estimate
e = pearson_matrix_ii_test[movie][j] - calculated_rating
RMSE += e**2
MAE += abs(e)
count +=1
b = time.time()
print(b-a)
RMSE /= count
RMSE = np.sqrt(RMSE)
MAE = MAE/count
print("RMSE",RMSE)
print("MAE",MAE)
# print(ls2)