-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathranking.py
2580 lines (2334 loc) · 110 KB
/
ranking.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Implementation of pairwise ranking using scikit-learn LinearSVC
Reference:
"Large Margin Rank Boundaries for Ordinal Regression", R. Herbrich,
T. Graepel, K. Obermayer 1999
"Learning to rank from medical imaging data." Pedregosa, Fabian, et al.,
Machine Learning in Medical Imaging 2012.
Authors: Fabian Pedregosa <[email protected]>
Alexandre Gramfort <[email protected]>
See also https://github.com/fabianp/pysofia for a more efficient implementation
of RankSVM using stochastic gradient descent methdos.
"""
import itertools
import numpy as np
import matplotlib.pyplot as plt
'''
from sklearn.externals import joblib
from sklearn import svm, linear_model, cross_validation
from sklearn.linear_model import LinearRegression, LassoLarsCV, RidgeCV
from sklearn.linear_model.base import LinearClassifierMixin, SparseCoefMixin, BaseEstimator
import sklearn as sk
from sklearn.cross_validation import train_test_split
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.svm import SVC
def transform_pairwise(X, y):
"""Transforms data into pairs with balanced labels for ranking
Transforms a n-class ranking problem into a two-class classification
problem. Subclasses implementing particular strategies for choosing
pairs should override this method.
In this method, all pairs are choosen, except for those that have the
same target value. The output is an array of balanced classes, i.e.
there are the same number of -1 as +1
Parameters
----------
X : array, shape (n_samples, n_features)
The data
y : array, shape (n_samples,) or (n_samples, 2)
Target labels. If it's a 2D array, the second column represents
the grouping of samples, i.e., samples with different groups will
not be considered.
Returns
-------
X_trans : array, shape (k, n_feaures)
Data as pairs
y_trans : array, shape (k,)
Output class labels, where classes have values {-1, +1}
"""
X_new = []
y_new = []
y = np.asarray(y)
if y.ndim == 1:
y = np.c_[y, np.ones(y.shape[0])]
comb = itertools.combinations(range(X.shape[0]), 2)
for k, (i, j) in enumerate(comb):
if y[i, 0] == y[j, 0] or y[i, 1] != y[j, 1]:
# skip if same target or different group
continue
X_new.append(X[i] - X[j])
y_new.append(np.sign(y[i, 0] - y[j, 0]))
# output balanced classes
if y_new[-1] != (-1) ** k:
y_new[-1] = - y_new[-1]
X_new[-1] = - X_new[-1]
return np.asarray(X_new), np.asarray(y_new).ravel()
class RankSVM(svm.LinearSVC):
"""Performs pairwise ranking with an underlying LinearSVC model
Input should be a n-class ranking problem, this object will convert it
into a two-class classification problem, a setting known as
`pairwise ranking`.
See object :ref:`svm.LinearSVC` for a full description of parameters.
"""
def fit(self, X, y):
"""
Fit a pairwise ranking model.
Parameters
----------
X : array, shape (n_samples, n_features)
y : array, shape (n_samples,) or (n_samples, 2)
Returns
-------
self
"""
X_trans, y_trans = transform_pairwise(X, y)
super(RankSVM, self).fit(X_trans, y_trans)
return self
def decision_function(self, X):
return np.dot(X, self.coef_.ravel())
def predict(self, X):
"""
Predict an ordering on X. For a list of n samples, this method
returns a list from 0 to n-1 with the relative order of the rows of X.
The item is given such that items ranked on top have are
predicted a higher ordering (i.e. 0 means is the last item
and n_samples would be the item ranked on top).
Parameters
----------
X : array, shape (n_samples, n_features)
Returns
-------
ord : array, shape (n_samples,)
Returns a list of integers representing the relative order of
the rows in X.
"""
if hasattr(self, 'coef_'):
return np.argsort(np.dot(X, self.coef_.ravel()))
else:
raise ValueError("Must call fit() prior to predict()")
def score(self, X, y):
"""
Because we transformed into a pairwise problem, chance level is at 0.5
"""
X_trans, y_trans = transform_pairwise(X, y)
return np.mean(super(RankSVM, self).predict(X_trans) == y_trans)
def rankingAlgorithm1(X,y):
true_coef = np.random.randn(n_features)
Y = np.c_[y, np.mod(np.arange(n_samples), 5)] # add query fake id
# Y = y
cv = cross_validation.KFold(n_samples, 5)
train, test = next(iter(cv))
# make a simple plot out of it
pl.scatter(np.dot(X, true_coef), y)
pl.title('Data to be learned')
pl.xlabel('<X, coef>')
pl.ylabel('y')
#pl.show()
# print the performance of ranking
rank_svm = RankSVM().fit(X[train], Y[train])
print('Performance of ranking ', rank_svm.score(X[test], Y[test]))
from old code
# and that of linear regression
ridge = linear_model.RidgeCV(fit_intercept=True)
ridge.fit(X[train], y[train])
X_test_trans, y_test_trans = transform_pairwise(X[test], y[test])
score = np.mean(np.sign(np.dot(X_test_trans, ridge.coef_)) == y_test_trans)
print('Performance of linear regression ', score)
blocks = np.array([0, 1] * int((X.shape[0] / 2)))
X_train, y_train, b_train = X[train], y[train], blocks[train]
X_test, y_test, b_test = X[test], y[test], blocks[test]
#ridge = linear_model.Ridge(1.)
ridge = linear_model.RidgeCV(fit_intercept=True)
ridge.fit(X_train, y_train)
for i in range(2):
tau, _ = stats.kendalltau(ridge.predict(X_test[b_test == i]), y_test[b_test == i])
print('Kendall correlation coefficient for block %s: %.5f' % (i, tau))
return
def rankingAlgorithm2(X,y):
blocks = np.array([0, 1] * int((X.shape[0] / 2)))
cv = cross_validation.StratifiedShuffleSplit(y, test_size=.5)
train, test = next(iter(cv))
X_train, y_train, b_train = X[train], y[train], blocks[train]
X_test, y_test, b_test = X[test], y[test], blocks[test]
# --------------------------------------------------------------------------------------
# plot the result
idx = (b_train == 0)
np.random.seed(0)
theta = np.deg2rad(60)
w = np.array([np.sin(theta), np.cos(theta)])
pl.scatter(X_train[idx, 0], X_train[idx, 1], c=y_train[idx], marker='^', cmap=pl.cm.Blues, s=100)
pl.scatter(X_train[~idx, 0], X_train[~idx, 1], c=y_train[~idx], marker='o', cmap=pl.cm.Blues, s=100)
pl.arrow(0, 0, 8 * w[0], 8 * w[1], fc='gray', ec='gray', head_width=0.5, head_length=0.5)
pl.text(0, 1, '$w$', fontsize=20)
pl.arrow(-3, -8, 8 * w[0], 8 * w[1], fc='gray', ec='gray', head_width=0.5, head_length=0.5)
pl.text(-2.6, -7, '$w$', fontsize=20)
pl.axis('equal')
# pl.show()
# ---------------------------------------------------------------------------------------
ridge = linear_model.Ridge(1.)
ridge.fit(X_train, y_train)
coef = ridge.coef_ / np.linalg.norm(ridge.coef_)
# ----------------------------------------------------------------------------------------
pl.scatter(X_train[idx, 0], X_train[idx, 1], c=y_train[idx], marker='^', cmap=pl.cm.Blues, s=100)
pl.scatter(X_train[~idx, 0], X_train[~idx, 1], c=y_train[~idx], marker='o', cmap=pl.cm.Blues, s=100)
pl.arrow(0, 0, 7 * coef[0], 7 * coef[1], fc='gray', ec='gray', head_width=0.5, head_length=0.5)
pl.text(2, 0, '$\hat{w}$', fontsize=20)
pl.axis('equal')
pl.title('Estimation by Ridge regression')
# pl.show()
# ----------------------------------------------------------------------------------------
for i in range(2):
tau, _ = stats.kendalltau(ridge.predict(X_test[b_test == i]), y_test[b_test == i])
print('Kendall correlation coefficient for block %s: %.5f' % (i, tau))
return
class ELM(BaseEstimator):
def __init__(self, n_nodes, link='rbf', output_function='lasso', n_jobs=1, c=1):
self.n_jobs = n_jobs
self.n_nodes = n_nodes
self.c = c
if link == 'rbf':
self.link = lambda z: np.exp(-z*z)
elif link == 'sig':
self.link = lambda z: 1./(1 + np.exp(-z))
elif link == 'id':
self.link = lambda z: z
else:
self.link = link
if output_function == 'lasso':
self.output_function = LassoLarsCV(cv=10, n_jobs=self.n_jobs)
elif output_function == 'lr':
self.output_function = LinearRegression(n_jobs=self.n_jobs)
elif output_function == 'ridge':
self.output_function = RidgeCV(cv=10)
else:
self.output_function = output_function
return
def H(self, x):
n, p = x.shape
xw = np.dot(x, self.w.T)
xw = xw + np.ones((n, 1)).dot(self.b.T)
return self.link(xw)
def fit(self, x, y, w=None):
n, p = x.shape
self.mean_y = y.mean()
if w == None:
self.w = np.random.uniform(-self.c, self.c, (self.n_nodes, p))
else:
self.w = w
self.b = np.random.uniform(-self.c, self.c, (self.n_nodes, 1))
self.h_train = self.H(x)
self.output_function.fit(self.h_train, y)
return self
def predict(self, x):
self.h_predict = self.H(x)
return self.output_function.predict(self.h_predict)
def get_params(self, deep=True):
return {"n_nodes": self.n_nodes,
"link": self.link,
"output_function": self.output_function,
"n_jobs": self.n_jobs,
"c": self.c}
def set_params(self, **parameters):
for parameter, value in parameters.items():
setattr(self, parameter, value)
return self
def estimateBestAlpha(X,y,modelSavePath):
elm = ELM(n_nodes=30, output_function='lasso')
gs = sk.grid_search.GridSearchCV(elm,cv=5,
param_grid={"c": np.linspace(0.0001, 1, 50)},fit_params={}, scoring='mean_squared_error')
gs.fit(X, y)
print("best_params_")
print(gs.best_params_['c'])
return gs.best_params_['c']
lasso = linear_model.Lasso()
alphas = np.logspace(-4, -.5, 30)#np.linspace(0.00001, 1, 30) # np.logspace(-4, -.5, 30)
scores = list()
scores_std = list()
for alpha in alphas:
lasso.alpha = alpha
this_scores = cross_validation.cross_val_score(lasso, X, y, n_jobs=1)
scores.append(np.mean(this_scores))
scores_std.append(np.std(this_scores))
plt.figure(figsize=(4, 3))
plt.semilogx(alphas, scores)
# plot error lines showing +/- std. errors of the scores
plt.semilogx(alphas, np.array(scores) + np.array(scores_std) / np.sqrt(len(X)),
'b--')
plt.semilogx(alphas, np.array(scores) - np.array(scores_std) / np.sqrt(len(X)),
'b--')
plt.ylabel('CV score')
plt.xlabel('alpha')
plt.axhline(np.max(scores), linestyle='--', color='.5')
plt.show()
index = 0
minIndex = 0
min_score = -1000
for score in scores:
if score>min_score:
min_score = score
minIndex = index
index+=1
alphas = np.logspace(-4, -.5, 30)
print("alphas")
print(alphas)
lasso_cv = linear_model.LassoCV(alphas=alphas)
k_fold = cross_validation.KFold(len(X), 5)
min_score = -1000
for k, (train, test) in enumerate(k_fold):
lasso_cv.fit(X[train], y[train])
score = lasso_cv.score(X[test], y[test])
if score > min_score:
min_score = score
minAlpha= lasso_cv.alpha_
#print("[fold {0}] alpha: {1:.5f}, score: {2:.5f}".format(k, lasso_cv.alpha_,score ))
joblib.dump(lasso_cv, modelSavePath, compress=9)
return minAlpha
def rankingAlgorithm5(X,y,n_samples,modelSavePath):
gs = sk.grid_search.GridSearchCV(ELM(n_nodes=20, output_function='lasso'),
cv=5,
param_grid={"c": np.linspace(0.0001, 1, 10)},
fit_params={},scoring='mean_squared_error')
gs.fit(X, y)
print("best_params_")
print(gs.best_params_)
print(gs.best_params_['c'])
lasso = linear_model.Lasso()
alphas = np.linspace(0.0001, 1, 50)#np.logspace(-4, -.5, 30)
scores = list()
scores_std = list()
print("alphas")
print(alphas)
for alpha in alphas:
lasso.alpha = alpha
this_scores = cross_validation.cross_val_score(lasso, X, y, n_jobs=1)
scores.append(np.mean(this_scores))
scores_std.append(np.std(this_scores))
plt.figure(figsize=(4, 3))
plt.semilogx(alphas, scores)
# plot error lines showing +/- std. errors of the scores
plt.semilogx(alphas, np.array(scores) + np.array(scores_std) / np.sqrt(len(X)),
'b--')
plt.semilogx(alphas, np.array(scores) - np.array(scores_std) / np.sqrt(len(X)),
'b--')
plt.ylabel('CV score')
plt.xlabel('alpha')
plt.axhline(np.max(scores), linestyle='--', color='.5')
plt.show()
lasso_cv = linear_model.LassoCV(alphas=alphas)
k_fold = cross_validation.KFold(len(X), 5)
for k, (train, test) in enumerate(k_fold):
lasso_cv.fit(X[train], y[train])
print("[fold {0}] alpha: {1:.5f}, score: {2:.5f}".
format(k, lasso_cv.alpha_, lasso_cv.score(X[test], y[test])))
trainLen = 4
testLen = 4
tau = 0
return trainLen, testLen, tau
return
def rankingAlgorithm4(X,y,n_samples,modelSavePath):
# Loading the Digits dataset
# Split the dataset in two equal parts
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.5, random_state=0)
# Set the parameters by cross-validation
tuned_parameters = {'alpha': [10 ** a for a in range(-6, -2)]}
scores = ['precision', 'recall']
regressionModel = linear_model.Lasso
for score in scores:
print("# Tuning hyper-parameters for %s" % score)
print()
clf = GridSearchCV(regressionModel, tuned_parameters, cv=5,
scoring='mean_squared_error' % score)
clf.fit(X_train, y_train)
print("Best parameters set found on development set:")
print()
print(clf.best_params_)
print()
print("Grid scores on development set:")
print()
for params, mean_score, scores in clf.grid_scores_:
print("%0.3f (+/-%0.03f) for %r"
% (mean_score, scores.std() * 2, params))
print()
print("Detailed classification report:")
print()
print("The model is trained on the full development set.")
print("The scores are computed on the full evaluation set.")
print()
y_true, y_pred = y_test, clf.predict(X_test)
print(classification_report(y_true, y_pred))
print()
return
def rankingAlgorithm3(X,y,n_samples,modelSavePath):
from sklearn.cross_validation import cross_val_score
ridge = linear_model.Lasso(alpha=0.1)
scores = cross_val_score(ridge,X,y,scoring='mean_squared_error',cv=10)
print("MSE")
print(np.sqrt(-scores).mean())
cv = KFold(n_samples, 5)
AllPredictions = []
AllTest = []
testLen = 0
trainLen = 0
#ridge = linear_model.BayesianRidge(alpha_1=1e-06, alpha_2=1e-06, compute_score=False, copy_X=True,
# fit_intercept=True, lambda_1=1e-06, lambda_2=1e-06, n_iter=300,
# normalize=False, tol=0.001, verbose=False)
#alphas = [0.01,0.02,0.1,0.2,0.0001]#np.logspace(-16, 3, num=50, base=2)
min_Score = 10000000
min_alpha = 0
alphares = estimateBestAlpha(X,y,modelSavePath)
print("alphares")
print(alphares)
#for alpha in alphas:
#regressionModel = linear_model.Lasso(alpha=alphares)
# ridge = linear_model.Ridge(1.)
# ridge = linear_model.Lasso(alpha=0.1)
tau = 0
return trainLen, testLen, tau
#print("alpha")
#print(alpha)
for train, test in cv:
X_train = X[train]
y_train = y[train]
trainLen = len(X_train)
X_test = X[test]
y_test = y[test]
testLen = len(X_test)
# ridge = linear_model.RidgeCV(fit_intercept=True)
regressionModel.fit(X_train, y_train)
# print the performance of ranking
#modelscore = regressionModel.score(X_test, y_test)
#print('Performance of ranking ', modelscore)
predictions = regressionModel.predict(X_test)
for pred in predictions:
AllPredictions.append(pred)
for tes in y_test:
AllTest.append(tes)
#tau, _ = stats.kendalltau(predictions, y_test)
# Saving the model
joblib.dump(regressionModel, modelSavePath, compress=9)
# Reading the model
# ridge_new = joblib.load(modelSavePath)
#taus, _ = stats.spearmanr(AllPredictions, AllTest)
tau, _ = stats.kendalltau(AllPredictions, AllTest)
tau = round(tau,3)
#print('Kendall correlation coefficient for the test list : %.5f ' % (tau))
return trainLen,testLen,tau
'''
def buildFeatureListForCategory(catFilePath,productBaseDirectory):
X = [] # list of samples each with list of features
y = [] # contains the average as the expected value
productList = []
featureProduct = dict()
index = 0
with open(catFilePath, 'r') as fp:
for line in fp:
row = line.split('\t')
productId = row[0]
productId = productId.split('\n')
productId = productId[0]
featureList = []
ratingTemproalCategory, ratingHelpfulnessCategory, n, average = analyzeProduct(productBaseDirectory,productId)
periodDict = {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: [],}
for i in range(len(ratingTemproalCategory)):
for item in ratingTemproalCategory[i]:
try:
record = periodDict[item]
record.append(ratingTemproalCategory[i][item])
periodDict[item] = record
except KeyError as e:
pass
# featureList.append(ratingTemproalCategory[i][item])
five = 0
avStart = 0
sum = 0
for key, value in periodDict.items():
for item in value:
featureList.append(item)
avStart +=(item*(five+1))
sum+=item
five+=1
if sum > 0:
avStart = avStart / sum
#featureList.append(avStart)
avStart = 0
five = 0
sum = 0
n_features = len(featureList)
if n_features != 55:
print("not 55")
print(periodDict)
print(ratingTemproalCategory)
print(n_features)
print(featureList)
productList.append((productId,average))
featureProduct[productId] = featureList
X.append(featureList)
y.append(average)
index +=1
return X,y,productList,featureProduct
def buildFeatureListForCategoryForDirichlet(catFilePath,productBaseDirectory):
X = [] # list of samples each with list of features
y = [] # contains the average as the expected value
productList = []
featureProduct = dict()
index = 0
with open(catFilePath, 'r') as fp:
for line in fp:
row = line.split('\t')
productId = row[0]
productId = productId.split('\n')
productId = productId[0]
featureList = []
ratingTemproalCategory, ratingHelpfulnessCategory, n, average = analyzeProduct(productBaseDirectory,productId)
periodDict = {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: [],}
for i in range(len(ratingTemproalCategory)):
for item in ratingTemproalCategory[i]:
try:
record = periodDict[item]
record.append(ratingTemproalCategory[i][item])
periodDict[item] = record
except KeyError as e:
pass
# featureList.append(ratingTemproalCategory[i][item])
five = 0
avStart = 0
sum = 0
for key, value in periodDict.items():
for item in value:
featureList.append(item)
avStart +=(item*(five+1))
sum+=item
five+=1
if sum > 0:
avStart = avStart / sum
#featureList.append(avStart)
avStart = 0
five = 0
sum = 0
n_features = len(featureList)
if n_features != 55:
print("not 55")
print(periodDict)
print(ratingTemproalCategory)
print(n_features)
print(featureList)
ratings = aggregateRatingsForAllTimePeriods(ratingTemproalCategory)
prior = [2,2,2,2,2]
retValue = dirichlet_mean(ratings, prior)
productList.append((productId,average))
featureProduct[productId] = featureList
X.append(featureList)
y.append(retValue)
index +=1
return X,y,productList,featureProduct
def buildFeatureListForCategoryForGeneral(catFilePath,productBaseDirectory,category,option,featureSet,ProductPolaritiesPerRating ):
X = [] # list of samples each with list of features
y = [] # contains the average as the expected value
productList = []
featureProduct = dict()
index = 0
filePathExpertiese = "C:\Yassien_RMIT PhD\Datasets\TruthDiscovery_Datasets\Web data Amazon reviews/Unique_Products_Stanford_three/UserHelpfulVotesPerCategoryNew/" + category
userExpert = dict()
with open(filePathExpertiese, 'r') as fp:
for line in fp:
row = line.split('\t')
userExpert[row[0]] = float(row[3])
productpriceFile = "C:\Yassien_RMIT PhD\Datasets\TruthDiscovery_Datasets\Web data Amazon reviews/Unique_Products_Stanford_three/Experiment 2/product_prices.txt"
prices = dict()
with open(productpriceFile, 'r') as fp:
for line in fp:
row = line.split('\t')
prices[row[0]] = float(row[1])
'''productPolartiesFile = "C:\Yassien_RMIT PhD\Datasets\TruthDiscovery_Datasets\Web data Amazon reviews/Unique_Products_Stanford_three/Experiment 2/product_polarties.txt"
postivePolarity = dict()
negativePolarity = dict()
with open(productPolartiesFile, 'r') as fp:
for line in fp:
row = line.split("\t")
if len(row)>3:
postivePolarity[row[0]] = float(row[2])
negativePolarity[row[0]] = float(row[3])
else:
print("problem with this line len "+str(len(row))+" "+str(row))
'''
with open(catFilePath, 'r') as fp:
for line in fp:
row = line.split('\t')
productId = row[0]
productId = productId.split('\n')
productId = productId[0]
featureList = []
ratingTemproalCategory, ratingHelpfulnessCategory, n, average,numReviews,numFeedBackPerDayDictionary,numHelpFeedPerDayDictionary = analyzeProduct(productBaseDirectory,productId)
periodDict = {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: [],}
for i in range(len(ratingTemproalCategory)):
for item in ratingTemproalCategory[i]:
try:
record = periodDict[item]
record.append(ratingTemproalCategory[i][item])
periodDict[item] = record
except KeyError as e:
pass
# featureList.append(ratingTemproalCategory[i][item])
five = 0
avStart = 0
sum = 0
if featureSet == 1: #We'll add only the basic feature set
retValue = average
ratings = aggregateRatingsForAllTimePeriods(ratingTemproalCategory)
for key, value in ratings.items():
featureList.append(value) # Feature Number of reviews with specific star rating
# Adding Polarity
AllPolarities = []
try:
AllPolarities = ProductPolaritiesPerRating[productId]
except KeyError:
print("failed to find Positive polarity to product " + productId)
pass
if len(AllPolarities) == 20:
# +ve Polarity for 5 ratings
featureList.append(int(AllPolarities[1]))
featureList.append(int(AllPolarities[5]))
featureList.append(int(AllPolarities[9]))
featureList.append(int(AllPolarities[13]))
featureList.append(int(AllPolarities[17]))
# -ve Polarity for 5 ratings
featureList.append(int(AllPolarities[2]))
featureList.append(int(AllPolarities[6]))
featureList.append(int(AllPolarities[10]))
featureList.append(int(AllPolarities[14]))
featureList.append(int(AllPolarities[18]))
'''
polarity = 0
try:
polarity = postivePolarity[productId]
except KeyError as e:
print("failed to find Positive polarity to product " + productId)
pass
featureList.append(polarity) # Feature Product Positive Polarity
polarity = 0
try:
polarity = negativePolarity[productId]
except KeyError as e:
print("failed to find Negative polarity to product " + productId)
pass
featureList.append(polarity) # Feature Product Negative Polarity
'''
numFeedBacks = []
for key, value in numFeedBackPerDayDictionary.items():
listofDays = value
numFeedBackPerRating = 0
for item in listofDays:
numFeedBackPerRating+=item[0]
numFeedBacks.append(numFeedBackPerRating)
numHelpFeedBacks = []
for key, value in numHelpFeedPerDayDictionary.items():
listofDays = value
numFeedBackPerRating = 0
for item in listofDays:
numFeedBackPerRating += item[0]
numHelpFeedBacks.append(numFeedBackPerRating)
numNonHelpFeedBacks = []
for i in range(len(numFeedBacks)):
numNonHelpFeedBacks.append(numFeedBacks[i]-numHelpFeedBacks[i])
#print(numFeedBacks)
#print(numNonHelpFeedBacks)
#print(numHelpFeedBacks)
for item in numHelpFeedBacks: #Adding Helpful votes per star ratings
featureList.append(item)
for item in numNonHelpFeedBacks: # Adding Non Helpful votes per star ratings
featureList.append(item)
if len(featureList) < 17:
print("Problem with features ")
print(numFeedBackPerDayDictionary)
print((numHelpFeedPerDayDictionary))
featureProduct[productId] = featureList
productList.append((productId, retValue))
X.append(featureList)
y.append(retValue)
else:
for key, value in periodDict.items():
for item in value:
featureList.append(item)
avStart +=(item*(five+1))
sum+=item
five+=1
if sum > 0:
avStart = avStart / sum
#featureList.append(avStart)
avStart = 0
five = 0
sum = 0
n_features = len(featureList)
if n_features != 55:#features 55 from 5 star rating levels in 11 periods
print("not 55")
print(periodDict)
print(ratingTemproalCategory)
print(n_features)
print(featureList)
expoValue = 0
if option == 1:
prior = [2,2,2,2,2]
ratings = aggregateRatingsForAllTimePeriods(ratingTemproalCategory)
retValue = dirichlet_mean(ratings, prior)
elif option == 2:
productFileName = productBaseDirectory+productId+".txt"
expoValue = computeExponentialScore(productFileName, userExpert)
#print(featureList)
# will add dricilet and the exponential score as additional features
#--------------------------------------------------------------------------------------------------------------------
prior = [2, 2, 2, 2, 2]
retValue = 0
#ratings = aggregateRatingsForAllTimePeriods(ratingTemproalCategory)
#retValue = dirichlet_mean(ratings, prior)
featureList.append(numReviews)#Feature 56 Number of reviews
featureList.append(expoValue)#Feature 57 exp model
# --------------------------------------------------------------------------------------------------------------------
productPrice = 0
try:
productPrice = prices[productId]
if productPrice == -1:
productPrice = 0
except KeyError as e:
print("failed to find price to product "+productId)
pass
featureList.append(productPrice)# Feature 58 Product Price
#---------------------------------------------------------------------------------------------------------------------
#Adding Polarity
polarity = 0
try:
polarity = postivePolarity[productId]
except KeyError as e:
print("failed to find Positive polarity to product " + productId)
pass
featureList.append(polarity) # Feature 59 Product Positive Polarity
polarity = 0
try:
polarity = negativePolarity[productId]
except KeyError as e:
print("failed to find Negative polarity to product " + productId)
pass
featureList.append(polarity) # Feature 60 Product Negative Polarity
# ---------------------------------------------------------------------------------------------------------------------
productList.append((productId,retValue))
featureProduct[productId] = featureList
X.append(featureList)
y.append(retValue)
index +=1
return X,y,productList,featureProduct
from Testing import divideReviewsByRatingLevelByTimePeriods
def buildFeatureListForCategoryForTimePeriods(catFilePath,productBaseDirectory,ProductPolaritiesPerRatingPerPeriod,dataset_type,timeperiods ):
X = [] # list of samples each with list of features
y = [] # contains the average as the expected value
productList = []
featureProduct = dict()
index = 0
with open(catFilePath, 'r') as fp:
for line in fp:
row = line.split('\t')
productId = row[0]
productId = productId.split('\n')
productId = productId[0]
featureList = []
productFilePath=productBaseDirectory+productId+".txt"
polarties = []
try:
polarties = ProductPolaritiesPerRatingPerPeriod[productId]
except KeyError:
print("didn't find polarites for "+str(productId))
reviewRatingLevelTimeDict = divideReviewsByRatingLevelByTimePeriods(productFilePath, timeperiods,dataset_type)
ratingLevelPerTimePeriod = dict()
helpfulPerRatingPerTimePeriod = dict()
nonHelpfulPerRatingPerTimePeriod = dict()
for key, value in reviewRatingLevelTimeDict.items():
ratingsDictionary = value
ratingLevels = []
helpful=[]
nonhelpful = []
for key2, value2 in ratingsDictionary.items():
if len(value2) !=0:
reviews = value2
ratingLevels.append(len(reviews))
numHelpful = 0
numNonHelpful = 0
for review in reviews:
if dataset_type=="amazon":
if review[3]!="" and review[4]!="":
numFeedback = int(review[3])
numHelpful+= int(review[4])
nonhelpf=numFeedback-int(review[4])
numNonHelpful+=nonhelpf
else:
numFeedback = 0
numHelpful += 0
nonhelpf = numFeedback
numNonHelpful += nonhelpf
elif dataset_type=="yelp":
votes = str(review[2]).split(',')
funny=int(votes[0].split(':')[1])
useful=int(votes[1].split(':')[1])
cool=int(votes[2].split(':')[1].split('}')[0])
numHelpful=useful+cool
numNonHelpful=funny
helpful.append(numHelpful)
nonhelpful.append(numNonHelpful)
else:
ratingLevels.append(0)
helpful.append(0)
nonhelpful.append(0)
ratingLevelPerTimePeriod[key]=ratingLevels
helpfulPerRatingPerTimePeriod[key] = helpful
nonHelpfulPerRatingPerTimePeriod[key] = nonhelpful
#Adding Num reviews per rating level per time period
#print("Num reviews per rating")
for key, value in ratingLevelPerTimePeriod.items():
ratingLevels = value
#print(ratingLevels)
for numRatingsPerLevel in ratingLevels:
featureList.append(numRatingsPerLevel)
#print(" Num helpful votes per rating")
# Adding Num helpful votes per rating level per time period
for key, value in helpfulPerRatingPerTimePeriod.items():
ratingLevels = value
#print(ratingLevels)
for numRatingsPerLevel in ratingLevels:
featureList.append(numRatingsPerLevel)
# Adding Num non helpful votes per rating level per time period
#print(" Num non helpful votes per rating")
for key, value in nonHelpfulPerRatingPerTimePeriod.items():
ratingLevels = value
# print(ratingLevels)
for numRatingsPerLevel in ratingLevels:
featureList.append(numRatingsPerLevel)
# Adding +ve and -ve polarities per rating level per time period
if len(polarties) != (timeperiods*5*2):
print("Missing polarities " + str(len(polarties)))
for polarity in polarties:
featureList.append(polarity)
if len(featureList) !=(timeperiods*25):
print("missing features "+str(len(featureList)))
retValue = 0
productList.append((productId, retValue))
featureProduct[productId] = featureList
X.append(featureList)
y.append(retValue)
index+=1
print(index)
return X,y,productList,featureProduct
def buildFeatureListForCategoryRetDict(catFilePath,productBaseDirectory):
X = [] # list of samples each with list of features
y = [] # Product IDs
index = 0
with open(catFilePath, 'r') as fp:
for line in fp:
row = line.split('\t')
productId = row[0]
productId = productId.split('\n')
productId = productId[0]
featureList = []
ratingTemproalCategory, ratingHelpfulnessCategory, n, average = analyzeProduct(productBaseDirectory,productId)
periodDict = {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: [],}
for i in range(len(ratingTemproalCategory)):
for item in ratingTemproalCategory[i]:
try:
record = periodDict[item]
record.append(ratingTemproalCategory[i][item])
periodDict[item] = record
except KeyError as e:
pass
# featureList.append(ratingTemproalCategory[i][item])
five = 0
avStart = 0
sum = 0
for key, value in periodDict.items():
for item in value:
featureList.append(item)
avStart +=(item*(five+1))
sum+=item
five+=1
if sum > 0:
avStart = avStart / sum
#featureList.append(avStart)
avStart = 0
five = 0
sum = 0
n_features = len(featureList)
if n_features != 55:
print("not 55")
print(periodDict)
print(ratingTemproalCategory)
print(n_features)
print(featureList)
X.append(featureList)
y.append(productId)
index +=1
return X,y
import math
''' for sorting sales rank
sales_dict = []
sales_rank = "C:\Yassien_RMIT PhD\Datasets\TruthDiscovery_Datasets\Web data Amazon reviews/Unique_Products_Stanford_three/Experiment 2/Sorted_Categories/categories_sorted_sales_rank/"+filename
with open(sales_rank, 'r') as fp:
for line in fp:
row = line.split("\t")
product = row[0]
row = row[1].split("\n")
salesrank = int(row[0])
sales_dict.append((product,salesrank))
onlyNeededList = []
for item in (productList):
for sale in sales_dict:
if item[0]==sale[0]:
onlyNeededList.append(sale)
break
quickSort(onlyNeededList)
print(onlyNeededList)
onlyNeededDict = dict()
for item in (sales_dict):
onlyNeededDict[item[0]]=item[1]