-
Notifications
You must be signed in to change notification settings - Fork 56
/
user_cate_shop.py
3474 lines (3081 loc) · 180 KB
/
user_cate_shop.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
from datetime import datetime
from datetime import timedelta
import pandas as pd
import pickle
import os
import numpy as np
from sklearn.model_selection import StratifiedKFold
import lightgbm as lgb
from dateutil.parser import parse
import warnings
from sklearn import preprocessing
warnings.filterwarnings('ignore')
# 读取用户数据(全量数据)
def get_basic_user_feat():
dump_path = './cache/basic_user_F12_7.pkl'
if os.path.exists(dump_path):
user = pd.read_pickle(dump_path)
else:
user = pd.read_pickle('./cache/origin_user.pkl')
user_info = user.copy()
age_df = pd.get_dummies(user["age"], prefix="age")
sex_df = pd.get_dummies(user["sex"], prefix="sex")
user_lv_df = pd.get_dummies(user["user_lv_cd"], prefix="user_lv_cd")
city_level_df = pd.get_dummies(user["city_level"], prefix="city_level")
province_df = pd.get_dummies(user["province"], prefix="province")
user = pd.concat([user[['user_id', 'city', 'county']], age_df, sex_df, user_lv_df, city_level_df, province_df],
axis=1)
city_count_map = user_info.city.value_counts()
province_count_map = user_info.province.value_counts()
user_info['province_count_map'] = user_info['province'].map(province_count_map).fillna(-1)
user_info['city_count_map'] = user_info['province'].map(city_count_map).fillna(-1) # city
now = datetime.today()
user_info['user_reg_tm'] = pd.to_datetime(user_info['user_reg_tm'])
user_info['user_duration'] = user_info['user_reg_tm'].fillna(now).apply(lambda x: (now - x).days)
_ = user_info.pop('user_reg_tm')
user_info.city_level = user_info.city_level.fillna(4.0)
user_stat = user_info[['user_id', 'province_count_map', 'city_count_map', 'user_duration']]
user = user.merge(user_stat, on='user_id', how='left')
pickle.dump(user, open(dump_path, 'wb'))
print('user finished')
return user
# 读取行为数据,与产品数据拼接(起始时间-结束时间的行为数据)
def get_actions_product(start_date, end_date):
dump_path = './cache/all_action_product_F12_7_%s_%s.pkl' % (start_date, end_date)
if os.path.exists(dump_path):
actions = pd.read_pickle(dump_path)
else:
actions = pd.read_pickle('./cache/origin_action.pkl')
product = pd.read_pickle('./cache/origin_product.pkl')
shop = pd.read_pickle('./cache/origin_shop.pkl')
actions = actions[(actions.action_time >= start_date) & (actions.action_time < end_date)]
actions = actions[actions['type'] != 5] # 训练集时间区间内无type=5, 仅测试集时间区间存在
actions = actions[actions['sku_id'].isin(product['sku_id'])] # 行为中sku_id不在product中的
actions = pd.merge(actions, product, on='sku_id', how='left')
actions = actions[actions['cate'] != 13] # cate13的数据没有购买行为
actions = pd.merge(actions, shop[['shop_id', 'vender_id']], on=['shop_id'], how='left')
print(actions.shape)
actions = actions[actions['vender_id'] != 3666] # 数据没有购买行为
print(actions.shape)
actions.to_pickle(dump_path)
return actions
# 读取行为数据,与产品数据拼接(用于生成购物车特征)
def get_actions_product_cart(start_date, end_date):
dump_path = './cache/all_action_product_cart_F12_7_%s_%s.pkl' % (start_date, end_date)
if os.path.exists(dump_path):
actions = pd.read_pickle(dump_path)
else:
actions = pd.read_pickle('./cache/origin_action.pkl')
product = pd.read_pickle('./cache/origin_product.pkl')
shop = pd.read_pickle('./cache/origin_shop.pkl')
actions['action_time'] = pd.to_datetime(actions['action_time'])
actions = actions[(actions.action_time >= start_date) & (actions.action_time < end_date)]
actions = actions[actions['sku_id'].isin(product['sku_id'])] # 行为中sku_id不在product中的
actions = pd.merge(actions, product, on='sku_id', how='left')
actions = actions[actions['cate'] != 13] # cate13的数据没有购买行为
actions = pd.merge(actions, shop[['shop_id', 'vender_id']], on=['shop_id'], how='left')
print(actions.shape)
actions = actions[actions['vender_id'] != 3666] # 数据没有购买行为
print(actions.shape)
actions.to_pickle(dump_path)
return actions
# 行为比例特征(2.01-4.08) 滑窗
def get_accumulate_user_feat_cart(start_date, end_date):
dump_path = './cache/user_feat_accumulate_cart_F12_7_%s_%s.pkl' % (start_date, end_date)
if os.path.exists(dump_path):
f11_actions = pd.read_pickle(dump_path)
else:
actions = get_actions_product_cart(start_date, end_date)
df = pd.get_dummies(actions['type'], prefix='%s-%s-action' % (start_date, end_date))
actions = pd.concat([actions[['user_id', 'cate', 'shop_id']], df], axis=1)
# 索引
f11_actions = actions[['user_id', 'cate', 'shop_id']].drop_duplicates()
actions1 = actions.drop(['cate', 'shop_id'], axis=1)
actions1 = actions1.groupby(['user_id'], as_index=False).sum().add_prefix('user_id_')
actions1['user_action_1_ratio_%s_%s' % (start_date, end_date)] = actions1['user_id_%s-%s-action_2' % (
start_date, end_date)] / actions1['user_id_%s-%s-action_1' % (start_date, end_date)]
actions1['user_action_4_ratio_%s_%s' % (start_date, end_date)] = actions1['user_id_%s-%s-action_2' % (
start_date, end_date)] / actions1['user_id_%s-%s-action_4' % (start_date, end_date)]
actions1['user_action_3_ratio_%s_%s' % (start_date, end_date)] = actions1['user_id_%s-%s-action_2' % (
start_date, end_date)] / actions1['user_id_%s-%s-action_3' % (start_date, end_date)]
actions1['user_action_5_ratio_%s_%s' % (start_date, end_date)] = actions1['user_id_%s-%s-action_2' % (
start_date, end_date)] / actions1['user_id_%s-%s-action_5' % (start_date, end_date)]
actions1.rename(columns={'user_id_user_id': 'user_id'}, inplace=True)
actions2 = actions.drop(['user_id', 'shop_id'], axis=1)
actions2 = actions2.groupby(['cate'], as_index=False).sum().add_prefix('cate_')
actions2['cate_action_1_ratio_%s_%s' % (start_date, end_date)] = actions2['cate_%s-%s-action_2' % (
start_date, end_date)] / actions2['cate_%s-%s-action_1' % (start_date, end_date)]
actions2['cate_action_4_ratio_%s_%s' % (start_date, end_date)] = actions2['cate_%s-%s-action_2' % (
start_date, end_date)] / actions2['cate_%s-%s-action_4' % (start_date, end_date)]
actions2['cate_action_3_ratio_%s_%s' % (start_date, end_date)] = actions2['cate_%s-%s-action_2' % (
start_date, end_date)] / actions2['cate_%s-%s-action_3' % (start_date, end_date)]
actions2['cate_action_5_ratio_%s_%s' % (start_date, end_date)] = actions2['cate_%s-%s-action_2' % (
start_date, end_date)] / actions2['cate_%s-%s-action_5' % (start_date, end_date)]
actions2.rename(columns={'cate_cate': 'cate'}, inplace=True)
actions3 = actions.drop(['user_id', 'cate'], axis=1)
actions3 = actions3.groupby(['shop_id'], as_index=False).sum().add_prefix('shop_id_')
actions3['shop_action_1_ratio_%s_%s' % (start_date, end_date)] = actions3['shop_id_%s-%s-action_2' % (
start_date, end_date)] / actions3['shop_id_%s-%s-action_1' % (start_date, end_date)]
actions3['shop_action_4_ratio_%s_%s' % (start_date, end_date)] = actions3['shop_id_%s-%s-action_2' % (
start_date, end_date)] / actions3['shop_id_%s-%s-action_4' % (start_date, end_date)]
actions3['shop_action_3_ratio_%s_%s' % (start_date, end_date)] = actions3['shop_id_%s-%s-action_2' % (
start_date, end_date)] / actions3['shop_id_%s-%s-action_3' % (start_date, end_date)]
actions3['shop_action_5_ratio_%s_%s' % (start_date, end_date)] = actions3['shop_id_%s-%s-action_2' % (
start_date, end_date)] / actions3['shop_id_%s-%s-action_5' % (start_date, end_date)]
actions3.rename(columns={'shop_id_shop_id': 'shop_id'}, inplace=True)
actions4 = actions
actions4 = actions4.groupby(['user_id', 'cate', 'shop_id'], as_index=False).sum().add_prefix(
'user_cate_shop_id_')
actions4['user_cate_shop_id_action_1_ratio_%s_%s' % (start_date, end_date)] = actions4[
'user_cate_shop_id_%s-%s-action_2' % (
start_date, end_date)] / \
actions4[
'user_cate_shop_id_%s-%s-action_1' % (
start_date, end_date)]
actions4['user_cate_shop_id_action_4_ratio_%s_%s' % (start_date, end_date)] = actions4[
'user_cate_shop_id_%s-%s-action_2' % (
start_date, end_date)] / \
actions4[
'user_cate_shop_id_%s-%s-action_4' % (
start_date, end_date)]
actions4['user_cate_shop_id_action_3_ratio_%s_%s' % (start_date, end_date)] = actions4[
'user_cate_shop_id_%s-%s-action_2' % (
start_date, end_date)] / \
actions4[
'user_cate_shop_id_%s-%s-action_3' % (
start_date, end_date)]
actions4['user_cate_shop_id_action_5_ratio_%s_%s' % (start_date, end_date)] = actions4[
'user_cate_shop_id_%s-%s-action_2' % (
start_date, end_date)] / \
actions4[
'user_cate_shop_id_%s-%s-action_5' % (
start_date, end_date)]
actions4.rename(columns={'user_cate_shop_id_user_id': 'user_id', 'user_cate_shop_id_cate': 'cate',
'user_cate_shop_id_shop_id': 'shop_id'}, inplace=True)
# 拼接
f11_actions = f11_actions.merge(actions1, on='user_id', how='left')
f11_actions = f11_actions.merge(actions2, on='cate', how='left')
f11_actions = f11_actions.merge(actions3, on='shop_id', how='left')
f11_actions = f11_actions.merge(actions4, on=['user_id', 'cate', 'shop_id'], how='left')
print('accumulate user cart finished')
return f11_actions
# 行为比例特征(2.01-4.08) 滑窗
def get_accumulate_user_feat(start_date, end_date):
dump_path = './cache/user_feat_accumulate_F12_7_%s_%s.pkl' % (start_date, end_date)
if os.path.exists(dump_path):
f11_actions = pd.read_pickle(dump_path)
else:
actions = get_actions_product(start_date, end_date)
df = pd.get_dummies(actions['type'], prefix='%s-%s-action' % (start_date, end_date))
actions = pd.concat([actions[['user_id', 'cate', 'shop_id']], df], axis=1)
# 索引
f11_actions = actions[['user_id', 'cate', 'shop_id']].drop_duplicates()
actions1 = actions.drop(['cate', 'shop_id'], axis=1)
actions1 = actions1.groupby(['user_id'], as_index=False).sum().add_prefix('user_id_')
actions1['user_action_1_ratio_%s_%s' % (start_date, end_date)] = actions1['user_id_%s-%s-action_2' % (
start_date, end_date)] / actions1['user_id_%s-%s-action_1' % (start_date, end_date)]
actions1['user_action_4_ratio_%s_%s' % (start_date, end_date)] = actions1['user_id_%s-%s-action_2' % (
start_date, end_date)] / actions1['user_id_%s-%s-action_4' % (start_date, end_date)]
actions1['user_action_3_ratio_%s_%s' % (start_date, end_date)] = actions1['user_id_%s-%s-action_2' % (
start_date, end_date)] / actions1['user_id_%s-%s-action_3' % (start_date, end_date)]
actions1.rename(columns={'user_id_user_id': 'user_id'}, inplace=True)
actions2 = actions.drop(['user_id', 'shop_id'], axis=1)
actions2 = actions2.groupby(['cate'], as_index=False).sum().add_prefix('cate_')
actions2['cate_action_1_ratio_%s_%s' % (start_date, end_date)] = actions2['cate_%s-%s-action_2' % (
start_date, end_date)] / actions2['cate_%s-%s-action_1' % (start_date, end_date)]
actions2['cate_action_4_ratio_%s_%s' % (start_date, end_date)] = actions2['cate_%s-%s-action_2' % (
start_date, end_date)] / actions2['cate_%s-%s-action_4' % (start_date, end_date)]
actions2['cate_action_3_ratio_%s_%s' % (start_date, end_date)] = actions2['cate_%s-%s-action_2' % (
start_date, end_date)] / actions2['cate_%s-%s-action_3' % (start_date, end_date)]
actions2.rename(columns={'cate_cate': 'cate'}, inplace=True)
actions3 = actions.drop(['user_id', 'cate'], axis=1)
actions3 = actions3.groupby(['shop_id'], as_index=False).sum().add_prefix('shop_id_')
actions3['shop_action_1_ratio_%s_%s' % (start_date, end_date)] = actions3['shop_id_%s-%s-action_2' % (
start_date, end_date)] / actions3['shop_id_%s-%s-action_1' % (start_date, end_date)]
actions3['shop_action_4_ratio_%s_%s' % (start_date, end_date)] = actions3['shop_id_%s-%s-action_2' % (
start_date, end_date)] / actions3['shop_id_%s-%s-action_4' % (start_date, end_date)]
actions3['shop_action_3_ratio_%s_%s' % (start_date, end_date)] = actions3['shop_id_%s-%s-action_2' % (
start_date, end_date)] / actions3['shop_id_%s-%s-action_3' % (start_date, end_date)]
actions3.rename(columns={'shop_id_shop_id': 'shop_id'}, inplace=True)
actions4 = actions
actions4 = actions4.groupby(['user_id', 'cate', 'shop_id'], as_index=False).sum().add_prefix(
'user_cate_shop_id_')
actions4['user_cate_shop_id_action_1_ratio_%s_%s' % (start_date, end_date)] = actions4[
'user_cate_shop_id_%s-%s-action_2' % (
start_date, end_date)] / \
actions4[
'user_cate_shop_id_%s-%s-action_1' % (
start_date, end_date)]
actions4['user_cate_shop_id_action_4_ratio_%s_%s' % (start_date, end_date)] = actions4[
'user_cate_shop_id_%s-%s-action_2' % (
start_date, end_date)] / \
actions4[
'user_cate_shop_id_%s-%s-action_4' % (
start_date, end_date)]
actions4['user_cate_shop_id_action_3_ratio_%s_%s' % (start_date, end_date)] = actions4[
'user_cate_shop_id_%s-%s-action_2' % (
start_date, end_date)] / \
actions4[
'user_cate_shop_id_%s-%s-action_3' % (
start_date, end_date)]
actions4.rename(columns={'user_cate_shop_id_user_id': 'user_id', 'user_cate_shop_id_cate': 'cate',
'user_cate_shop_id_shop_id': 'shop_id'}, inplace=True)
# 拼接
f11_actions = f11_actions.merge(actions1, on='user_id', how='left')
f11_actions = f11_actions.merge(actions2, on='cate', how='left')
f11_actions = f11_actions.merge(actions3, on='shop_id', how='left')
f11_actions = f11_actions.merge(actions4, on=['user_id', 'cate', 'shop_id'], how='left')
print('accumulate user finished')
return f11_actions
# 基础统计特征
def get_stat_feat(start_date, end_date):
dump_path = './cache/stat_feat_accumulate_F12_7_%s_%s.pkl' % (start_date, end_date)
if os.path.exists(dump_path):
action = pd.read_pickle(dump_path)
else:
action = get_actions_product(start_date, end_date)
action_index = action[['user_id', 'cate', 'shop_id']].drop_duplicates()
# 行为onehot
action_type = pd.get_dummies(action['type'])
action_type.columns = ['act_1', 'act_2', 'act_3', 'act_4']
action_type = action_type[['act_1', 'act_2', 'act_3', 'act_4']]
action_type['cate'] = action['cate']
action_type['user_id'] = action['user_id']
action_type['shop_id'] = action['shop_id']
# 基于user_id的统计特征
user_stat = action[['user_id']].drop_duplicates()
user_action_count = action.groupby('user_id')['type'].count()
user_order_count = action_type.groupby('user_id')['act_2'].sum()
user_order_rate = user_order_count / (user_action_count).fillna(0)
user_cate_count = action.groupby('user_id')['cate'].nunique()
user_sku_count = action.groupby('user_id')['sku_id'].nunique()
user_shop_count = action.groupby('user_id')['shop_id'].nunique()
user_stat['user_action_count_%s_%s' % (start_date, end_date)] = user_action_count
user_stat['user_order_rate_%s_%s' % (start_date, end_date)] = user_order_rate
user_stat['user_cate_count_%s_%s' % (start_date, end_date)] = user_cate_count
user_stat['user_sku_count_%s_%s' % (start_date, end_date)] = user_sku_count
user_stat['user_shop_count_%s_%s' % (start_date, end_date)] = user_shop_count
# 基于cate的统计特征
cate_stat = action[['cate']].drop_duplicates()
# cate下的用户特征
cate_user_count = action.groupby('cate')['user_id'].count()
cate_user_nunique = action.groupby('cate')['user_id'].nunique()
cate_order_count = action_type.groupby('cate')['act_2'].sum()
cate_order_rate = cate_order_count / cate_user_count
# cate下:购买用户/总用户
cate_order_user_count = action_type.groupby(['cate', 'user_id'])['act_2'].sum().reset_index()
cate_order_user_count = cate_order_user_count[cate_order_user_count.act_2 > 0].groupby('cate')[
'user_id'].nunique()
cate_order_user_rate = (cate_order_user_count / cate_user_nunique)
cate_sku_nunique = action.groupby('cate')['sku_id'].nunique()
# cate下的店铺特征
cate_shop_count = action.groupby('cate')['shop_id'].count()
cate_shop_nunique = action.groupby('cate')['shop_id'].nunique()
cate_shop_order_count = action_type.groupby('cate')['act_2'].sum()
cate_shop_order_rate = cate_shop_order_count / cate_shop_count
# cate下: 购买店铺/总店铺
cate_order_shop_count = action_type.groupby(['cate', 'shop_id'])['act_2'].sum().reset_index()
cate_order_shop_count = cate_order_shop_count[cate_order_shop_count.act_2 > 0].groupby('cate')[
'shop_id'].nunique()
cate_order_shop_rate = (cate_order_shop_count / cate_shop_nunique)
cate_stat['cate_user_count_%s_%s' % (start_date, end_date)] = cate_user_count
cate_stat['cate_user_nunique_%s_%s' % (start_date, end_date)] = cate_user_nunique
cate_stat['cate_order_rate_%s_%s' % (start_date, end_date)] = cate_order_rate.fillna(0)
cate_stat['cate_order_user_count_%s_%s' % (start_date, end_date)] = cate_order_user_count
cate_stat['cate_order_user_rate_%s_%s' % (start_date, end_date)] = cate_order_user_rate
cate_stat['cate_sku_nunique_%s_%s' % (start_date, end_date)] = cate_sku_nunique
cate_stat['cate_shop_nunique_%s_%s' % (start_date, end_date)] = cate_shop_nunique
cate_stat['cate_shop_order_rate_%s_%s' % (start_date, end_date)] = cate_shop_order_rate
cate_stat['cate_order_shop_count_%s_%s' % (start_date, end_date)] = cate_order_shop_count
cate_stat['cate_order_shop_rate_%s_%s' % (start_date, end_date)] = cate_order_shop_rate
# 基于shop_id的统计特征
shop_stat = action[['shop_id']].drop_duplicates()
shop_user_count = action.groupby('shop_id')['user_id'].count()
shop_user_nunique = action_type.groupby('shop_id')['user_id'].nunique()
shop_order_count = action_type.groupby('shop_id')['act_2'].sum()
shop_order_rate = shop_order_count / (shop_user_count).fillna(0)
shop_sku_nunique = action.groupby('shop_id')['sku_id'].nunique()
shop_sku_count = action.groupby('shop_id')['sku_id'].count()
# 店铺下:购买用户/总用户
shop_order_user_count = action_type.groupby(['shop_id', 'user_id'])['act_2'].sum().reset_index()
shop_order_user_count = shop_order_user_count[shop_order_user_count.act_2 > 0].groupby('shop_id')[
'user_id'].nunique()
shop_order_user_rate = (shop_order_user_count / shop_user_nunique)
shop_stat['shop_user_count_%s_%s' % (start_date, end_date)] = shop_user_count
shop_stat['shop_user_nunique_%s_%s' % (start_date, end_date)] = shop_user_nunique
shop_stat['shop_order_rate_%s_%s' % (start_date, end_date)] = shop_order_rate
shop_stat['shop_sku_count_%s_%s' % (start_date, end_date)] = shop_sku_count
shop_stat['shop_sku_nunique_%s_%s' % (start_date, end_date)] = shop_sku_nunique
shop_stat['shop_order_user_count_%s_%s' % (start_date, end_date)] = shop_order_user_count
shop_stat['shop_order_user_rate_%s_%s' % (start_date, end_date)] = shop_order_user_rate
action = pd.merge(action_index, user_stat, on='user_id', how='left')
action = pd.merge(action, cate_stat, on='cate', how='left')
action = pd.merge(action, shop_stat, on='shop_id', how='left')
action.to_pickle(dump_path)
print('stat_feat finished')
return action
def get_hours(start_date, end_date):
d = parse(end_date) - parse(start_date)
hours = int(d.days * 24 + d.seconds / 3600)
return hours
# 行为时间特征
def get_time_feat(start_date, end_date):
dump_path = './cache/time_feature_F12_7_%s_%s.pkl' % (start_date, end_date)
if os.path.exists(dump_path):
f11_actions = pd.read_pickle(dump_path)
else:
actions = get_actions_product(start_date, end_date)
f11_actions = actions[['user_id']].drop_duplicates()
active_days = actions[['user_id', 'action_time']]
buy_days = actions[['user_id', 'action_time', 'type']]
active_last = actions[['user_id', 'action_time']]
buy_last = actions[['user_id', 'action_time', 'type']]
# 活动天数
active_days = active_days.groupby(['user_id', 'action_time']).size().reset_index()
active_days = active_days.groupby('user_id').size().reset_index()
active_days.rename(columns={0: 'user_active_days'}, inplace=True)
# 购买天数
buy_days = buy_days[buy_days['type'] == 2]
del buy_days['type']
buy_days = buy_days.groupby(['user_id', 'action_time']).size().reset_index()
buy_days = buy_days.groupby('user_id').size().reset_index()
buy_days.rename(columns={0: 'user_buy_days'}, inplace=True)
# 最近交互时间
active_last = active_last.sort_values(by='action_time', ascending=False)
active_last = active_last.drop_duplicates('user_id')
active_last['user_active_last'] = active_last['action_time'].apply(lambda x: get_hours(x, end_date))
del active_last['action_time']
# 最近购买时间(h)
buy_last = buy_last[buy_last['type'] == 2]
del buy_last['type']
buy_last = buy_last.sort_values(by='action_time', ascending=False)
buy_last = buy_last.drop_duplicates('user_id')
buy_last['user_buy_last'] = buy_last['action_time'].apply(lambda x: get_hours(x, end_date))
del buy_last['action_time']
f11_actions = f11_actions.merge(active_days, on='user_id', how='left')
f11_actions = f11_actions.merge(buy_days, on='user_id', how='left')
f11_actions = f11_actions.merge(active_last, on='user_id', how='left')
f11_actions = f11_actions.merge(buy_last, on='user_id', how='left')
pickle.dump(f11_actions, open(dump_path, 'wb'))
print('time finished')
return f11_actions
# 店铺特征
def get_shop_feat(start_date, end_date):
dump_path = './cache/shop_feature_F12_7_%s_%s.pkl' % (start_date, end_date)
if os.path.exists(dump_path):
shop_feature = pd.read_pickle(dump_path)
else:
shop = pd.read_pickle('./cache/origin_shop.pkl')
shop = shop[shop['vender_id'] != 3666]
del shop['vender_id']
shop = shop.drop_duplicates(['cate', 'shop_id'])
shop['vip_ratio'] = shop['vip_num'] / shop['fans_num']
shop_info = shop.copy()
action_shop = get_actions_product(start_date, end_date)
now = pd.to_datetime(action_shop.action_time.max())
shop_info['shop_reg_tm'] = pd.to_datetime(shop_info['shop_reg_tm'])
shop_info['shop_duration'] = shop_info['shop_reg_tm'].fillna(now).apply(lambda x: (now - x).days)
_ = shop_info.pop('shop_reg_tm')
cate_count_map = shop_info.cate.value_counts()
shop_info['cate_count_map'] = shop_info['cate'].map(cate_count_map).fillna(-1)
shop_info['cate_shop'] = shop_info['cate'].fillna(-1)
_ = shop_info.pop('cate')
action_shop = action_shop[['user_id', 'sku_id', 'action_time', 'shop_id', 'type']]
action_shop = action_shop.merge(shop_info[['shop_id', 'cate_shop']], on='shop_id', how='left')
action_shop['order'] = (action_shop.type == 2).astype('int8')
action_shop['explor'] = (action_shop.type == 1).astype('int8')
shop_stat = pd.DataFrame()
shop_stat['shop_order_mean'] = action_shop.groupby('shop_id')['order'].mean()
shop_stat['shop_order_sum'] = action_shop.groupby('shop_id')['order'].sum()
shop_stat['shop_act_count'] = action_shop.groupby('shop_id')['order'].count()
shop_cate_stat = pd.DataFrame()
shop_cate_stat['shop_cate_order_mean'] = action_shop.groupby('cate_shop')['order'].mean()
shop_cate_stat['shop_cate_order_sum'] = action_shop.groupby('cate_shop')['order'].sum()
shop_cate_stat['shop_cate_order_count'] = action_shop.groupby('cate_shop')['order'].count()
shop_stat = shop_stat.reset_index()
shop_cate_stat = shop_cate_stat.reset_index()
shop_info_ = shop_info.merge(shop_stat, on='shop_id', how='left')
shop_info_ = shop_info_.merge(shop_cate_stat, on='cate_shop', how='left')
shop_feature = shop_info_.merge(shop_stat, on='shop_id', how='left')
pickle.dump(shop_feature, open(dump_path, 'wb'))
del shop_feature['cate_shop']
print('shop finished')
return shop_feature
# 商品和评论特征
def get_product_stat_feat(start_date, end_date):
dump_path = './cache/product_feature_F12_7_%s_%s.pkl' % (start_date, end_date)
if os.path.exists(dump_path):
cate_stat = pd.read_pickle(dump_path)
else:
product_ori = pd.read_pickle('./cache/origin_product.pkl')
comment_ori = pd.read_pickle('./cache/origin_comment.pkl')
cate_info = product_ori.copy()
comment_sku = comment_ori.groupby('sku_id').sum().reset_index()
cate_info = cate_info.merge(comment_sku, on='sku_id', how='left')
cate_stat_1 = pd.DataFrame()
cate_stat_1['cate_sku_count'] = cate_info.groupby('cate')['sku_id'].count()
cate_stat_1['cate_brand_count'] = cate_info.groupby('cate')['brand'].nunique()
cate_stat_1['cate_shop_count'] = cate_info.groupby('cate')['shop_id'].nunique()
cate_stat_1['cate_comments_count'] = cate_info.groupby('cate')['comments'].sum()
cate_stat_1['cate_good_comments_count'] = cate_info.groupby('cate')['good_comments'].sum()
cate_stat_1['cate_bad_comments_count'] = cate_info.groupby('cate')['bad_comments'].sum()
cate_stat_1['cate_good_rate'] = cate_stat_1['cate_good_comments_count'] / cate_stat_1['cate_comments_count']
cate_stat_1['cate_good_rate'] = cate_stat_1.cate_good_rate.fillna(cate_stat_1.cate_good_rate.mean())
cate_stat = cate_stat_1.reset_index()
pickle.dump(cate_stat, open(dump_path, 'wb'))
print('product finished')
return cate_stat
def cate_user_reg(d):
if d <0:
d = -1
elif d>=0 and d<=3:
d = 1
elif d>3 and d<=6:
d = 2
elif d>6 and d<=12:
d = 3
elif d>12 and d<=24:
d = 4
elif d>24 and d<=48:
d = 5
else:
d = 6
return d
# 用户特征
def user_features(start_date, end_date):
dump_path = './cache/user_features_F12_7_%s_2.pkl' % (end_date)
if os.path.exists(dump_path):
actions = pd.read_pickle(dump_path)
else:
user = pd.read_pickle('./cache/origin_user.pkl')
user['reg_duration'] = ((pd.to_datetime(user['user_reg_tm']) - pd.to_datetime('2018/04/16')).dt.days) // 30
user['reg_duration_cate'] = user['reg_duration'].apply(cate_user_reg)
sub_action = get_actions_product(start_date, end_date)
end_date = pd.to_datetime(end_date)
day = timedelta(1, 0)
print('=====> 提取特征...')
sub_action['action_time'] = pd.to_datetime(sub_action['action_time'])
sub_1 = sub_action[(sub_action['action_time'] >= end_date - 1 * day) & (sub_action['action_time'] < end_date)]
sub_7 = sub_action[(sub_action['action_time'] >= end_date - 7 * day) & (sub_action['action_time'] < end_date)]
sub_all = sub_action[sub_action['action_time'] < end_date]
# ========================================
# 用户历史行为
# ========================================
# 6种行为特征
df = pd.get_dummies(sub_all['type'], prefix='type')
df['type_0'] = df.sum(axis=1)
df = pd.concat([sub_all[['user_id', 'cate', 'shop_id']], df], axis=1)
# 行为sum
u_feature_all = df.drop(['cate', 'shop_id'], axis=1).groupby('user_id').sum().reset_index()
col = ['user_id', 'browse_all', 'buy_all', 'follow_all', 'comment_all', 'action_all']
u_feature_all.columns = col
u_feature_all['buy/browse_all'] = u_feature_all['buy_all'] / (u_feature_all['browse_all'] + 0.001) * 100
u_feature_all['buy/follow_all'] = u_feature_all['buy_all'] / (u_feature_all['follow_all'] + 0.001) * 100
u_feature_all['buy/comment_all'] = u_feature_all['buy_all'] / (u_feature_all['comment_all'] + 0.001) * 100
# 活跃天数
u_days = sub_all[['user_id', 'action_time']]
u_days = u_days.drop_duplicates()
u_days = u_days.groupby('user_id').count().reset_index()
u_days.rename(columns={'date': 'u_days_all'}, inplace=True)
u_feature_all = pd.merge(u_feature_all, u_days, on='user_id', how='left').fillna(0)
# 时间特征
u_days = sub_all[['user_id', 'action_time']]
u_start = u_days.groupby('user_id').min().reset_index()
u_start.rename(columns={'action_time': 'start'}, inplace=True)
u_end = u_days.groupby('user_id').max().reset_index()
u_end.rename(columns={'action_time': 'end'}, inplace=True)
u_duration = pd.merge(u_start, u_end, on='user_id')
u_duration['u_duration_all'] = u_duration['end'] - u_duration['start']
u_duration['u_duration_all'] = u_duration['u_duration_all'].map(lambda x: x.days * 24 + x.seconds / 3600)
u_duration = u_duration[['user_id', 'u_duration_all']]
u_feature_all = pd.merge(u_feature_all, u_duration, on='user_id', how='left').fillna(0)
# 行为/时间
u_feature_all['action_avg_all'] = u_feature_all['action_all'] / (u_feature_all['u_duration_all'] + 0.001)
u_feature_all['browse_avg_all'] = u_feature_all['browse_all'] / (u_feature_all['u_duration_all'] + 0.001)
u_feature_all['buy_avg_all'] = u_feature_all['buy_all'] / (u_feature_all['u_duration_all'] + 0.001)
u_feature_all['follow_avg_all'] = u_feature_all['follow_all'] / (u_feature_all['u_duration_all'] + 0.001)
u_feature_all['comment_avg_all'] = u_feature_all['comment_all'] / (u_feature_all['u_duration_all'] + 0.001)
# ========================================
# 用户7天行为特征
# ========================================
df = pd.get_dummies(sub_7['type'], prefix='type')
df['type_0'] = df.sum(axis=1)
df = pd.concat([sub_7[['user_id', 'cate', 'shop_id']], df], axis=1)
# 子集行为特征
u_feature_7 = df.drop(['cate', 'shop_id'], axis=1).groupby('user_id').sum().reset_index()
col = ['user_id', 'browse_7', 'buy_7', 'follow_7', 'comment_7', 'action_7']
u_feature_7.columns = col
# 时间特征
u_days = sub_7[['user_id', 'action_time']]
u_start = u_days.groupby('user_id').min().reset_index()
u_start.rename(columns={'action_time': 'start'}, inplace=True)
u_end = u_days.groupby('user_id').max().reset_index()
u_end.rename(columns={'action_time': 'end'}, inplace=True)
u_duration = pd.merge(u_start, u_end, on='user_id')
u_duration['u_duration_7'] = u_duration['end'] - u_duration['start']
u_duration['u_duration_7'] = u_duration['u_duration_7'].map(lambda x: x.days * 24 + x.seconds / 3600)
u_duration['u_stop_7'] = end_date - u_duration['end']
u_duration['u_stop_7'] = u_duration['u_stop_7'].map(lambda x: x.days * 24 + x.seconds / 3600)
u_duration = u_duration[['user_id', 'u_duration_7', 'u_stop_7']]
u_feature_7 = pd.merge(u_feature_7, u_duration, on='user_id', how='left').fillna(0)
# ========================================
# 用户1天行为特征
# ========================================
df = pd.get_dummies(sub_1['type'], prefix='type')
df['type_0'] = df.sum(axis=1)
df = pd.concat([sub_1[['user_id', 'cate', 'shop_id']], df], axis=1)
u_feature_1 = df.drop(['cate', 'shop_id'], axis=1).groupby('user_id').sum().reset_index()
col = ['user_id', 'browse_1', 'buy_1', 'follow_1', 'comment_1', 'action_1']
u_feature_1.columns = col
# ========================================
# 特征融合
# ========================================
actions = pd.merge(user[['user_id', 'user_lv_cd', 'reg_duration', 'reg_duration_cate']], u_feature_all,
on='user_id', how='left')
actions['lv/reg_day'] = actions['user_lv_cd'] / (actions['reg_duration'] + 0.001) * 100
actions['lv/reg_day_cate'] = actions['user_lv_cd'] / (actions['reg_duration_cate'] + 0.001)
actions = pd.merge(actions, u_feature_7, on='user_id', how='left')
actions['action_7D/all'] = actions['action_7'] / (actions['action_all'] + 0.001)
actions = pd.merge(actions, u_feature_1, on='user_id', how='left')
actions['action_diff1'] = actions['action_1'] - actions['action_avg_all']
actions['browse_diff1'] = actions['browse_1'] - actions['browse_avg_all']
actions['buy_diff1'] = actions['buy_1'] - actions['buy_avg_all']
actions['follow_diff1'] = actions['follow_1'] - actions['follow_avg_all']
actions['comment_diff1'] = actions['comment_1'] - actions['comment_avg_all']
actions['action_diff7'] = actions['action_7'] - actions['action_avg_all']
actions['browse_diff7'] = actions['browse_7'] - actions['browse_avg_all']
actions['buy_diff7'] = actions['buy_7'] - actions['buy_avg_all']
actions['follow_diff7'] = actions['follow_7'] - actions['follow_avg_all']
actions['comment_diff7'] = actions['comment_7'] - actions['comment_avg_all']
col = ['browse_7', 'buy_7', 'follow_7', 'comment_7', 'action_7','user_lv_cd', 'browse_1', 'buy_1',
'follow_1', 'comment_1', 'action_1']
actions = actions.drop(col, axis=1)
print(actions.columns)
print('=====> 完成!')
pickle.dump(actions, open(dump_path, 'wb'))
print(actions.shape)
print('user feat finished')
return actions
# 交叉特征
def get_cross_feat(start_date, end_date):
dump_path = './cache/cross_feat_F12_7_%s_%s.pkl' % (start_date, end_date)
if os.path.exists(dump_path):
actions = pd.read_pickle(dump_path)
else:
actions = get_actions_product(start_date, end_date)[['user_id', 'cate', 'shop_id']]
actions['cnt'] = 0
action1 = actions.groupby(['user_id', 'cate', 'shop_id'], as_index=False).count()
action2 = actions.groupby('user_id', as_index=False).count()
del action2['cate']
del action2['shop_id']
action2.columns = ['user_id', 'user_cnt']
action3 = actions.groupby('cate', as_index=False).count()
del action3['user_id']
del action3['shop_id']
action3.columns = ['cate', 'cate_cnt']
action4 = actions.groupby('shop_id', as_index=False).count()
del action4['user_id']
del action4['cate']
action4.columns = ['shop_id', 'shop_cnt']
actions = pd.merge(action1, action2, how='left', on='user_id')
actions = pd.merge(actions, action3, how='left', on='cate')
actions = pd.merge(actions, action4, how='left', on='shop_id')
actions['user_cnt'] = actions['cnt'] / actions['user_cnt']
actions['cate_cnt'] = actions['cnt'] / actions['cate_cnt']
actions['shop_cnt'] = actions['cnt'] / actions['shop_cnt']
del actions['cnt']
pickle.dump(actions, open(dump_path, 'wb'))
actions.columns = ['user_id', 'cate', 'shop_id'] + ['cross_feat_' + str(i) for i in range(1, actions.shape[1] - 2)]
print('cross feature finished')
return actions
# 加购特征
def get_last1day_cart_fearture(start_date, end_date, day):
'''
设计两个特征
第一个是在f12id上act5的总和
第二个是f12id act5行为总和 * (act_2==0)
'''
this_end_date = pd.to_datetime(end_date)
this_start_date = this_end_date - timedelta(days=day)
# date转化为str
this_end_date = str(this_end_date).split(' ')[0]
this_start_date = str(this_start_date).split(' ')[0]
x_action = get_actions_product_cart(this_start_date, this_end_date)
print('from:', x_action.action_time.min(), ' to:', x_action.action_time.max())
x_oh = pd.get_dummies(x_action.type, prefix='act').astype('int8')
x_action_oh = pd.concat([x_action[['user_id', 'cate', 'shop_id', 'sku_id', 'action_time']], x_oh], axis=1)
x_act5_stat = x_action_oh.groupby(['user_id', 'cate', 'shop_id'])[['act_5', 'act_2']].sum().add_prefix(
'lastday_sum_').reset_index()
x_act5_stat['cart_not_buy'] = x_act5_stat['lastday_sum_act_5'] * (x_act5_stat['lastday_sum_act_2'] == 0)
#x_act5_stat['cart_minus_buy'] = x_act5_stat['lastday_sum_act_5'] - x_act5_stat['lastday_sum_act_2']
return x_act5_stat
"""
########################
user_id feat
########################
"""
# 行为前的累积特征(访问天数)
def get_user_feat1(start_date, end_date):
dump_path = './cache/user_feat1_after_F12_7_%s_%s.pkl' % (start_date, end_date)
if os.path.exists(dump_path):
actions = pd.read_pickle(dump_path)
else:
# 购买前的浏览天数
def user_feat_2_1(start_date, end_date):
actions = get_actions_product(start_date, end_date)[['user_id', 'type', 'action_time']]
actions['action_time'] = actions['action_time'].map(lambda x: x.split(' ')[0])
visit = actions[actions['type'] == 1]
visit = visit.drop_duplicates(['user_id', 'action_time'], keep='first')
del visit['action_time']
del actions['action_time']
visit = visit.groupby('user_id', as_index=False).count()
visit.columns = ['user_id', 'visit']
buy = actions[actions['type'] == 2]
buy = buy.groupby('user_id', as_index=False).count()
buy.columns = ['user_id', 'buy']
actions = pd.merge(visit, buy, on='user_id', how='left')
actions['visit_day_before_buy'] = actions['visit'] / actions['buy']
del actions['buy']
del actions['visit']
return actions
# 用户关注前访问天数
def user_feat_3_1(start_date, end_date):
actions = get_actions_product(start_date, end_date)[['user_id', 'type', 'action_time']]
actions['action_time'] = actions['action_time'].map(lambda x: x.split(' ')[0])
visit = actions[actions['type'] == 1]
visit = visit.drop_duplicates(['user_id', 'action_time'], keep='first')
del visit['action_time']
del actions['action_time']
visit = visit.groupby('user_id', as_index=False).count()
visit.columns = ['user_id', 'visit']
guanzhu = actions[actions['type'] == 3]
guanzhu = guanzhu.groupby('user_id', as_index=False).count()
guanzhu.columns = ['user_id', 'guanzhu']
actions = pd.merge(visit, guanzhu, on='user_id', how='left')
actions['visit_day_before_guanzhu'] = actions['visit'] / actions['guanzhu']
del actions['guanzhu']
del actions['visit']
return actions
# 用户购买前关注天数
def user_feat_2_5(start_date, end_date):
actions = get_actions_product(start_date, end_date)[['user_id', 'type', 'action_time']]
actions['action_time'] = actions['action_time'].map(lambda x: x.split(' ')[0])
guanzhu = actions[actions['type'] == 3]
guanzhu = guanzhu.drop_duplicates(['user_id', 'action_time'], keep='first')
del guanzhu['action_time']
del actions['action_time']
guanzhu = guanzhu.groupby('user_id', as_index=False).count()
guanzhu.columns = ['user_id', 'guanzhu']
buy = actions[actions['type'] == 2]
buy = buy.groupby('user_id', as_index=False).count()
buy.columns = ['user_id', 'buy']
actions = pd.merge(guanzhu, buy, on='user_id', how='left')
actions['guanzhu_day_before_buy'] = actions['guanzhu'] / actions['buy']
del actions['buy']
del actions['guanzhu']
return actions
actions = pd.merge(user_feat_2_1(start_date, end_date), user_feat_3_1(start_date, end_date), on='user_id',
how='outer')
actions = pd.merge(actions, user_feat_2_5(start_date, end_date), on='user_id', how='outer')
pickle.dump(actions, open(dump_path, 'wb'))
actions.columns = ['user_id'] + ['u_feat1_' + str(i) for i in range(1, actions.shape[1])]
print('get_user_feat1 finished')
return actions
# 用户平均访问间隔 慢
def get_user_feat2(start_date, end_date):
dump_path = './cache/user_feat2_F12_7_%s_%s.pkl' % (start_date, end_date)
if os.path.exists(dump_path):
actions = pd.read_pickle(dump_path)
else:
df = get_actions_product(start_date, end_date)[['user_id', 'action_time']]
df['action_time'] = df['action_time'].map(lambda x: x.split(' ')[0])
df = df.drop_duplicates(['user_id', 'action_time'], keep='first')
df['action_time'] = df['action_time'].map(lambda x: datetime.strptime(x, '%Y-%m-%d'))
actions = df.groupby('user_id', as_index=False).agg(lambda x: x['action_time'].diff().mean())
actions['avg_visit'] = actions['action_time'].dt.days
del actions['action_time']
pickle.dump(actions, open(dump_path, 'wb'))
print('get_user_feat2 finished')
return actions
# 用户平均4种行为的访问间隔 慢
def get_user_feat3(start_date, end_date):
dump_path = './cache/user_feat3_six_F12_7_%s_%s.pkl' % (start_date, end_date)
if os.path.exists(dump_path):
actions = pd.read_pickle(dump_path)
else:
df = get_actions_product(start_date, end_date)[['user_id', 'action_time', 'type']]
df = df.dropna()
df['action_time'] = pd.to_datetime(df['action_time'])
df['action_time'] = (pd.to_datetime(start_date) - df['action_time']).dt.days
df['action_time'] = df['action_time'] * (-1)
df = df.drop_duplicates(['user_id', 'action_time', 'type'], keep='first')
actions = df.groupby(['user_id', 'type']).agg(lambda x: np.diff(x).mean())
actions = actions.unstack()
actions.columns = list(range(actions.shape[1]))
actions = actions.reset_index()
pickle.dump(actions, open(dump_path, 'wb'))
actions.columns = ['user_id'] + ['u_feat3_six_' + str(i) for i in range(1, actions.shape[1])]
print('get_user_feat3 finished')
return actions
# 用户的购买频率 慢
def get_user_feat4(start_date, end_date):
dump_path = './cache/user_feat4_six_F12_7_%s_%s.pkl' % (start_date, end_date)
if os.path.exists(dump_path):
actions = pd.read_pickle(dump_path)
else:
df = get_actions_product(start_date, end_date)[['user_id', 'type', 'action_time']]
df['action_time'] = pd.to_datetime(df['action_time'])
actions = df.groupby(['user_id', 'type'], as_index=False).count()
time_min = df.groupby(['user_id', 'type'], as_index=False).min()
time_max = df.groupby(['user_id', 'type'], as_index=False).max()
time_cha = pd.merge(time_max, time_min, on=['user_id', 'type'], how='left')
time_cha['action_time_x'] = pd.to_datetime(time_cha['action_time_x'])
time_cha['action_time_y'] = pd.to_datetime(time_cha['action_time_y'])
time_cha['cha_hour'] = 1 + (time_cha['action_time_x'] - time_cha['action_time_y']).dt.days * 24 + \
(time_cha['action_time_x'] - time_cha['action_time_y']).dt.seconds // 3600
del time_cha['action_time_x']
del time_cha['action_time_y']
actions = pd.merge(time_cha, actions, on=['user_id', 'type'], how="left")
actions = actions.groupby(['user_id', 'type']).sum()
actions['cnt/time'] = actions['action_time'] / actions["cha_hour"]
actions = actions.unstack()
actions.columns = list(range(actions.shape[1]))
actions = actions.reset_index()
actions = actions.fillna(0)
pickle.dump(actions, open(dump_path, 'wb'))
actions.columns = ['user_id'] + ['u_feat4_' + str(i) for i in range(1, actions.shape[1])]
print('get_user_feat4 finished')
return actions
# 行为0-1化
def user_top_k_0_1(start_date, end_date):
actions = get_actions_product(start_date, end_date)
actions = actions[['user_id', 'sku_id', 'type']]
df = pd.get_dummies(actions['type'], prefix='%s-%s-action' % (start_date, end_date))
actions = pd.concat([actions, df], axis=1) # type: pd.DataFrame
actions = actions.groupby('user_id', as_index=False).sum()
del actions['type']
del actions['sku_id']
user_id = actions['user_id']
del actions['user_id']
actions = actions.applymap(lambda x: 1 if x > 0 else 0)
actions = pd.concat([user_id, actions], axis=1)
return actions
# 用户最近K天行为0/1提取
def get_user_feat5(start_date, end_date):
dump_path = './cache/user_feat5_%s_%s.pkl' % (start_date, end_date)
if os.path.exists(dump_path):
actions = pd.read_pickle(dump_path)
else:
actions = None
for i in (1, 2, 3, 4, 5, 6, 7, 15, 30):
start_days = datetime.strptime(end_date, '%Y-%m-%d') - timedelta(days=i)
start_days = start_days.strftime('%Y-%m-%d')
if actions is None:
actions = user_top_k_0_1(start_days, end_date)
else:
actions = pd.merge(actions, user_top_k_0_1(start_days, end_date), how='outer', on='user_id')
pickle.dump(actions, open(dump_path, 'wb'))
actions.columns = ['user_id'] + ['u_feat5_' + str(i) for i in range(1, actions.shape[1])]
print('get_user_feat5 finished')
return actions
# 获取用户的重复购买率
def get_user_feat6(start_date, end_date):
dump_path = './cache/product_feat6_F12_7_%s_%s.pkl' % (start_date, end_date)
if os.path.exists(dump_path):
actions = pd.read_pickle(dump_path)
else:
df = get_actions_product(start_date, end_date)[['user_id', 'sku_id', 'type']]
df = df[df['type'] == 2] # 购买的行为
df = df.groupby(['user_id', 'sku_id'], as_index=False).count()
df.columns = ['user_id', 'sku_id', 'count1']
df['count1'] = df['count1'].map(lambda x: 1 if x > 1 else 0)
grouped = df.groupby(['user_id'], as_index=False)
actions = grouped.count()[['user_id', 'count1']]
actions.columns = ['user_id', 'count']
re_count = grouped.sum()[['user_id', 'count1']]
re_count.columns = ['user_id', 're_count']
actions = pd.merge(actions, re_count, on='user_id', how='left')
re_buy_rate = actions['re_count'] / actions['count']
actions = pd.concat([actions['user_id'], re_buy_rate], axis=1)
actions.columns = ['user_id', 're_buy_rate']
pickle.dump(actions, open(dump_path, 'wb'))
actions.columns = ['user_id'] + ['u_feat6_' + str(i) for i in range(1, actions.shape[1])]
print('get_user_feat6 finished')
return actions
# 获取最近一次行为的时间距离当前时间的差距
def get_user_feat7(start_date, end_date):
dump_path = './cache/user_feat7_F12_7_%s_%s.pkl' % (start_date, end_date)
if os.path.exists(dump_path):
actions = pd.read_pickle(dump_path)
else:
df = get_actions_product(start_date, end_date)[['user_id', 'action_time', 'type']]
df = df.drop_duplicates(['user_id', 'type'], keep='last')
df['action_time'] = pd.to_datetime(df['action_time'])
df['action_time'] = (pd.to_datetime(end_date) - df['action_time']).dt.days
df['action_time'] = df['action_time'] + 1
actions = df.groupby(['user_id', 'type']).sum()
actions = actions.unstack()
actions.columns = list(range(actions.shape[1]))
actions = actions.reset_index()
actions = actions.fillna(30)
pickle.dump(actions, open(dump_path, 'wb'))
actions.columns = ['user_id'] + ['u_feat7_' + str(i) for i in range(1, actions.shape[1])]
print('get_user_feat7 finished')
return actions
# 用户购买/加入购物车/关注前访问次数
def get_user_feat8(start_date, end_date):
dump_path = './cache/user_feat8_F12_7_%s_%s.pkl' % (start_date, end_date)
if os.path.exists(dump_path):
actions = pd.read_pickle(dump_path)
else:
# 用户购买前访问次数
def user_feat_8_1(start_date, end_date):
actions = get_actions_product(start_date, end_date)[['user_id', 'type']]
visit = actions[actions['type'] == 1]
visit = visit.groupby('user_id', as_index=False).count()
visit.columns = ['user_id', 'visit']
buy = actions[actions['type'] == 2]
buy = buy.groupby('user_id', as_index=False).count()
buy.columns = ['user_id', 'buy']
actions = pd.merge(visit, buy, on='user_id', how='left')
actions['visit_num_before_buy'] = actions['visit'] / actions['buy']
del actions['buy']
del actions['visit']
return actions
# 用户关注前访问次数
def user_feat_8_2(start_date, end_date):
actions = get_actions_product(start_date, end_date)[['user_id', 'type']]
visit = actions[actions['type'] == 1]
visit = visit.groupby('user_id', as_index=False).count()
visit.columns = ['user_id', 'visit']
guanzhu = actions[actions['type'] == 3]
guanzhu = guanzhu.groupby('user_id', as_index=False).count()
guanzhu.columns = ['user_id', 'guanzhu']
actions = pd.merge(visit, guanzhu, on='user_id', how='left')
actions['visit_num_before_guanzhu'] = actions['visit'] / actions['guanzhu']
del actions['guanzhu']
del actions['visit']
return actions
# 用户购买前关注次数
def user_feat_8_3(start_date, end_date):
actions = get_actions_product(start_date, end_date)[['user_id', 'type']]
guanzhu = actions[actions['type'] == 3]
guanzhu = guanzhu.groupby('user_id', as_index=False).count()
guanzhu.columns = ['user_id', 'guanzhu']
buy = actions[actions['type'] == 2]
buy = buy.groupby('user_id', as_index=False).count()