-
Notifications
You must be signed in to change notification settings - Fork 0
/
Predictive Model for Mobike Users.py
1331 lines (1192 loc) · 56.6 KB
/
Predictive Model for Mobike Users.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
"""
Predictive Model for Mobike Users
Co-authors: xingyu Fu && shen Zheng
Institutions: Sun Yat_sen University && JiNan University && Gradient Trading
For contact: 443518347@qq.com
All Rights Reserved
"""
"""Import Libraries"""
from geohash import decode_exactly
from pandas import read_csv
from sklearn.neighbors import KDTree
from scipy.optimize import minimize
import numpy as np
import math
import csv
import xgboost as xgb
from xgboost.sklearn import XGBClassifier
from sklearn import grid_search
from random import seed
from random import randrange
import os
from collections import OrderedDict
"""Change the Working Directory"""
dire = "C:/Users/fxy/Documents/Academic/AI/Fintechlab/Code/Mobike_Contest"
os.chdir(dire)
del dire
"""Some Constants"""
N=3 #Number of predictions we are going to make
MAX_KM=3.0 #The Maximal distance we allow for a single bike trip
#(The average is 0.815 ; 1000000th is 0.493 ; 2000000th is 0.799 ; 3000000th is 1.67 ; 3100000th is 2.16 ; 3170000th is 3.212)
KD=5 #The number of destinations KDTree predict
TRICK_NUM=2 #The number of destinations Trick predict
Neighbor_Condition=0.5 #The distance threshold to characterize neighbors
Method4_Top = 5 # If the above threshold is exceeded , then we pick up 5 destinations to make prediction
Bayes_Num=4 #The maximal number of Negative examples we allow the algorithm to predict
stdv = 1 #The Standard Variance which the Gaussian PDF uses
time_scaler1=12.0
lat_scaler1=0.01
lon_scaler1=0.01
time_scaler2=1.20
lat_scaler2=0.1
lon_scaler2=0.1
Expand_Num = 4 #For each negative example , how many neighbours should a single Expander find.
"""Construct A Dictionary whose key is the orderid and the corresponding value is the specific date(TEST DATASET)"""
#Useful when we implement the Method6 in "test" mode
file_name_test = "test.csv"
orderid_time_test = read_csv(file_name_test,usecols=[0,4])
orderid_time_test = orderid_time_test.values
for row in orderid_time_test:
row[1] = int( row[1][8:10] )
orderid_time_test = dict( orderid_time_test )
del file_name_test
file_name_train="train.csv"
order_time_train=read_csv(file_name_train,usecols=[0,4])
order_time_train=order_time_train.values
for row in order_time_train:
row[1] = int( row[1][8:10] )
order_time_train= dict(order_time_train)
del file_name_train
orderid_time_test.update(order_time_train)
del order_time_train
"""Transform the date into Weekday(0) and Weekend(1)"""
def work_play(inf):
#prepare data
date=int( inf[8:10] )
#handle date
set_end={13,14,20,21,27,28}
dateflag=int(not (date in set_end))
return dateflag
"""Transform the time information into the float formation of hour (e.g. 13:27->13.45)"""
def hour_minute(inf):
hour=float(inf[11:13])
minute=float(inf[14:16])/60.0
return hour+minute
"""Calculate the distance between two points given their Latitude and Longitude (KM)"""
def distan(lat1 ,lng1 ,lat2 ,lng2 ):
radlat1=math.radians(lat1)
radlat2=math.radians(lat2)
a=radlat1-radlat2
b=math.radians(lng1)-math.radians(lng2)
s=2*math.asin(math.sqrt(math.pow(math.sin(a/2),2)+math.cos(radlat1)*math.cos(radlat2)*math.pow(math.sin(b/2),2)))
earth_radius=6378.137
s=s*earth_radius
if s<0:
return -s
else:
return s
"""Gaussian Distribution PDF (For Bayes)"""
def Gaussian_PDF(x,u,s):
exponential=math.exp( -( ((x-u)**2)/(2*s**2) ) )
return ( 1.0/(math.sqrt(2*math.pi)*s) ) * exponential
"""Bulid dictionary"""
def Build_dict(Set,Tag,Way):
#Set indicates the dataset which the dictionary is based on
#Tag indicates the key of the dictionary
#Way indicates the method that we manipulate the dataset
result=dict()
if Way==0 :#Add to the same list if tag repeated
for record in Set:
if record[Tag] in result:
result[ record[Tag] ].append(record)
else:
result[ record[Tag] ]=[]
result[ record[Tag] ].append(record)
else :#Count frequency if tag repeated (way==1)
for record in Set:
if record[Tag] in result:
result[ record[Tag] ]+=1
else:
result[ record[Tag] ]=1
return result
def random_subset(X,Y, split=0.01):
X_sub =list()
Y_sub =list()
sub_size = split * len(X)
while len(X_sub) < sub_size:
index = randrange( len(X) )
X_sub.append( X[index] )
Y_sub.append( Y[index] )
return X_sub,Y_sub
"""Feature Vector Generator"""
def Feature_Vector(methods, real_record, prediction_record, prediction_destination, Knowledges):
"""The Features constructed only by the real_record"""
F0 = 1 if (real_record[0] in Knowledges[0]) else 0 #Old Clients(1) or New Clients(0)
F1 = real_record[1] # Wether or not the start point is weekend
F2 = real_record[2] # The specific time in the start point
F3 = real_record[4] # The latitude of the start point
F4 = real_record[5] # The longitude of the start point
"""The Features constructed by the methods you use to create this specific negative examples"""
F5 = 1 if (methods == 1) else 0 #Use Method1
F6 = 1 if (methods == 2) else 0 #Use Method2
F7 = 1 if (methods == 3) else 0 #Use Method3
F8 = 1 if (methods == 4) else 0 #Use Method4
F9 = 1 if (methods == 5) else 0 #Use Method5
F10= 1 if (methods == 6) else 0 #Use Method6
FBayes = 1 if (methods == 7) else 0 #Use Method7
FtimtKD = 1 if (methods == 8) else 0 #Use Method8
"""The Features constructed by the personal history records of this specific user"""
F11 = 0
F12 = 0
F13 = 0
F14 = 0
F15 = 0
F16 = 0
if F0 != 0:
personal_history = Knowledges[0][ real_record[0] ] #From "train" (operator)
bool_same_start=[(1 if (rec[3]==real_record[3]) else 0) for rec in personal_history]
F11= sum( bool_same_start ) #How many times the specific user start his trip in this given start
F12= float(F11)/float( len( bool_same_start ) ) #The frequency of this given start point in the user's history
bool_same_end=[ (1 if rec[6]==prediction_destination else 0) for rec in personal_history ]
F13= sum( bool_same_end ) #How many times the specific user go to this prediction_destination
F14= float(F13)/float( len(bool_same_end) ) #The frequency of this given destination in the user's history
bool_same_start_end= [(1 if (bool_same_start[i] and bool_same_end[i]) else 0) for i in range( len(personal_history) )]
F15= sum( bool_same_start_end ) #How many times the specific route has been biked by this user
F16= float(F15)/float( len(bool_same_start_end) ) #The frequency of F15
del bool_same_start
del bool_same_end
del bool_same_start_end
del personal_history
"""The Features constructed by Popularity-Map"""
Popularity_Map_depart=Knowledges[3]
Popularity_Map_destin=Knowledges[4]
F17 = 0
F18 = 0
F19 = 0
if real_record[3] in Popularity_Map_depart:
F17= Popularity_Map_depart[ real_record[3] ] #Popularity of this given start in the city
if prediction_destination in Popularity_Map_destin:
F18= Popularity_Map_destin[ prediction_destination ] #Popularity of this given destination in the city
if real_record[3] in Knowledges[2]:
Same_start_users_records=Knowledges[2][ real_record[3] ] # From operator ("train")
F19= sum( [ (1 if rec[6]==prediction_destination else 0) for rec in Same_start_users_records ] ) #Popularity of this given path in the city
del Same_start_users_records
del Popularity_Map_depart
del Popularity_Map_destin
"""The Features constructed by the prediction_record"""
F20= prediction_record[1] #Wether or not the prediction_record is weekend
F21= (1 if (F1==F20) else 0) #Wether or not F1 and F20 are the same
"""Coefficient of Universal Gravity"""
F22 = 0 # Formula of Gravity -> (GMm)/r^2
if (methods == 2) or (methods == 6):
r=distan(real_record[4],real_record[5],prediction_record[4],prediction_record[5])
if r!=0:
F22= float(F17*F18)/(r**2)
else:
F22= np.nan
else:
r=distan(real_record[4],real_record[5],prediction_record[7],prediction_record[8])
if r!=0:
F22= float(F17*F18)/(r**2)
else:
F22= np.nan
# The time difference between the real_record and prediction_record
F23=0
if (methods == 2) or (methods == 6):
F23=np.nan
else:
F23=-(math.fabs(math.fabs(real_record[2]-prediction_record[2])-12)-12)
# The multiplication between start_point popularity and destination popularity
F24 = F17*F18
#Slicing the time into several sections (USing One Hot Encoding)
F25 = 1 if(real_record[2]>=6.0 and real_record[2]<9.5) else 0
F26 = 1 if(real_record[2]>=9.5 and real_record[2]<11.5) else 0
F27 = 1 if(real_record[2]>=11.5 and real_record[2]<14) else 0
F28 = 1 if(real_record[2]>=14.0 and real_record[2]<17.0) else 0
F29 = 1 if(real_record[2]>=17.0 and real_record[2]<20.0) else 0
F30 = 1 if(real_record[2]>=20.0 and real_record[2]<23.0) else 0
F31 = 1 if(real_record[2]>=23.0 or real_record[2]<6.0) else 0
#Feature by double_dict
dictionary=dict()
if F25 == 1:
dictionary = Knowledges[6][1]
elif F26 == 1:
dictionary = Knowledges[6][2]
elif F27 == 1:
dictionary = Knowledges[6][3]
elif F28 == 1:
dictionary = Knowledges[6][4]
elif F29 == 1:
dictionary = Knowledges[6][5]
elif F30 == 1:
dictionary = Knowledges[6][6]
else: #F31 == 1
dictionary = Knowledges[6][7]
F32 = 0
if prediction_destination in dictionary:
F32 = float(dictionary[ prediction_destination ]) / float(dictionary[ "sum" ])
if (methods != 6) and (methods !=2) :
Vector=[ F0,F1,F2,F3,F4,F5,F6,F7,F8,F9,F10,FBayes,FtimtKD,F11,F12,F13,F14,F15,F16,F17,F18,F19,F20,F21,F22,F23,F24,F25,F26,F27,F28,F29,F30,F31,F32,prediction_destination,prediction_record[7],prediction_record[8] ]
else:
Vector=[ F0,F1,F2,F3,F4,F5,F6,F7,F8,F9,F10,FBayes,FtimtKD,F11,F12,F13,F14,F15,F16,F17,F18,F19,F20,F21,F22,F23,F24,F25,F26,F27,F28,F29,F30,F31,F32,prediction_destination,prediction_record[4],prediction_record[5] ]
return Vector
def Feature_Vector1(methods, real_record, prediction_record, neighbor_record, prediction_destination, Knowledges):
"""The Features constructed only by the real_record"""
F0 = 1 if (real_record[0] in Knowledges[0]) else 0 #Old Clients(1) or New Clients(0)
F1 = real_record[1] # Wether or not the start point is weekend
F2 = real_record[2] # The specific time in the start point
F3 = real_record[4] # The latitude of the start point
F4 = real_record[5] # The longitude of the start point
"""The Features constructed by the methods you use to create this specific negative examples"""
F5 = 1 if (methods == 1) else 0 #Use Method1
F6 = 1 if (methods == 2) else 0 #Use Method2
F7 = 1 if (methods == 3) else 0 #Use Method3
F8 = 1 if (methods == 4) else 0 #Use Method4
F9 = 1 if (methods == 5) else 0 #Use Method5
F10= 1 if (methods == 6) else 0 #Use Method6
FBayes = 1 if (methods == 7) else 0 #Use Method7
FtimtKD = 1 if (methods == 8) else 0 #Use Method8
"""The Features constructed by the personal history records of this specific user"""
F11 = 0
F12 = 0
F13 = 0
F14 = 0
F15 = 0
F16 = 0
if F0 != 0:
personal_history = Knowledges[0][ real_record[0] ] #From "train" (operator)
bool_same_start=[(1 if (rec[3]==real_record[3]) else 0) for rec in personal_history]
F11= sum( bool_same_start ) #How many times the specific user start his trip in this given start
F12= float(F11)/float( len( bool_same_start ) ) #The frequency of this given start point in the user's history
bool_same_end=[ (1 if rec[6]==prediction_destination else 0) for rec in personal_history ]
F13= sum( bool_same_end ) #How many times the specific user go to this prediction_destination
F14= float(F13)/float( len(bool_same_end) ) #The frequency of this given destination in the user's history
bool_same_start_end= [(1 if (bool_same_start[i] and bool_same_end[i]) else 0) for i in range( len(personal_history) )]
F15= sum( bool_same_start_end ) #How many times the specific route has been biked by this user
F16= float(F15)/float( len(bool_same_start_end) ) #The frequency of F15
del bool_same_start
del bool_same_end
del bool_same_start_end
del personal_history
"""The Features constructed by Popularity-Map"""
Popularity_Map_depart=Knowledges[3]
Popularity_Map_destin=Knowledges[4]
F17 = 0
F18 = 0
F19 = 0
if real_record[3] in Popularity_Map_depart:
F17= Popularity_Map_depart[ real_record[3] ] #Popularity of this given start in the city
if prediction_destination in Popularity_Map_destin:
F18= Popularity_Map_destin[ prediction_destination ] #Popularity of this given destination in the city
if real_record[3] in Knowledges[2]:
Same_start_users_records=Knowledges[2][ real_record[3] ] # From operator ("train")
F19= sum( [ (1 if rec[6]==prediction_destination else 0) for rec in Same_start_users_records ] ) #Popularity of this given path in the city
del Same_start_users_records
del Popularity_Map_depart
del Popularity_Map_destin
"""The Features constructed by the prediction_record"""
F20= prediction_record[1] #Wether or not the prediction_record is weekend
F21= (1 if (F1==F20) else 0) #Wether or not F1 and F20 are the same
"""Coefficient of Universal Gravity"""
F22 = 0 # Formula of Gravity -> (GMm)/r^2
r=distan(real_record[4],real_record[5],neighbor_record[7],neighbor_record[8])
if r!=0:
F22= float(F17*F18)/(r**2)
else:
F22= np.nan
# The time difference between the real_record and prediction_record
F23=0
if (methods == 2) or (methods == 6):
F23=np.nan
else:
F23=-(math.fabs(math.fabs(real_record[2]-prediction_record[2])-12)-12)
# The multiplication between start_point popularity and destination popularity
F24 = F17*F18
#Slicing the time into several sections (USing One Hot Encoding)
F25 = 1 if(real_record[2]>=6.0 and real_record[2]<9.5) else 0
F26 = 1 if(real_record[2]>=9.5 and real_record[2]<11.5) else 0
F27 = 1 if(real_record[2]>=11.5 and real_record[2]<14) else 0
F28 = 1 if(real_record[2]>=14.0 and real_record[2]<17.0) else 0
F29 = 1 if(real_record[2]>=17.0 and real_record[2]<20.0) else 0
F30 = 1 if(real_record[2]>=20.0 and real_record[2]<23.0) else 0
F31 = 1 if(real_record[2]>=23.0 or real_record[2]<6.0) else 0
#Feature by double_dict
dictionary=dict()
if F25 == 1:
dictionary = Knowledges[6][1]
elif F26 == 1:
dictionary = Knowledges[6][2]
elif F27 == 1:
dictionary = Knowledges[6][3]
elif F28 == 1:
dictionary = Knowledges[6][4]
elif F29 == 1:
dictionary = Knowledges[6][5]
elif F30 == 1:
dictionary = Knowledges[6][6]
else: #F31 == 1
dictionary = Knowledges[6][7]
F32 = 0
if prediction_destination in dictionary:
F32 = float(dictionary[ prediction_destination ]) / float(dictionary[ "sum" ])
Vector=[ F0,F1,F2,F3,F4,F5,F6,F7,F8,F9,F10,FBayes,FtimtKD,F11,F12,F13,F14,F15,F16,F17,F18,F19,F20,F21,F22,F23,F24,F25,F26,F27,F28,F29,F30,F31,F32,prediction_destination,neighbor_record[7],neighbor_record[8] ]
return Vector
"""The destination to which the user used to go(we do not fix the start)"""
def Method1(real_record,negative_examples,Knowledges,operator):
if real_record[0] not in Knowledges[0]:
return None
personal_history = Knowledges[0][ real_record[0] ]#originated from operator (Must belongs to train)
for prediction_record in personal_history:
if distan(real_record[4],real_record[5],prediction_record[7],prediction_record[8]) > MAX_KM:
# If the distance between the start and destination is too large, then we say that it is impossible for them to form a bike trip.
continue
else:
prediction_destination=prediction_record[6]
negative=Feature_Vector(1, real_record, prediction_record, prediction_destination, Knowledges)
negative_examples.append(negative)
#Search the neighbours of the predicted destination
Expander = Knowledges[8]
dist,ind = Expander.query( [ [prediction_record[7]/lat_scaler1 , prediction_record[8]/lon_scaler1] ], k=Expand_Num)
for j in range( Expand_Num ):
prediction_destination=operator[ ind[0][j] ][6]
neighbor_record = operator[ ind[0][j] ]
negative=Feature_Vector1(1, real_record, prediction_record, neighbor_record, prediction_destination, Knowledges)
negative_examples.append(negative)
return None
"""The start from which the user used to start(we do not fix the destination)"""
def Method2(real_record,negative_examples,Knowledges,operator) :
if real_record[0] not in Knowledges[0]:
return None
personal_history=Knowledges[0][ real_record[0] ] #from operator(train)
for prediction_record in personal_history: #prediction_record form operator while real_record from operated
if distan(real_record[4],real_record[5],prediction_record[4],prediction_record[5]) > MAX_KM:
# If the distance between the start and destination is too large, then we say that it is impossible for them to form a bike trip.
continue
else:
prediction_destination=prediction_record[3]
negative=Feature_Vector(2, real_record, prediction_record, prediction_destination, Knowledges)
negative_examples.append(negative)
#Search the neighbours of the predicted destination
Expander = Knowledges[8]
dist,ind = Expander.query( [ [prediction_record[4]/lat_scaler1 , prediction_record[5]/lon_scaler1] ], k=Expand_Num)
for j in range( Expand_Num ):
prediction_destination=operator[ ind[0][j] ][6]
neighbor_record = operator[ ind[0][j] ]
negative=Feature_Vector1(2, real_record, prediction_record, neighbor_record, prediction_destination, Knowledges)
negative_examples.append(negative)
return None
"""The destination to which the user used to go in this given start (3 is in 1)"""
def Method3(real_record,negative_examples,Knowledges,operator):
if real_record[0] not in Knowledges[0]:
return None
personal_history=Knowledges[0][ real_record[0] ] #from operator
for prediction_record in personal_history:
if real_record[3] != prediction_record[3]:
#We are now looking for the personal records with the same start
continue
else:
prediction_destination=prediction_record[6]
negative=Feature_Vector(3, real_record, prediction_record, prediction_destination, Knowledges)
negative_examples.append(negative)
#Search the neighbours of the predicted destination
Expander = Knowledges[8]
dist,ind = Expander.query( [ [prediction_record[7]/lat_scaler1 , prediction_record[8]/lon_scaler1] ], k=Expand_Num)
for j in range( Expand_Num ):
prediction_destination=operator[ ind[0][j] ][6]
neighbor_record = operator[ ind[0][j] ]
negative=Feature_Vector1(3, real_record, prediction_record, neighbor_record,prediction_destination, Knowledges)
negative_examples.append(negative)
return None
"""The destination to which all the users used to go from this start"""
def Method4(real_record,negative_examples,Knowledges,operator):
if real_record[3] not in Knowledges[2]:
return None
destinations_from_record = Knowledges[2][ real_record[3] ] #from operator(Must be in train)
des_count=dict()
des_record=dict()
for record in destinations_from_record:
if record[6] not in des_count:
des_count[ record[6] ] = 1
des_record[ record[6] ] = record
else:
des_count[ record[6] ] += 1
des_count=sorted(des_count.items(),key=lambda d:d[1],reverse=False )
content=0
for loc in des_count:
if content >= Method4_Top:
break
else:
content+=1
prediction_record=des_record[ loc[0] ]
prediction_destination=loc[0]
negative=Feature_Vector(4, real_record, prediction_record, prediction_destination, Knowledges)
negative_examples.append(negative)
#Search the neighbours of the predicted destination
Expander = Knowledges[8]
dist,ind = Expander.query( [ [prediction_record[7]/lat_scaler1 , prediction_record[8]/lon_scaler1] ], k=Expand_Num)
for j in range( Expand_Num ):
prediction_destination=operator[ ind[0][j] ][6]
neighbor_record = operator[ ind[0][j] ]
negative=Feature_Vector1(4, real_record, prediction_record, neighbor_record, prediction_destination, Knowledges)
negative_examples.append(negative)
return None
"""The prediction made by Collaborative Fliter(Based on KDTree)"""
"""Note: This KD Tree focus on location"""
def Method5(real_record,negative_examples,Knowledges,operator) :
dist,ind=Knowledges[5].query([ [ (real_record[2])/time_scaler1, real_record[4]/lat_scaler1, real_record[5]/lon_scaler1] ] , k=KD)
num=KD
while len( set( [ operator[index][6] for index in ind[0] ] ) ) <= N-1:
num+=KD
dist,ind=Knowledges[5].query([ [ (real_record[2])/time_scaler1, real_record[4]/lat_scaler1, real_record[5]/lon_scaler1] ] , k=num)
for j in range(num):
prediction_record=operator[ ind[0][j] ] #the neighbors of real_record are from "train"(operator) set
prediction_destination=prediction_record[6]
negative=Feature_Vector(5, real_record, prediction_record, prediction_destination, Knowledges)
negative_examples.append(negative)
#Search the neighbours of the predicted destination
Expander = Knowledges[8]
dist,inde = Expander.query( [ [prediction_record[7]/lat_scaler1 , prediction_record[8]/lon_scaler1] ], k=Expand_Num)
for j in range( Expand_Num ):
prediction_destination=operator[ inde[0][j] ][6]
neighbor_record = operator[ inde[0][j] ]
negative=Feature_Vector1(5, real_record, prediction_record, neighbor_record, prediction_destination, Knowledges)
negative_examples.append(negative)
return None
"""The prediction made by Round_Trip trick"""
def Method6(real_record,negative_examples,Knowledges,operator,mode):
history_ed=Knowledges[1][ real_record[0] ]
des_distance=dict()
des_record=dict()
for prediction_record in history_ed:
if prediction_record[3] in des_distance:
continue
else:
if (prediction_record[1] == real_record[1]) and ( distan(real_record[4],real_record[5],prediction_record[4],prediction_record[5])<=MAX_KM ) :
des_distance[ prediction_record[3] ] = distan( real_record[4], real_record[5], prediction_record[4], prediction_record[5])
des_record[ prediction_record[3] ] = prediction_record
else:
continue
des_distance=sorted(des_distance.items(),key=lambda d:d[1],reverse=False )
content=0
for loc in des_distance[1:]:
if content >= TRICK_NUM:
break
else:
content+=1
prediction_record=des_record[ loc[0] ]
prediction_destination=loc[0]
if orderid_time_test[ prediction_record[-1] ] == orderid_time_test[ real_record[-1] ]:
negative=Feature_Vector(6, real_record, prediction_record, prediction_destination, Knowledges)
negative_examples.append(negative)
#Search the neighbours of the predicted destination
Expander = Knowledges[8]
dist,ind = Expander.query( [ [prediction_record[4]/lat_scaler1 , prediction_record[5]/lon_scaler1] ], k=Expand_Num)
for j in range( Expand_Num ):
prediction_destination=operator[ ind[0][j] ][6]
neighbor_record = operator[ ind[0][j] ]
negative=Feature_Vector1(6, real_record, prediction_record, neighbor_record, prediction_destination, Knowledges)
negative_examples.append(negative)
else:
negative=Feature_Vector(2, real_record, prediction_record, prediction_destination, Knowledges)
negative_examples.append(negative)
#Search the neighbours of the predicted destination
Expander = Knowledges[8]
dist,ind = Expander.query( [ [prediction_record[4]/lat_scaler1 , prediction_record[5]/lon_scaler1] ], k=Expand_Num)
for j in range( Expand_Num ):
prediction_destination=operator[ ind[0][j] ][6]
neighbor_record = operator[ ind[0][j] ]
negative=Feature_Vector1(2, real_record, prediction_record, neighbor_record, prediction_destination, Knowledges)
negative_examples.append(negative)
"""The prediction made by Naive Gaussian-Bayes Algorithm (Make Prediction Only Based On Time)(7 is in 1)"""
def Method7(real_record,negative_examples,Knowledges,operator):
if real_record[0] not in Knowledges[0]: #If the current user is not old user , then we do not use Bayes
return None
personal_history = Knowledges[0][ real_record[0] ]#originated from operator (Must belongs to train)
subhistory=[record for record in personal_history if record[1] == real_record[1]] # A subset of personal_history ,in which all the record share the same kind of date
l=float( len( subhistory ) )
time = real_record[2]
if l != 0.0 : # If the subhistory is un-empty
possible_destination=dict()
possible_destination_record=dict()
for record in subhistory:
if record[6] not in possible_destination:
possible_destination[ record[6] ] = 1.0
possible_destination_record[ record[6] ] = record
else:
possible_destination[ record[6] ] +=1.0#Record the frequency of the destinations
#Calculate the Bayes Probability of each possible destination and sort by probability
for loc in possible_destination:
def cost(u):
return sum([(math.fabs(math.fabs(record[2]-u)-12)-12)**2 for record in subhistory if record[6]==loc])
re=minimize( fun=cost,x0=(12.0,),method="SLSQP",bounds=((0,24),) )
u=(re.x)[0]
possible_destination[loc]=(possible_destination[loc]/l)*Gaussian_PDF(u+(math.fabs(math.fabs(time-u)-12)-12),u,stdv)
possible_destination=sorted(possible_destination.items(),key=lambda d:d[1],reverse=True)
if len(possible_destination) >= Bayes_Num:
possible_destination = possible_destination[ 0 : Bayes_Num ]
else:
pass
for loc in possible_destination:
prediction_record = possible_destination_record[ loc[0] ]
prediction_destination = loc[0]
negative=Feature_Vector(7, real_record, prediction_record, prediction_destination, Knowledges)
negative_examples.append(negative)
#Search the neighbours of the predicted destination
Expander = Knowledges[8]
dist,ind = Expander.query( [ [prediction_record[7]/lat_scaler1 , prediction_record[8]/lon_scaler1] ], k=Expand_Num)
for j in range( Expand_Num ):
prediction_destination=operator[ ind[0][j] ][6]
neighbor_record = operator[ ind[0][j] ]
negative=Feature_Vector1(7, real_record, prediction_record, neighbor_record, prediction_destination, Knowledges)
negative_examples.append(negative)
return None
else:
return None
"""The prediction made by Collaborative Fliter(Based on KDTree)"""
"""Note: This KD Tree focus on time"""
def Method8(real_record,negative_examples,Knowledges,operator) :
dist,ind=Knowledges[7].query([ [ (real_record[2])/time_scaler2, real_record[4]/lat_scaler2, real_record[5]/lon_scaler2] ] , k=KD)
num=KD
while len( set( [ operator[index][6] for index in ind[0] ] ) ) <= N-1:
num+=KD
dist,ind=Knowledges[7].query([ [ (real_record[2])/time_scaler2, real_record[4]/lat_scaler2, real_record[5]/lon_scaler2] ] , k=num)
for j in range(num):
prediction_record=operator[ ind[0][j] ] #the neighbors of real_record are from "train"(operator) set
prediction_destination=prediction_record[6]
negative=Feature_Vector(8, real_record, prediction_record, prediction_destination, Knowledges)
negative_examples.append(negative)
#Search the neighbours of the predicted destination
Expander = Knowledges[8]
dist,inde = Expander.query( [ [prediction_record[7]/lat_scaler1 , prediction_record[8]/lon_scaler1] ], k=Expand_Num)
for j in range( Expand_Num ):
prediction_destination=operator[ inde[0][j] ][6]
neighbor_record = operator[ inde[0][j] ]
negative=Feature_Vector1(8, real_record, prediction_record, neighbor_record, prediction_destination, Knowledges)
negative_examples.append(negative)
return None
"""Construct Negative Examples"""
def Negative_Examples(operated,operator,mode):
X_train_xgboost=[]
Y_train_xgboost=[]
test_xgboost=OrderedDict()
#Construct the name dictionary of all users in the operator("train") dataset
#the value corresponding to each name is a list of personal records in the operator dataset
namedict_or=Build_dict(operator,Tag=0,Way=0)
#Construct the name dictionary of all users in the operated("test") dataset
namedict_ed=Build_dict(operated,Tag=0,Way=0)
#Construct the departure dictionary of all records in the operator dataset
#the value corresponding to each departure point is a list of records which share the same departure point
departdict_or=Build_dict(operator,Tag=3,Way=0)
#Construct the popularity-map of all Departure points in the operator dataset
Popularity_Map_departure=Build_dict(operator,Tag=3,Way=1)
#Construct the popularity-map of all destinations in the operator dataset
Popularity_Map_destination=Build_dict(operator,Tag=6,Way=1)
#Construct KD Tree of the operator dataset
#This KD Tree mainly focus on location (Little Concern About the Time)
train_for_tree=[]
for record in operator:
sample_for_tree=[]
sample_for_tree.append( record[2]/time_scaler1 )
sample_for_tree.append( record[4]/lat_scaler1 )
sample_for_tree.append( record[5]/lon_scaler1 )
train_for_tree.append( sample_for_tree )
tree1=KDTree( train_for_tree )
#Construct KD Tree of the operator dataset
#This KD Tree mainly focus on time (Little Concern About the Location)
train_for_tree=[]
for record in operator:
sample_for_tree=[]
sample_for_tree.append( record[2]/time_scaler2 )
sample_for_tree.append( record[4]/lat_scaler2 )
sample_for_tree.append( record[5]/lon_scaler2 )
train_for_tree.append( sample_for_tree )
tree2=KDTree( train_for_tree )
#Construct KD Tree of the DESTINATION in operator dataset
#This KD Tree only focus on LOCATION!!!
#The mission of this KD TREE is to increase the coverage rate
train_for_tree=[]
for record in operator:
sample_for_tree=[]
sample_for_tree.append( record[7]/lat_scaler1 )
sample_for_tree.append( record[8]/lon_scaler1 )
train_for_tree.append( sample_for_tree )
tree3=KDTree( train_for_tree )
#Construction of Double Dictionary(First Key is the time sections ; Second Key is the destinations of the records which happen in each time section)
double_dict=dict()
double_dict[ 1 ] = dict()
double_dict[ 1 ][ "sum" ]=0
double_dict[ 2 ] = dict()
double_dict[ 2 ][ "sum" ]=0
double_dict[ 3 ] = dict()
double_dict[ 3 ][ "sum" ]=0
double_dict[ 4 ] = dict()
double_dict[ 4 ][ "sum" ]=0
double_dict[ 5 ] = dict()
double_dict[ 5 ][ "sum" ]=0
double_dict[ 6 ] = dict()
double_dict[ 6 ][ "sum" ]=0
double_dict[ 7 ] = dict()
double_dict[ 7 ][ "sum" ]=0
for record in operator:
if(record[2]>=6.0 and record[2]<9.5) :
if record[6] not in double_dict[ 1 ]:
double_dict[ 1 ][ record[6] ] = 1
double_dict[ 1 ][ "sum" ] += 1
else:
double_dict[ 1 ][ record[6] ] += 1
double_dict[ 1 ][ "sum" ] += 1
elif (record[2]>=9.5 and record[2]<11.5):
if record[6] not in double_dict[ 2 ]:
double_dict[ 2 ][ record[6] ] = 1
double_dict[ 2 ][ "sum" ] += 1
else:
double_dict[ 2 ][ record[6] ] += 1
double_dict[ 2 ][ "sum" ] += 1
elif (record[2]>=11.5 and record[2]<14):
if record[6] not in double_dict[ 3 ]:
double_dict[ 3 ][ record[6] ] = 1
double_dict[ 3 ][ "sum" ] += 1
else:
double_dict[ 3 ][ record[6] ] += 1
double_dict[ 3 ][ "sum" ] += 1
elif (record[2]>=14.0 and record[2]<17.0):
if record[6] not in double_dict[ 4 ]:
double_dict[ 4 ][ record[6] ] = 1
double_dict[ 4 ][ "sum" ] += 1
else:
double_dict[ 4 ][ record[6] ] += 1
double_dict[ 4 ][ "sum" ] += 1
elif (record[2]>=17.0 and record[2]<20.0):
if record[6] not in double_dict[ 5 ]:
double_dict[ 5 ][ record[6] ] = 1
double_dict[ 5 ][ "sum" ] += 1
else:
double_dict[ 5 ][ record[6] ] += 1
double_dict[ 5 ][ "sum" ] += 1
elif (record[2]>=20.0 and record[2]<23.0):
if record[6] not in double_dict[ 6 ]:
double_dict[ 6 ][ record[6] ] = 1
double_dict[ 6 ][ "sum" ] += 1
else:
double_dict[ 6 ][ record[6] ] += 1
double_dict[ 6 ][ "sum" ] += 1
else:
if record[6] not in double_dict[ 7 ]:
double_dict[ 7 ][ record[6] ] = 1
double_dict[ 7 ][ "sum" ] += 1
else:
double_dict[ 7 ][ record[6] ] += 1
double_dict[ 7 ][ "sum" ] += 1
#A combination of all the structures constructed above
Knowledges=( namedict_or, namedict_ed, departdict_or, Popularity_Map_departure, Popularity_Map_destination, tree1, double_dict, tree2, tree3)
del train_for_tree
del namedict_or
del namedict_ed
del departdict_or
del Popularity_Map_departure
del Popularity_Map_destination
del double_dict
del tree1
del tree2
del tree3
for real_record in operated:#operated can be interpreted as "test"
"""Construct Negative Examples For Each Record In The Operated Dataset"""
negative_examples=[]
Method1(real_record,negative_examples,Knowledges,operator) #The destination to which the user used to go(we do not fix the start)
Method2(real_record,negative_examples,Knowledges,operator) #The start from which the user used to start(we do not fix the destination)
Method3(real_record,negative_examples,Knowledges,operator) #The destination to which the user used to go in this given start (3 is in 1)
Method4(real_record,negative_examples,Knowledges,operator) #The destination to which all the users used to go from this start
Method5(real_record,negative_examples,Knowledges,operator) #The prediction made by Collaborative Fliter(Based on KDTree)
Method6(real_record,negative_examples,Knowledges,operator,mode) #The prediction made by Round_Trip trick
Method7(real_record,negative_examples,Knowledges,operator) #The prediction made by Naive Gaussian-Bayes Algorithm
Method8(real_record,negative_examples,Knowledges,operator) #The prediction made by Collaborative Fliter(Based on KDTree)
"""Construct Some Features about the Collective Behaviours of all Negative Examples"""
#Neighbour Counting
l=len(negative_examples)
Neighbour_Matrix=[ [0]*l for ww in range(l) ]
for pp in range( l ): #Draw the Neighbour Matrix
qq=pp+1
while qq <= l-1:
lat1,lng1=negative_examples[pp][-2],negative_examples[pp][-1]
lat2,lng2=negative_examples[qq][-2],negative_examples[qq][-1]
d=distan(lat1,lng1,lat2,lng2)
if d < Neighbor_Condition:
Neighbour_Matrix[pp][qq]=Neighbour_Matrix[qq][pp]=1
qq+=1
for pp in range( l ):# Sum the neighbors signal over rows of Neighbour_Matrix
del negative_examples[pp][-1]
del negative_examples[pp][-1]
negative_examples[pp].insert( len(negative_examples[pp])-1 , sum(Neighbour_Matrix[pp]) )
#Group by destination of negative examples
same_destination=dict()
for ii in range(len(negative_examples)):
example=negative_examples[ii]
if example[-1] not in same_destination:
same_destination[ example[-1] ]=[]
same_destination[ example[-1] ].append( ii )
else:#The list has already existed
same_destination[ example[-1] ].append( ii )
#Add One-Hot-Vector
for des in same_destination:
d=same_destination[ des ]
if len( d ) == 1:
pass
else: #If the same destination appears several times , then we add their one hot vector
m1=0
m2=0
m3=0
m4=0
m5=0
m6=0
m7=0
m8=0
for ii in d: # 5---11
m1+=negative_examples[ii][5]
m2+=negative_examples[ii][6]
m3+=negative_examples[ii][7]
m4+=negative_examples[ii][8]
m5+=negative_examples[ii][9]
m6+=negative_examples[ii][10]
m7+=negative_examples[ii][11]
m8+=negative_examples[ii][12]
for ii in d:
negative_examples[ii][5]=m1
negative_examples[ii][6]=m2
negative_examples[ii][7]=m3
negative_examples[ii][8]=m4
negative_examples[ii][9]=m5
negative_examples[ii][10]=m6
negative_examples[ii][11]=m7
negative_examples[ii][12]=m8
"""Transform the Location-Prediction problem into Classification problem which XGboost can handle"""
negative_examples=np.array( negative_examples , dtype=object )
if mode=="train":
lis=[ (1 if (des==real_record[3]) else 0) for des in negative_examples[ : , len(negative_examples[0])-1 ] ]
X_train_xgboost.extend( negative_examples[ : , 0:len(negative_examples[0])-1 ] )
Y_train_xgboost.extend( lis )
else: #mode == "test"
test_xgboost[ real_record[-1] ] = negative_examples
if mode=="train":
return np.array(X_train_xgboost) , Y_train_xgboost
else:
return test_xgboost
"""#####################################################################Main Function#####################################################################"""
"""#####################################################################Main Function#####################################################################"""
"""#####################################################################Main Function#####################################################################"""
"""#####################################################################Main Function#####################################################################"""
print("####################"+"Loading Data form disk")
"""Load Training Set(Stored in data_train)"""
# The Following is the content of elements in data_train
# 0. User Name
# 1. Wether_or_not the date of the record is weekend
# 2. The specific time of the record
# 3. Departure point(Geohash)
# 4. Latitude of Departure point
# 5. Longitude of Departure point
# 6. Destination(Geohash)
# 7. Latitude of Destination
# 8. Longitude of Destination
# 9. Orderid
file_name_train="train.csv"
dataframe_train=read_csv(file_name_train,usecols=[0,1,4,5,6])
dataframe_train=dataframe_train.sort_index(by='starttime') # Sort the training Dataset by date
data_train_raw=dataframe_train.values
data_train=[]
for train in data_train_raw:#Rearrange the order of features
lat1,lng1,a,b=decode_exactly( train[3] )
lat2,lng2,a,b=decode_exactly( train[4] )
train_sample=(train[1], work_play(train[2]), hour_minute(train[2]), train[3], float(lat1), float(lng1), train[4], float(lat2), float(lng2),train[0])
data_train.append(train_sample)
del file_name_train
del dataframe_train
del data_train_raw
data_train=np.array(data_train,dtype=object) #data_train is a numpy array which can be sliced, masked
#but can not use the append and extend function.
#The reason why we assert dtype=object is that we want a mixed type array
steps=np.array([262569,272210,265173,225281,236594,279554,288719,322201,314516,134159,209440,124816,150456,128408])
step=steps.cumsum()
#step=len(data_train)//Q
#Construct operated dataset , of which we generate the negative examples
#We can comprehend the operated set as the "test" set
#a subset of data_train
#Construct operator dataset , from which the information is extracted to build operated dataset
#We can comprehend the operator set as the "train" set
#a subset of data_train
operated=data_train[step[7]:]
operator=data_train[:step[7]]
operator=np.array(operator, dtype=object)
operated=np.array(operated, dtype=object)
"""Construct Negative Examples"""
X,Y = Negative_Examples(operated,operator,"train")
del operated
del operator
#Write the X into disk
name_X="CV_X"+".npy"
np.save(name_X, X)
#Write the Y into disk
name_Y="CV_Y"+".npy"
np.save(name_Y,Y)
del X
del Y
"""Load the Negative Examples into Python"""
"""The Reason why we save the negative examples into the disk is to save memory"""
X_train_xgboost=[] #This is the input train set with negative examples
Y_train_xgboost=[] #This is the output train set with negative examples
#Construct X_train_xgboost
#X_train_xgboost is a numpy array after construction
ar = np.load('CV_X.npy')
X_train_xgboost.extend(ar)
del ar
X_train_xgboost=np.array(X_train_xgboost)
#Construct Y_train_xgboost
dr = np.load('CV_Y.npy')
dr=list(dr)
Y_train_xgboost.extend(dr)
del dr
"""Data Preparation for XGBoost training"""
#Split training_dataset into old and new clients
X_old_train = []
Y_old_train = []
X_new_train = []
Y_new_train = []
for i in range( len( Y_train_xgboost ) ):
if X_train_xgboost[i][0] == 1: #Old
X_old_train.append(X_train_xgboost[i])
Y_old_train.append(Y_train_xgboost[i])
else:
X_new_train.append(X_train_xgboost[i])
Y_new_train.append(Y_train_xgboost[i])
del X_train_xgboost
del Y_train_xgboost
"""Train XGBoost and Hyperparameters Tuning(Old Clients)"""
"""Note: the training process is completed on the Old Clients' dataset"""
print("####################"+"Train XGboost and Hyperparameter Tuning(Old Clients)")
seed(1)
x,y=random_subset(X_old_train,Y_old_train) #x and y are used for Hyperparameter Tuning
x,all_x,all_y=np.array(x),np.array(X_old_train),Y_old_train#Change the structure into Numpy Array
del X_old_train
del Y_old_train
dtrain = xgb.DMatrix(all_x,all_y)
del all_x
del all_y
##input train_x as x ,train_y as y,test_x as test_X
param_test1 = {
'max_depth':[i for i in range(1,10,1)], ##use loop to extract the value