-
Notifications
You must be signed in to change notification settings - Fork 1
/
createFeature6.py
150 lines (95 loc) · 2.5 KB
/
createFeature6.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
# coding:utf-8
'''
生成用户地理位置的一级特征
'''
import csv, time,sys, util,com
import numpy as np
# 特征生成文件6, user geo feature
user_geo = dict()
geo_ids = set()
def IncDict(d, key):
if key in d:
d[key] = d[key] + 1
else:
d[key] = 1
def GetDict(d, key):
if key in d:
return d[key]
else:
return 0
def DiffTime(t1, t2):
t1 = time.mktime(time.strptime(t1,'%Y-%m-%d %H'))
t2 = time.mktime(time.strptime(t2,'%Y-%m-%d %H'))
return t1 - t2
def parse_time(t):
return time.mktime(time.strptime(t,'%Y-%m-%d %H'))
def AddLastTime(time_dict, utid, t):
if utid not in time_dict:
time_dict[utid] = t
return
if DiffTime(time_dict[utid], t)<0:
time_dict[utid] = t
return
def JugeDoingNobuy(d,last_doing_set, last_doing_time, utid):
if utid not in last_doing_set: # no doing
d[utid] = 0
return
if utid not in user_item_buy: # not buy
d[utid] = 1
return
do_t = last_doing_time[utid]
buy_t = user_item_last_buy_time[utid]
diff_time = DiffTime(do_t, buy_t)
if diff_time > 0:
d[utid] = 0
return
d[utid] = 1
# print utid
def GenFeature(finput='user_action_train.csv', foutput = 'feature.csv', lastday = '2014-12-18'):
# 细化行为特征
user_items = set() # 其实是用户物品对
item_cat = dict()
with open(finput, 'rb') as f:
reader = csv.reader(f, delimiter=',')
header = reader.next()
print header
i = 0
for row in reader:
if row[5] > '%s 23' % lastday : # 未来的数据
continue
uid = row[0]
tid = row[1]
cid = row[4]
t = row[5]
utid = '%s_%s' % (uid, tid)
ucid = '%s_%s' % (uid, cid)
user_items.add('%s_%s' % (uid,tid))
item_cat[tid] = cid
geoid = row[3][:1]
if geoid is not '':
geo_ids.add(geoid)
if geoid not in user_geo:
user_geo[uid] = dict()
user_geo[uid][geoid] = 1
i = i + 1
if i%100000==0:
print 'processed %d scores!' % i
# user feature
fd = open(foutput,'wb')
fw = csv.writer(fd, delimiter=',')
fw.writerow(['user_id', 'item_id'] + ['user_geo_%s' % i for i in geo_ids])
for key in user_items:
uid, tid = key.split('_')
cid = item_cat[tid]
utid = '%s_%s' % (uid, tid)
ucid = '%s_%s' % (uid, cid)
if uid not in user_geo:
geodata = [0 for g in geo_ids]
else:
geodata = [GetDict(user_geo[uid], g) for g in geo_ids]
data = [uid, tid,
] + geodata
fw.writerow(data)
fd.close()
if __name__ == '__main__':
com.CreateFeature(__file__, sys.argv[1])