-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfriend.py
431 lines (350 loc) · 9.18 KB
/
friend.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
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
from __future__ import division
import csv
from math import *
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
import tkinter as tk
from tkinter import messagebox
from tkinter import *
from sklearn.cluster import DBSCAN
from sklearn import metrics
class User():
id = 0
bookmarks = {}
tags = {}
friends = {}
count = 0
def __init__(self,id):
self.id = id
self.tags = {}
self.bookmarks = {}
self.friends ={}
self.count = 0
# array of objects
users = {}
def read_data():
for line in open('dataset/user_taggedbookmarks.dat'):
fields = line.split('\t')
uid = fields[0]
bid = fields[1]
tid = fields[2]
if not uid in users:
users[uid] = User(uid)
if not tid in users[uid].tags:
users[uid].tags[tid] = 0
users[uid].count += 1
users[uid].tags[tid] += 1
users[uid].bookmarks[bid] = 1
read_data()
class Bookmark():
id = 0
tags = {}
def __init__(self,id):
self.id = id
self.tags = {}
bookmarks = {}
def read_bookmarks():
for line in open('dataset/bookmark_tags.dat'):
fields = line.split('\t')
bid = fields[0]
tid = fields[1]
weight = fields[2]
if(not bid in bookmarks):
bookmarks[bid] = Bookmark(bid)
bookmarks[bid].tags[tid] = fields[2]
read_bookmarks()
print('Bookmarks Read')
def biclustering(matrix):
model = SpectralBiclustering()
model.fit(matrix)
fit_data = data[np.argsort(model.row_labels_)]
fit_data = fit_data[:, np.argsort(model.column_labels_)]
return fit_data
#Getting similarity between 2 bookmarks
def book_sim(i,j):
if(i in bookmarks and j in bookmarks):
# dot product
intersection = len(list( (set(bookmarks[i].tags.keys()) & set(bookmarks[j].tags.keys())) ))
# normalization
union = sqrt(len(list( (set(bookmarks[i].tags.keys())))))*len(list( (set(bookmarks[j].tags.keys()))))
# union =len(list( (set(bookmarks[i].tags.keys()) | set(bookmarks[j].tags.keys())) ))
sim=intersection/union
return sim
else:
return -1
S = []
n = 1867
total_tags = 53388
alpha = 0.1
beta = 0.1
def tag_similarity(key1,key2):
#calculate mean_vu and mean_vm
vu_mean = vm_mean = 0
for key in users[key1].tags:
vu_mean += users[key1].tags[key]
vu_mean = vu_mean/total_tags
for key in users[key2].tags:
vm_mean += users[key2].tags[key]
vm_mean = vm_mean/total_tags
#Pearsons formula to calulate similarity
numerator = 0
den1 = den2 = 0
for key in users[key1].tags:
if key in users[key2].tags:
#vuj, vmj are tag based user profiles for the tag 'key'
vuj = users[key1].tags[key]/users[key1].count
vmj = users[key2].tags[key]/users[key2].count
numerator += ( (vuj - vu_mean)*(vmj - vm_mean) )
den1 += pow((vuj-vu_mean),2)
den2 += pow((vmj-vm_mean),2)
#print(key1,den1,den2)
den1 = den1**(1.0/2)
den2 = den2**(1.0/2)
if(den1 != 0 and den2 != 0):
ans = numerator/(den1*den2)
return ans
else:
return 0
# db1=DBSCAN(eps=2, min_samples=4).fit_predict(X)
def user_interaction(key1,key2):
numerator = 0
den = len(users[key1].bookmarks)
for key in users[key1].bookmarks:
if key in users[key2].bookmarks:
numerator += 1
ans = numerator/den
return ans
#Store contacts of users
contacts = {}
for line in open('dataset/user_contacts.dat'):
fields = line.split('\t')
if(not ( ((fields[0],fields[1]) in contacts) or ((fields[1],fields[0])in contacts) )):
contacts[(fields[0],fields[1])] = 1
#resources = {}
"""
booktags = {}
reader = csv.reader(open('booktags.csv', 'r'))
for row in reader:
k, v = row
booktags[k] = v
tagsim = {}
def ressim():
flag = 0
for key1,value1 in booktags.items():
fields1 = "a"
fields2 = "b"
union = 0
intersection = 0
for key2,valu1e2 in booktags.items():
if(key1 != key2):
fields1=key1.split("'")
fields2=key2.split("'")
union = union + 1
if(booktags[key1] == booktags[key2]):
intersection += 1
flag = 1 #just to test for 1 pair
tagsim[(fields1[1],fields2[1])] = intersection/union
if(flag):
break
"""
total_usrs = len(users)
true_positive = 0
true_recs = 0
g_novel = 0
g_satisfied = 0
g_stf_denom = 0
g_seren_denom = 0
g_novel_denom = 0
def friend_reccomder(key1):
A=[]
counter = 0
tr = 0
tp = 0
satisfied = 0
satisfied_denom = 0
novel = 0
serendipitous = 0
seren_denom = 0
novel_denom = 0
beta1=beta
while(len(A)<2):
if not key1 in users:
A.append(0)
#for key1 in users:
else:
counter += 1
#print(''+str(counter)+'/'+str(total_usrs))
u = users[key1]
flag = 0
recom = 0
for key2 in users:
if(key1 != key2):
m = users[key2]
#sim = tag_similarity(key1,key2)
user_interest1 = user_interaction(key1,key2)
user_interest2 = user_interaction(key2,key1)
#print(sim)
if(user_interest1 > beta1 or user_interest2 > beta1):
#this friend is recommended to user (key1)
# S.append((key1,key2))
tr += 1 #total recommendations
recom = 1 #current friend is recommended
#print("tr %s"%(tr))
#To check if it is a positive contact
if( ( (key1,key2) in contacts ) or ( (key2,key1) in contacts)):
tp += 1
flag = 1
#To check if recommended bookmarks are serendipitous
for i in users[key2].bookmarks:
check = 1
for j in users[key1].bookmarks:
sim = book_sim(i,j)
if(sim>0):
if(not key2 in A):
A.append((key2))
check = 0
break
if(check==1):
serendipitous += 1
seren_denom += 1
beta1=beta1-0.01
#To check if recommended bookmarks are novel
return A
def bookmark_reccomder(key1):
C=[]
alpha1 = 0.5
while (len(C)<2):
if(not key1 in users):
C.append(0)
for key2 in users:
if( ( (key1,key2) in contacts ) or ( (key2,key1) in contacts)):
for i in users[key2].bookmarks:
for j in users[key1].bookmarks:
sim = book_sim(i,j)
if(sim>alpha1):
if(not i in C):
C.append(i)
alpha1-=0.05
return C
#A = friend_reccomder('1')
#C=bookmark_reccomder('8')
def ans_in_str(C):
D=""
for i in range(0,len(C)):
for line in open('dataset/bookmarks.dat',encoding = "ISO-8859-1"):
fields = line.split('\t')
bid = fields[0]
burl = fields[5]
if(C[i]==0):
return "User not found"
if(bid == C[i]):
D=D+burl;
return D
#print(A)
def frs_in_str(C):
D=""
for i in range(0,len(C)):
if(C[i]==0):
return "User not found"
D=D+str(C[i])+'\n'
return D
def frs():
counter = 0
tr = 0
tp = 0
satisfied = 0
satisfied_denom = 0
novel = 0
serendipitous = 0
seren_denom = 0
novel_denom = 0
for key1 in users:
counter += 1
print(''+str(counter)+'/'+str(total_usrs))
u = users[key1]
flag = 0
recom = 0
for key2 in users:
if(key1 != key2):
m = users[key2]
#sim = tag_similarity(key1,key2)
user_interest1 = user_interaction(key1,key2)
user_interest2 = user_interaction(key2,key1)
#print(sim)
if(user_interest1 > beta or user_interest2 > beta):
#this friend is recommended to user (key1)
S.append((key1,key2))
tr += 1 #total recommendations
recom = 1 #current friend is recommended
#print("tr %s"%(tr))
#To check if it is a positive contact
if( ( (key1,key2) in contacts ) or ( (key2,key1) in contacts)):
tp += 1
flag = 1
#To check if recommended bookmarks are serendipitous
for i in users[key2].bookmarks:
check = 1
for j in users[key1].bookmarks:
sim = book_sim(i,j)
if(sim>0.5):
check = 0
break
#To check if recommended bookmarks are novel
for b in users[key2].bookmarks:
if(not b in users[key1].bookmarks):
novel += 1
novel_denom += 1
if(recom == 1):
satisfied_denom += 1
if(flag == 1 and recom == 1):
satisfied += 1
global g_stf_denom
g_stf_denom = satisfied_denom
global true_positive
true_positive= tp
global true_recs
true_recs = tr
global g_novel
g_novel = novel
global g_satisfied
g_satisfied = satisfied
global g_novel_denom
g_novel_denom = novel_denom
frs()
precision = true_positive/true_recs
percentage_satisfied = g_satisfied/g_stf_denom
novelty = g_novel/g_novel_denom
print("Satisfied Users: %s " %(percentage_satisfied))
print("Precision: %s " %(precision))
print("Novelty: %s " %(novelty))
from tkinter import *
from tkinter.messagebox import *
def show_answer():
# Ans = int(num1.get()) + int(num2.get())
C=bookmark_reccomder(str(num1.get()))
ans=ans_in_str(C)
#print(ans)
Label(main, text = "Bookmark \nReccomendations").grid(row=2)
blank.delete(1.0,END)
blank.insert(1.0,str(ans))
def show_friend():
C=friend_reccomder(str(num1.get()))
ans=frs_in_str(C)
#print(ans)
Label(main, text = "Friend \nReccomendations").grid(row=2)
blank.delete(1.0,END)
blank.insert(1.0,str(ans))
main = Tk()
Label(main, text = "Enter User ID").grid(row=0)
Label(main, text = "Reccomendations").grid(row=2)
num1 = Entry(main)
# num2 = Entry(main)
blank = Text(main, width = 40, height = 20,font=("Courier", 14))
num1.grid(row=0, column=1)
# num2.grid(row=1, column=1)
blank.grid(row=2, column=1)
Button(main, text='Quit', command=main.destroy).grid(row=4, column=0, sticky=W, pady=4)
Button(main, text='Bookmarks', command=show_answer).grid(row=4, column=1, sticky=W, pady=4)
Button(main, text='Friends', command=show_friend).grid(row=4, column=1, pady=4)
mainloop()