-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path3graphs.py
More file actions
306 lines (244 loc) · 5.86 KB
/
Copy path3graphs.py
File metadata and controls
306 lines (244 loc) · 5.86 KB
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import sys
import csv
import numpy as np
import scipy
import matplotlib.pyplot as plt
import math, datetime
from scipy.stats import mode
def getrating(data, uid, mid):
for d in data:
#print d
if d[0]== uid and d[1] == mid:
return d[2]
return 0
#scipy.stats.pearson(array1, array2)
def pearsoncor(a,b):
n = len(a)
nf = float(n)
meana = sum(a)/nf
meanb = sum(b)/nf
num = 0
denuma = 0
denumb = 0
for x in range(n):
va = meana - a[x]
vb = meanb - b[x]
num = num + va * vb
denuma = denuma + va * va
denumb = denumb + vb * vb
denum = math.sqrt(denuma)*math.sqrt(denumb)
sim = num/denum
return sim
def manhattandist(a,b):
dist = 0
for x in range(len(a)):
dist = dist + abs(a[x] - b[x])
return dist
def item_cf(data, uids, mids, userID, movieID, distance, k, i):
movies = []
def getrating(uid, mid):
for d in rdata[mid]:
if d[0]== uid and d[1] == mid:
rdata[mid].remove(d)
return d[2]
return 0
movies.append([0 for x in range(len(uids))])
rdata = [[] for x in range(len(mids)+1)]
for d in data:
rdata[d[1]].append(d)
for mn in mids:
movies.append([])
mrs = []
mrs.append(0)
for un in uids:
mrs.append(0)
rat = getrating(un, mn)
mrs[un] = rat
#print mrs[un], rat
movies[mn] = mrs
dists = []
mdata = movies[movieID]
for mn in mids:
if mn == movieID:
continue
if distance:
dis = manhattandist(mdata, movies[mn])
else:
sim = pearsoncor(mdata, movies[mn])
# convert into distance from similarity
dis = 1 - sim
# only consider people with rating if i == 1
if i == 1:
if movies[mn][userID] == 0:
continue
dists.append([mn, dis])
for x in range(len(dists)):
for y in range(x, len(dists)):
if dists[y][1] < dists[x][1]:
dists[x], dists[y] = dists[y], dists[x]
l = k
if k > len(dists):
l = len(dists)
kratings = []
for x in range(l):
kratings.append(movies[dists[x][0]][userID])
kratings = sorted(kratings)
m = l/2
if k%2 == 0:
urating = float((kratings[m-1] + kratings[m]))/2
else:
urating = kratings[int(m)]
return urating
def user_cf(data, uids, mids, userID, movieID, distance, k, i):
people = []
def getrating(uid, mid):
for d in rdata[mid]:
if d[0]== uid and d[1] == mid:
rdata[mid].remove(d)
return d[2]
return 0
people.append([0 for x in range(len(mids))])
rdata = [[] for x in range(len(mids)+1)]
for d in data:
rdata[d[1]].append(d)
for un in uids:
people.append([])
prs = []
prs.append(0)
for mn in mids:
prs.append(0)
rat = getrating(un, mn)
prs[mn] = rat
people[un] = prs
# finding top k
dists = []
udata = people[userID]
for un in uids:
if un == userID:
continue
if distance:
dis = manhattandist(udata, people[un])
else:
sim = pearsoncor(udata, people[un])
# convert into distance from similarity
dis = 1 - sim
# only consider people with rating if i == 1
if i == 1:
if people[un][movieID] == 0:
continue
dists.append([un, dis])
for x in range(len(dists)):
nosort = True
for y in range(x, len(dists)):
if dists[y][1] < dists[x][1]:
nosort = False
dists[x], dists[y] = dists[y], dists[x]
if nosort:
break
l = k
if k > len(dists):
l = len(dists)
kratings = []
for x in range(l):
kratings.append(people[dists[x][0]][movieID])
urating = mode(kratings)
urating = float(urating[0])
return urating
def read_file(datafile):
dfile = open(datafile, "r")
dat = dfile.read().strip()
dat = dat.split("\n")
data = []
mids = []
ratings = []
uids = []
for d in dat:
# userid, itemid, rating, timestamp
d = d.split("\t")
uid = int(d[0])
iid = int(d[1])
rating = int(d[2])
tstamp = int(d[3])
uids.append(uid)
mids.append(iid)
data.append([uid, iid, rating, tstamp])
mids = list(set(sorted(mids)))
uids = list(set(sorted(uids)))
return data, mids, uids
def plotgraphs(datafile):
# Read data from file
data, mids, uids = read_file(datafile)
print len(data)
people = []
rdata = [[] for x in range(len(mids)+1)]
for d in data:
rdata[d[1]].append(d)
def getrating(uid, mid):
for d in rdata[mid]:
if d[0]== uid and d[1] == mid:
rdata[mid].remove(d)
return d[2]
return 0
people.append([0 for x in range(len(mids))])
for un in uids:
people.append([])
prs = []
prs.append(0)
for mn in mids:
prs.append(0)
rat = getrating(un, mn)
prs[mn] = rat
people[un] = prs
nperson = len(uids)
pairperson = 0
nmovieslist = []
for x in range(nperson):
for y in range(x+1, nperson):
nmovies = 0
for z in range(len(mids)):
if people[x][z] != 0 and people[y][z] != 0:
nmovies = nmovies + 1
nmovieslist.append(nmovies)
nmovieslist = list(sorted(nmovieslist))
mean = sum(nmovieslist)/len(nmovieslist)
median = nmovieslist[int(len(nmovieslist)/2)]
#print nmovieslist
print "mean: ", mean
print "median: ", median
plt.hist(nmovieslist,len(set(nmovieslist))-1)
plt.xlim(min(nmovieslist), max(nmovieslist))
plt.xlabel("Number of movies reviewed in common")
plt.ylabel("Number of user pairs")
plt.savefig("3asolution.pdf")
plt.close()
rdata = [[] for x in range(len(mids)+1)]
for d in data:
rdata[d[1]].append(d)
movies = []
movies.append(0)
for mn in mids:
movies.append(0)
numrev = 0
for un in uids:
rat = getrating(un, mn)
if rat != 0:
numrev = numrev + 1
movies[mn] = numrev
#print mn, movies[mn], numrev
#print len(movies)
print "maximum: ", movies.index(max(movies)), max(movies)
movies = movies[1:]
print "miniumum: ", movies.index(min(movies))+1, min(movies)
movies = list(sorted(movies))
#print movies
movies.reverse()
plt.plot(range(1, len(movies)+1), movies)
plt.xlabel("Movie's number in order")
plt.ylabel("Number of reviews")
#plt.show()
plt.savefig("3bsolutoin.pdf")
plt.close()
if __name__ == "__main__":
# A fully specified path to a file like u.data
datafile = sys.argv[1]
plotgraphs(datafile )