-
Notifications
You must be signed in to change notification settings - Fork 0
/
try1.py
2347 lines (1782 loc) · 83 KB
/
try1.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
# -*- coding: utf-8 -*-
"""Naval Fate.
Usage:
naval_fate.py [--cf_on=False]
naval_fate.py [--compare_variants=False]
naval_fate.py observe_word2vec_hyperpara (min_count | window)
naval_fate.py time_overhead
naval_fate.py time_overhead_CF
naval_fate.py observe_CF_when_K_varies
naval_fate.py observe_word2vec_when_K_varies
naval_fate.py full_comparison
naval_fate.py exp_time_coef
naval_fate.py exp_mc
naval_fate.py exp_window
naval_fate.py exp_size
naval_fate.py exp_learning_rate
naval_fate.py exp_iter
naval_fate.py exp_K
naval_fate.py exp_K__simple_CF
naval_fate.py exp_time_overhead
naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
naval_fate.py ship shoot <x> <y>
naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
naval_fate.py (-h | --help)
naval_fate.py --version
Options:
-h --help Show this screen.
"""
from docopt import docopt
import time
import os
import gensim#from gensim.models import word2vec
import math
import random
import csv
import numpy as np
from numpy import linalg as la
import heapq
import multiprocessing
#from multiprocessing.dummy import Pool as ThreadPool
import datetime
import logging
#import threading
#import thread
import cPickle
import sqlite3
from utility_extract_data import extract_data_from_file_and_generate_train_and_test
from utility_user_repr import *
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
def get_least_numbers_big_data(self, alist, k):
max_heap = []
length = len(alist)
if not alist or k <= 0 or k > length:
return
k = k - 1
for ele in alist:
ele = -ele
if len(max_heap) <= k:
heapq.heappush(max_heap, ele)
else:
heapq.heappushpop(max_heap, ele)
return map(lambda x:-x, max_heap)
class RecommendatorSystem(object):
"""docstring for RecommendatorSystem"""
def __init__(self):
super(RecommendatorSystem, self).__init__()
def setup(self):
assert(False)
def split_data(self, data, M, k, seed):
'''Possible problem:
'''
test = []
train = []
random.seed(seed)
for user, item in data.items():
if k == random.randint(0, M):
test.append([user, item])
else:
train.append([user, item])
return train, test
def calculate_metrics(self, train, test, N):
starttime = datetime.datetime.now()
###
threads = []
# Start consumers
num_threads = multiprocessing.cpu_count() * 2
#num_threads = 1 # for debugging
if len(test) < num_threads:
num_threads = 1
print 'Creating %d threads' % num_threads
piece_len = len(test) / num_threads
test__in_list = test.items()
#print 'dict(test__in_list):', dict(test__in_list)
pieces = [dict(test__in_list[x * piece_len: (x + 1) * piece_len]) for x in xrange(0, num_threads + 1)]
#print 'pieces:', pieces
# 创建线程对象
name_prefix = 'thread-'
name_postfix = '.dump'
for en, x in enumerate(pieces):
name = name_prefix + str(en) + name_postfix
threads.append(InnerThreadClass(name, self, len(test), x, N))
for t in threads:
t.start()
for t in threads:
t.join()
total = len(test)
print 'progress: %d/%d. done.' % (total, total)
#
rec_pieces = [cPickle.load(open(name, 'r')) for name in [name_prefix + str(en) + name_postfix for en in xrange(num_threads + 1)]]
#print 'rec_pieces:', rec_pieces
rec = {}
map(lambda x: rec.update(x), rec_pieces)
#print 'rec:', rec
###
hit = 0
all__for_recall = 0
all__for_precision = 0
for user in test.keys():
history = test[user][0]
answer = test[user][1]
tu = [x[0] for x in answer]
rank = rec[user] # self.recommend(history, N)
#print 'rank:', rank
for item, pui in rank:
if item in tu:
hit += 1
all__for_recall += len(tu)
all__for_precision += len(rank) #Note: In book RSP, the author used 'all += N'
metric_recall = None
metric_precision = None
metric_f1 = None
if 0 == all__for_recall:
metric_recall = 0
else:
metric_recall = hit / (all__for_recall * 1.0)
if 0 == all__for_precision:
metric_precision = 0
else:
metric_precision = hit / (all__for_precision * 1.0)
if 0 == all__for_recall or 0 == all__for_precision:
metric_f1 = 0
else:
metric_f1 = 2/(1./metric_precision + 1./metric_recall)
endtime = datetime.datetime.now()
interval = (endtime - starttime).seconds
print 'metric calculation: time consumption: %d' % (interval)
return {'recall': metric_recall, 'precision': metric_precision, 'f1': metric_f1}
class InnerThreadClass(multiprocessing.Process):
def __init__(self, name, recommendator, total, partial_test_set, N):
multiprocessing.Process.__init__(self)
self.name = name
self.recommendator = recommendator
self.total = total
self.partial_test_set = partial_test_set
self.N = N
def run(self):
rec = {}
#print 'self.partial_test_set:', self.partial_test_set
for step, user_id in enumerate(self.partial_test_set):
piece_of_test_data = self.partial_test_set[user_id]
history = piece_of_test_data[0]
#print 'history:', history
recommendation = self.recommendator.recommend(history, self.N)
#print 'recommendation: %s' % (str(recommendation))
rec[user_id] = recommendation
if (0 == step % 64):
print 'progress: %d/%d' % (step, self.total)
#print '[%s]: rec: %s' % (self.name, str(rec))
cPickle.dump(rec, open(self.name, 'w'))
print 'done'
class RecommendatorSystemViaCollaborativeFiltering(RecommendatorSystem):
"""docstring for RecommendatorSystemViaCollaborativeFiltering"""
def __init__(self):
super(RecommendatorSystemViaCollaborativeFiltering, self).__init__()
self.W = None # weight matrix / user similarity matrix
def setup(self, para):
self.train = para['train']
# K
self.K = para['K']
#self.user_similarity(self.train)
def user_similarity(self, train):
#build inverse table item_users
print 'This is RecommendatorSystemViaCollaborativeFiltering'
starttime = datetime.datetime.now()
###
#
#user set
user_id_set = train.keys()
#user history dict
#user_history = {x: data[x].keys() for x in data}
#print 'user_history:', user_history
user_history = train
#
#calculate final similarity matrix W
threads = []
# Start consumers
num_threads = multiprocessing.cpu_count() * 2
print 'Creating %d threads' % num_threads
piece_len = len(user_id_set) / num_threads
pieces = []
user_id_list = list(user_id_set)
pieces = [user_id_list[x * piece_len: (x + 1) * piece_len] for x in xrange(0, num_threads + 1)]
# 创建线程对象
name_prefix = 'thread-'
name_postfix = '.dump'
for en, x in enumerate(pieces):
name = name_prefix + str(en) + name_postfix
threads.append(InnerThreadClass(name, train, x, self.K))
for t in threads:
t.start()
for t in threads:
t.join()
total = len(user_id_list)
print 'progress: %d/%d. done.' % (total, total)
#
W_pieces = [cPickle.load(open(name, 'r')) for name in [name_prefix + str(en) + name_postfix for en, x in enumerate(pieces)]]
W = {}
map(lambda x: W.update(x), W_pieces)
self.W = W
#
endtime = datetime.datetime.now()
interval=(endtime - starttime).seconds
print 'user_similarity: time consumption: %d' % (interval)
def find_K_neighbors(self, target_user_history):
### find K neighbors <begin>
simi_list_of_user_u = []
interacted_items = [x[0] for x in target_user_history]
for v in self.train.keys():
#if u == v:
# assert(False)
# continue
user_v_history = set([x[0] for x in self.train[v]])
#print 'user_v_history:', user_v_history
#user_u_repr = np.array(map(lambda x: 1 if x in train[u] else 0, self.distinct_item_list))
#user_v_repr = np.array(map(lambda x: 1 if x in train[v] else 0, self.distinct_item_list))
#common_items = user_u_history.intersection(user_v_history)
common_items = set(interacted_items).union(user_v_history)
if 0 == len(common_items):
simi = 0
else:
#print_matrix(train[u])
user_u_repr = np.array(map(lambda x: 1 if x in interacted_items else 0, common_items))
user_v_repr = np.array(map(lambda x: 1 if x in user_v_history else 0, common_items))
#print 'user_u_repr:', user_u_repr
#print 'user_v_repr:', user_v_repr
simi = user_u_repr.dot(user_v_repr) / (la.norm(user_u_repr * la.norm(user_v_repr)))
#raw_input()
#
simi_list_of_user_u.append((v, simi))
#
K_neighbors = heapq.nlargest(self.K * 2, simi_list_of_user_u, key=lambda s: s[1])
### find K neighbors <end>
return K_neighbors
def recommend(self, target_user_history, N):
'''@K: number of user neighbors considered
'''
rank = {}
interacted_items = [x[0] for x in target_user_history]
#print 'target_user_history:', target_user_history
#print 'interacted_items:', interacted_items
K_neighbors = self.find_K_neighbors(target_user_history)
for v, wuv in K_neighbors:
#for v, wuv in sorted(self.W[u].items(), key=lambda x: x[1], reverse=True)[0:K]: # wuv: similarity between user u and user v
for i, rvi, timestamp in self.train[v]: # rvi: rate of item by user v
if i in interacted_items:
#do not recommend items which user u interacted before
continue
if i not in rank:
rank[i] = 0.0
rank[i] += wuv * rvi
rank = rank.items()
rank.sort(key=lambda x: x[1], reverse=True)
return rank[:N]
### Word2vec
class RecommendatorViaWord2Vec(RecommendatorSystemViaCollaborativeFiltering):
"""docstring for RecommendatorViaWord2Vec"""
def __init__(self):
super(RecommendatorViaWord2Vec, self).__init__()
#self.model = None
self.W = None
self.model_name = None
def setup(self, para):
data = para['data']
self.train = para['data']
self.model_name = para['model_name']
sg = para['sg']
min_count = para['min_count']
window = para['window']
num_features = para['num_features']
learning_rate = para['learning_rate']
para_iter = para['para_iter']
batch_words = para['batch_words']
load_existed = para['load_existed']
self.user_repr_func = get_user_repr_func(para['variant'])
self.K = para['K']
if load_existed:
print 'start loading'
self.model = gensim.models.Word2Vec.load(self.model_name)
print 'loading finished'
else: # train a new one
#list_of_list = convert_2_level_dict_to_list_of_list(data)
list_of_list = convert_level_1_dict_level_2_list_of_size_3_tuples_to_list_of_list(data)
#print 'list_of_list:', list_of_list
print 'start training'
self.model = gensim.models.Word2Vec(list_of_list, sg=sg, min_count=min_count, window=window, size=num_features, alpha=learning_rate, iter=para_iter, batch_words=batch_words)
print 'training finished'
# If you don't plan to train the model any further, calling
# init_sims will make the model much more memory-efficient.
self.model.init_sims(replace=True)
# It can be helpful to create a meaningful model name and
# save the model for later use. You can load it later using Word2Vec.load()
self.model.save(self.model_name)
#
#user set
#user_id_set = data.keys()
#user history dict
#user_history = {x: data[x].keys() for x in data}
#print 'user_history:', user_history
#user repre dict
#user_repre = {uesr_id: np.average(map(lambda item: self.model[item], user_history[uesr_id]), axis=0) for uesr_id in user_history}
self.user_repre = {uesr_id: self.user_repr_func(self.model, data[uesr_id]) for uesr_id in data}
#print 'user_repre:', user_repre
def find_K_neighbors(self, target_user_history):
### find K neighbors <begin>
#print 'find_K_neighbors (word2vec)'
simi_list_of_user_u = []
#print 'interacted_items:', interacted_items
user_repre_of_u = self.user_repr_func(self.model, target_user_history)
if user_repre_of_u is None:
return []
for v in self.train.keys():
#if u == v:
# assert(False)
# continue
user_v_history = self.user_repre[v]
try:
simi = user_repre_of_u.dot(self.user_repre[v]) / (la.norm(user_repre_of_u * la.norm(self.user_repre[v])))
except TypeError:
continue
#
simi_list_of_user_u.append((v, simi))
#
K_neighbors = heapq.nlargest(self.K * 2, simi_list_of_user_u, key=lambda s: s[1])
### find K neighbors <end>
return K_neighbors
### Word2vec based CB
class RecommendatorViaWord2VecBasedCB(RecommendatorSystem):
def __init__(self):
super(RecommendatorSystem, self).__init__()
def setup(self, para):
item_file_name, item_file_delimiter, genre_delimiter = para['item_file_name'], para['item_file_delimiter'], para['genre_delimiter']
rating_file_name, rating_file_delimiter = para['rating_file_name'], para['rating_file_delimiter']
model_path = para['model_path']
self.user_repr_func = get_user_repr_func(para['variant'])
self.item_info = self.extract_item_info(item_file_name, item_file_delimiter, genre_delimiter)
self.user_item_interaction = extract_user_item_interaction(rating_file_name, rating_file_delimiter)
self.model = gensim.models.Word2Vec.load(model_path)
self.user_repr = {user: self.user_repr_func(self.model, self.user_item_interaction[user])
for user in self.user_item_interaction}
self.item_repr = self.model
self.all_items = set(self.model.wv.vocab.keys())
self.total_user_item_comb = 0
def extract_item_info(self, filename, delimiter, genre_delimiter):
data = {}
with open(filename , 'r') as f:
for i, line in enumerate(f):
itemId, title, genre_list = map(lambda x: x.strip(), line.split(delimiter))
data[itemId] = (title, genre_list.split(genre_delimiter))
return data
def extract_user_item_interaction(self, filename, delimiter):
data = {}
with open(filename , 'r') as f:
for i, line in enumerate(f):
userId, movieId, rating, timestamp = line.split(delimiter)
#userId = int(userId)
#movieId = int(movieId)
rating = float(rating)
timestamp = int(timestamp)
if userId not in data:
data[userId] = []
data[userId].append((movieId, rating, timestamp))
# order by time
for userId in data:
data[userId].sort(key=lambda x: x[2])
return data
'''
def main():
item_file_name, item_file_delimiter, genre_delimiter = os.path.sep.join(['ml-1m', 'movies.dat']), '::', '|'
item_info = extract_item_info(item_file_name, item_file_delimiter, genre_delimiter)
rating_file_name, rating_file_delimiter = os.path.sep.join(['ml-1m', 'ratings.dat']), '::'
user_item_interaction = extract_user_item_interaction(rating_file_name, rating_file_delimiter)
model_path = '/home/wsyj/dissertation__recommendation_system__experiment_2/dissertation__recommendation_system__experiment/main_modelnum_features=100_min_count=1_window=1_iter=30.model'
#model = gensim.models.Word2Vec.load('/home/wsyj/dissertation__recommendation_system__experiment_2/dissertation__recommendation_system__experiment/main_modelnum_features=200_min_count=5_window=2.model' )
model = gensim.models.Word2Vec.load(model_path)
#user_history2user_repr__simple_average(model, user_item_interaction['5989'])
# calculate user representation dict
user_repr = {user: user_history2user_repr__simple_average(model, user_item_interaction[user])
for user in user_item_interaction}
# item representation
item_repr = model
#print len(item_repr)
all_items = set(model.wv.vocab.keys())
# load train and test datasets
data_filename, delimiter, data_set = os.path.sep.join(['ml-1m', 'ratings.dat']), '::', '1M'
#data_filename, delimiter = os.path.sep.join(['ml-10M100K', 'ratings.dat']), '::'
#data_filename, delimiter, data_set = os.path.sep.join(['ml-100k', 'u.data']), '\t', '100K'
N = 20
seed = 2
K = 10
train_percent = 0.8
test_data_inner_ratio = 0.8
test = None
train, original_test = extract_data_from_file_and_generate_train_and_test(data_filename, train_percent, seed, delimiter, test_data_inner_ratio)
#train, test = extract_data_from_file_and_generate_train_and_test(data_filename, 3, 0, seed, delimiter)
# main: core of content-based recommendation
total_user_item_comb = 0
rec = {}
for user in original_test:
history, future = original_test[user]
history_items = set([x[0] for x in history])
candidates = all_items - history_items # filtering out those interacted
#print 'candidates:', candidates
total_user_item_comb += len(candidates)
cand_simi_list = []
for candy in candidates:
simi = user_repr[user].dot(item_repr[candy]) / (la.norm(user_repr[user]) * la.norm(item_repr[candy]))
cand_simi_list.append((candy, simi))
cand_simi_list.sort(key=lambda x: -1 * x[1])
rec[user] = cand_simi_list[:N]
print 'total_user_item_comb:', total_user_item_comb
metrics = calculate_metrics(original_test, rec)
print "metrics:", metrics
'''
def recommend(self, target_user_history, N, K=10):
'''@K: number of user neighbors considered
'''
#print 'word2vec based CB'
history_items = set([x[0] for x in target_user_history])
target_user_repr = self.user_repr_func(self.model, target_user_history)
candidates = self.all_items - history_items # filtering out those interacted
#print 'candidates:', candidates
self.total_user_item_comb += len(candidates)
cand_simi_list = []
for candy in candidates:
simi = target_user_repr.dot(self.item_repr[candy]) / (la.norm(target_user_repr) * la.norm(self.item_repr[candy]))
cand_simi_list.append((candy, simi))
cand_simi_list.sort(key=lambda x: -1 * x[1])
return cand_simi_list[:N]
#####################
'''
rank = {}
interacted_items = [x[0] for x in target_user_history]
#print 'target_user_history:', target_user_history
#print 'interacted_items:', interacted_items
K_neighbors = self.find_K_neighbors(target_user_history, K)
for v, wuv in K_neighbors:
#for v, wuv in sorted(self.W[u].items(), key=lambda x: x[1], reverse=True)[0:K]: # wuv: similarity between user u and user v
for i, rvi, timestamp in self.train[v]: # rvi: rate of item by user v
if i in interacted_items:
#do not recommend items which user u interacted before
continue
if i not in rank:
rank[i] = 0.0
rank[i] += wuv * rvi
rank = rank.items()
rank.sort(key=lambda x: x[1], reverse=True)
return rank[:N]'''
def print_matrix(M):
def print_wrapper(x):
print x, M[x]
map(lambda x: print_wrapper(x), M)
#def extract_data():
# filename = 'ml-latest-small\\ratings.csv'
# data = {}
#
# with open(filename , 'r') as f:
# first_line = f.readline()
# for i, line in enumerate(f):
# userId, movieId, rating, timestamp = line.split(',')
# userId = int(userId)
# movieId = int(movieId)
# rating = float(rating)
#
# if userId not in data:
# data[userId] = {}
# data[userId][movieId] = rating
#
# if 10 == i:
# break
#
# #print data
# return data
#
#
# #csvfile = file(filename, 'r')
# #reader = csv.reader(csvfile)
# #
# #for line in reader:
# # print line
# #
# #csvfile.close()
def try_different_train_test_ratio(ttratio, test_data_inner_ratio): # ttratio: train test ratio
cx = sqlite3.connect('my_metrics.db')
cur = cx.cursor()
data_filename, delimiter, data_set = os.path.sep.join(['ml-100k', 'u.data']), '\t', '100K'
seed = 2
K = 10
N = 20
train, test = extract_data_from_file_and_generate_train_and_test(data_filename, ttratio, seed, delimiter, test_data_inner_ratio)
#train, test = extract_data_from_file_and_generate_train_and_test(data_filename, 3, 0, seed, delimiter)
para_iter = 35
batch_words = 10000
table_name_prefix = 'ttratio_tiratio__metrics_N_%d__iter_%d__batch_words_%d__da_%s'
table_name = table_name_prefix % (N, para_iter, batch_words, data_set)
cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='%s';" % table_name)
ret = cur.fetchall()
if 0 == len(ret):
sql = '''create table %s (
_row_ID integer primary key autoincrement,
ttratio decimal(10, 9),
test_data_inner_ratio decimal(10, 9),
size integer,
min_count integer,
window integer,
precision decimal(30, 28),
recall decimal(30, 28),
f1 decimal(30, 28),
CreatedTime TimeStamp NOT NULL DEFAULT (datetime('now','localtime'))
);''' % (table_name)
cur.execute(sql)
cx.commit()
para_combs = [[440, 1, 2]]
print para_combs[0]
for i, (s, mc, w) in enumerate(para_combs):
rs = RecommendatorViaWord2Vec()
rs.setup({'data': train,
'model_name': 'main_model',
'num_features': s,
'min_count': mc,
'window': w,
'K': K,
'iter': para_iter,
'batch_words': batch_words,
})
print
metrics = rs.calculate_metrics(train, test, N)
print metrics
precision, recall, f1 = metrics['precision'], metrics['recall'], metrics['f1']
cur.execute('insert into %s (ttratio, test_data_inner_ratio, size, min_count, window, precision, recall, f1)' % (table_name) +
'values (%.19f, %.19f, %d, %d, %d, %.19f, %.19f, %.19f)' % (ttratio, test_data_inner_ratio, s, mc, w, precision, recall, f1))
cx.commit()
## CF <START> #########################################################
rs = RecommendatorSystemViaCollaborativeFiltering()
#rs = RecommendatorSystemViaCollaborativeFiltering_UsingRedis()
rs.setup({
'train': train,
'K': K,
})
metrics = rs.calculate_metrics(train, test, N)
print 'metrics:', metrics
precision, recall, f1 = metrics['precision'], metrics['recall'], metrics['f1']
cur.execute('insert into %s (ttratio, test_data_inner_ratio, size, min_count, window, precision, recall, f1)' % (table_name) +
'values ( %.19f, %.19f, %d, %d, %d, %.19f, %.19f, %.19f)' % (ttratio, test_data_inner_ratio, -1, -1, -1, precision, recall, f1))
cx.commit()
## CF <END> #########################################################
#exit(0)
###
cur.close()
cx.close()
def wrapper__try_different_ttratio_and_tiratio():
#train_test_ratio_list = [2. / 3]
#train_test_ratio_list = [0.1, 0.2, 0.3, 0.4, 0.5]
#train_test_ratio_list = [0.05, 0.06, 0.07, 0.08, 0.09]
#train_test_ratio_list = [0.01, 0.02, 0.03, 0.04, 0.05]
#for train_test_ratio in train_test_ratio_list:
# try_different_train_test_ratio(train_test_ratio)
#for train_test_ratio, test_data_inner_ratio in [(0.5, 0.80), (0.5, 0.85), (0.5, 0.9), (0.5, 0.95)]:
#for train_test_ratio, test_data_inner_ratio in [(0.5, 0.05), (0.5, 0.06), (0.5, 0.07), (0.5, 0.08)]: # good
for train_test_ratio, test_data_inner_ratio in [(0.5, 0.5)]:
#for train_test_ratio, test_data_inner_ratio in [(0.02, 0.05), (0.03, 0.05), (0.04, 0.05), (0.05, 0.05)]:
try_different_train_test_ratio(train_test_ratio, test_data_inner_ratio)
def main_Linux():
global arguments
#data_filename, delimiter = os.path.sep.join(['ml-latest-small', 'ratings.csv']), ','
data_filename, delimiter, data_set = os.path.sep.join(['ml-1m', 'ratings.dat']), '::', '1M'
#data_filename, delimiter = os.path.sep.join(['ml-10M100K', 'ratings.dat']), '::'
#data_filename, delimiter, data_set = os.path.sep.join(['ml-100k', 'u.data']), '\t', '100K'
seed = 2
K = 10
train_percent = 0.8
test_data_inner_ratio = 0.8
train, test = extract_data_from_file_and_generate_train_and_test(data_filename, train_percent, seed, delimiter, test_data_inner_ratio)
#train, test = extract_data_from_file_and_generate_train_and_test(data_filename, 3, 0, seed, delimiter)
## CF <START>
print arguments['--cf_on']
if 'True' == arguments['--cf_on']:
rs = RecommendatorSystemViaCollaborativeFiltering()
#rs = RecommendatorSystemViaCollaborativeFiltering_UsingRedis()
rs.setup({
'train': train,
'K': K,
})
for N in xrange(20, 21):
#for N in xrange(10, 11):
#for N in xrange(3, 50):
print 'N:', N
metrics = rs.calculate_metrics(train, test, N)
print 'metrics:', metrics
## CF <END>
##exit(0)
###
N = 20
para_iter = 30
batch_words = 10000
table_name_prefix = 'metrics__normalized_user_repr__N_%d__iter_%d__batch_words_%d__da_%s'
cx = sqlite3.connect('my_metrics.db')
cur = cx.cursor()
table_name = table_name_prefix % (N, para_iter, batch_words, data_set)
print 'table_name:', table_name
cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='%s';" % table_name)
ret = cur.fetchall()
if 0 == len(ret):
sql = '''create table %s (
_row_ID integer primary key autoincrement,
size integer,
min_count integer,
window integer,
precision decimal(30, 28),
recall decimal(30, 28),
f1 decimal(30, 28),
CreatedTime TimeStamp NOT NULL DEFAULT (datetime('now','localtime'))
);''' % (table_name)
cur.execute(sql)
cx.commit()
para_size = range(100, 501, 10)
para_min_count = range(1, 6, 1)
para_window = range(1, 6, 1)
#para_combs = zip(para_size, para_min_count, para_window)
#para_combs = [[[(s, mc, w) for w in para_window] for mc in para_min_count] for s in para_size]
para_combs = [(s, mc, w) for w in para_window for mc in para_min_count for s in para_size]
#para_combs = [[220, 1, 3]]
print para_combs[0]
load_existed = False # Careful ! ! !
ur_name = ur__rating # Careful ! ! !
for i, (s, mc, w) in enumerate(para_combs):
print "loop %d/%d" % (i, len(para_combs))
#if (i < 215):
# continue
starttime = datetime.datetime.now()
rs = RecommendatorViaWord2Vec()
rs.setup({'data': train,
'model_name': 'main_model',
'num_features': s,
'min_count': mc,
'window': w,
'K': K,
'iter': para_iter,
'batch_words': batch_words,
'variant': ur_name,
'load_existed': load_existed,
})
metrics = rs.calculate_metrics(train, test, N)
endtime = datetime.datetime.now()
interval = (endtime - starttime).seconds
print 'time consumption: %d' % (interval)
print metrics
precision, recall, f1 = metrics['precision'], metrics['recall'], metrics['f1']
cur.execute('insert into %s (size, min_count, window, precision, recall, f1)' % (table_name) +
'values (%d, %d, %d, %.19f, %.19f, %.19f)' % (s, mc, w, precision, recall, f1))
cx.commit()
cur.close()
cx.close()
def observe_word2vec_when_K_varies():
global arguments
#data_filename, delimiter = os.path.sep.join(['ml-latest-small', 'ratings.csv']), ','
data_filename, delimiter, data_set = os.path.sep.join(['ml-1m', 'ratings.dat']), '::', '1M'
#data_filename, delimiter = os.path.sep.join(['ml-10M100K', 'ratings.dat']), '::'
#data_filename, delimiter, data_set = os.path.sep.join(['ml-100k', 'u.data']), '\t', '100K'
seed = 2
#K = 10
train_percent = 0.8
test_data_inner_ratio = 0.8
train, test = extract_data_from_file_and_generate_train_and_test(data_filename, train_percent, seed, delimiter, test_data_inner_ratio)
#train, test = extract_data_from_file_and_generate_train_and_test(data_filename, 3, 0, seed, delimiter)
N = 20
para_iter = 30
batch_words = 10000
table_name_prefix = 'metrics__chap4_observe_word2ve_when_K_varies__N_%d__iter_%d__da_%s'
cx = sqlite3.connect('my_metrics.db')
cur = cx.cursor()
table_name = table_name_prefix % (N, para_iter, data_set)
print 'table_name:', table_name
cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='%s';" % table_name)
ret = cur.fetchall()
if 0 == len(ret):
sql = '''create table %s (
_row_ID integer primary key autoincrement,
size integer,
min_count integer,
window integer,
K integer,
precision decimal(30, 28),
recall decimal(30, 28),
f1 decimal(30, 28),
CreatedTime TimeStamp NOT NULL DEFAULT (datetime('now','localtime'))
);''' % (table_name)
cur.execute(sql)
cx.commit()
#para_size = range(100, 501, 10)
#para_min_count = range(1, 6, 1)
#para_window = range(1, 6, 1)
#para_combs = zip(para_size, para_min_count, para_window)
#para_combs = [[[(s, mc, w) for w in para_window] for mc in para_min_count] for s in para_size]
#para_combs = [(s, mc, w) for w in para_window for mc in para_min_count for s in para_size]
#para_combs = [[220, 1, 3]]
#print para_combs[0]
load_existed = False # Careful ! ! !
ur_name = ur__rating # Careful ! ! !
K_list = [4, 6, 8, 10, 12, 14, 16, 18, 20]
s, mc, w = 100, 1, 1
for i, K in enumerate(K_list):
print "loop %d/%d" % (i, len(K_list))
print 'current K: %d' % K
starttime = datetime.datetime.now()
rs = RecommendatorViaWord2Vec()
rs.setup({'data': train,
'model_name': 'main_model',
'num_features': s,
'min_count': mc,
'window': w,
'K': K,
'iter': para_iter,
'batch_words': batch_words,
'variant': ur_name,
'load_existed': load_existed,
})
metrics = rs.calculate_metrics(train, test, N)
endtime = datetime.datetime.now()
interval = (endtime - starttime).seconds
print 'time consumption: %d' % (interval)
print metrics
precision, recall, f1 = metrics['precision'], metrics['recall'], metrics['f1']
cur.execute('insert into %s (size, min_count, window, K, precision, recall, f1)' % (table_name) +
'values (%d, %d, %d, %d, %.19f, %.19f, %.19f)' % (s, mc, w, K, precision, recall, f1))
cx.commit()
cur.close()
cx.close()
def compare_variants():
#data_filename, delimiter = os.path.sep.join(['ml-latest-small', 'ratings.csv']), ','
data_filename, delimiter, data_set = os.path.sep.join(['ml-1m', 'ratings.dat']), '::', '1M'
#data_filename, delimiter = os.path.sep.join(['ml-10M100K', 'ratings.dat']), '::'
#data_filename, delimiter, data_set = os.path.sep.join(['ml-100k', 'u.data']), '\t', '100K'
init_tfidf(data_filename, delimiter) # func of module utility_user_repr
seed = 2
K = 10
train_percent = 0.8
test_data_inner_ratio = 0.8
train, test = extract_data_from_file_and_generate_train_and_test(data_filename, train_percent, seed, delimiter, test_data_inner_ratio)
#train, test = extract_data_from_file_and_generate_train_and_test(data_filename, 3, 0, seed, delimiter)
N = 20
para_iter = 30
batch_words = 10000
table_name_prefix = 'metrics__chap4_exp2_across_variants__N_%d__iter_%d__da_%s'
cx = sqlite3.connect('my_metrics.db')
cur = cx.cursor()
table_name = table_name_prefix % (N, para_iter, data_set)
print 'table_name:', table_name
cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='%s';" % table_name)
ret = cur.fetchall()
if 0 == len(ret):
sql = '''create table %s (
_row_ID integer primary key autoincrement,
size integer,
min_count integer,
window integer,
variant varchar(30),
precision decimal(30, 28),
recall decimal(30, 28),
f1 decimal(30, 28),
CreatedTime TimeStamp NOT NULL DEFAULT (datetime('now','localtime'))
);''' % (table_name)
cur.execute(sql)