Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- def originalR(rev, the_j):
- Cj = [x for i, j, x in rev if j == the_j]
- return sum(Cj) / len(Cj)
- def f(r, x, alpha):
- return 1 if abs(r-x) <= alpha else 0
- def r(listOfi, j, T, X):
- return sum([T[i]*X[(i, j)] for i in listOfi])/sum([T[i] for i in listOfi])
- def t(i, the_r, listOfj, X, alpha):
- return float((1+ sum([f(the_r[j], X[(i, j)], alpha) for j in listOfj])))/float((2+len(listOfj)))
- the_file = sys.argv[1]
- with open(the_file, 'r') as f:
- IOreviw = f.read()
- rev = [[float(x) for x in X.split(' ') if x<> ''] for X in IOreviw.split('\n') if X.split('')<>[]]
- #retrive the alpha
- alpha = float(sys.argv[2])
- #calculate the new one
- #what states do we have to hold that change as the file is read in
- C = {} # keys are j values are arrays of
- P = {} # keys are i
- X = {} # keys are (i,j) pairs
- T = {}
- the_r = {}
- #main loop
- for i,j,x in rev:
- print('%d:%d:%d' % (i,j,x))
- #If this is the first rating from customer i, using eq. (3) to initialise the trust level of customer i with the value corresponding to Pi ={} (i.e. the empty set);
- if not i in T:
- T[i] = 1./2
- #Using eq. (2) and the current trust levels of the relevant customers to calculate the overall rating for product j;
- #add the persons rating to the ratings for j
- #add this product to the set of products reviewed by i
- if i in P:
- P[i].append(j) #assume the person only review the product once
- else:
- P[i] = [j]
- #add this consumer to the set of people who have reviwed j
- if j in C:
- C[j].append(i) #same assumption
- else:
- C[j] = [i]
- #add i's review of product j
- X[(i,j)] = x
- #calulate the rating
- the_r[j] = r(C[j],j,T,X)
- #Using eq. (3) to update the trust levels of all customers who provided ratings for product j so far;
- for i in C[j]:
- T[i] = t(i,the_r,P[i],X,alpha)
- #Recalculating the overall ratings for the products other than product j affected by this updating of trust levels
- for j in P[i]:
- the_r[j] = r(C[j],j,T,X)
- #should this be for all of i in Cj?
- print('r:%.2f;t:%.2f;i:%d;j:%d;x:%d;' % (the_r[j],T[i],i,j,x))
- ###################################################
- outfile = sys.argv[3]
- #for each product in the product list
- with open(outfile,'w+') as f:
- for j in list(set([j for i,j,x in rev[:-1]])):
- f.write('%d %.2f (%.2f)\n'%(j,the_r[j], 1))
- f.write('\n')
- for i in list(set([i for i,j,x in rev[:-1]])):
- f.write('%d %.2f\n' % (i,T[i]))
Advertisement
Add Comment
Please, Sign In to add comment