-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdata_iter.py
383 lines (313 loc) · 12.6 KB
/
data_iter.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
import pandas as pd
import happybase
import os, pickle
import logging
from abc import ABCMeta, abstractmethod
from deprecated import deprecated
from queue import Queue
PATH = os.path.dirname(os.path.abspath(__file__))
INDEX_PATH = os.path.join(PATH, "index.pkl")
class DataGenerator(object, metaclass=ABCMeta):
@abstractmethod
def get_data(self, batch_size=128):
pass
@abstractmethod
def __enter__(self):
return self
@abstractmethod
def __exit__(self, exc_type, exc_val, exc_tb):
pass
class TrainDataIter(object):
def __init__(self, file_path: str, batch_size: int = 128, use_others=False):
"""
:param file_path:
:param batch_size:
:param use_others: if True, remember to rewrite __next__ method!
"""
self.data = pd.read_csv(file_path)
self.batch_size = batch_size
self.use_others = use_others
def __iter__(self):
self._index = 0
return self
def __next__(self):
if self._index < len(self.data):
self._index += self.batch_size
feature, target = [], []
for row in self.data[self._index - self.batch_size:self._index].itertuples(index=False):
tmp = []
tmp.append(getattr(row, "user_id"))
tmp.append(getattr(row, "ad_id"))
tmp.append(getattr(row, "action_code"))
tmp.append([int(i) for i in getattr(row, "ad_his").split(",")])
tmp.append([int(i) for i in getattr(row, "code_his").split(",")])
tmp.append(getattr(row, "seq_length"))
if self.use_others:
tmp.append(getattr(row, "province"))
tmp.append(getattr(row, "city"))
tmp.append(getattr(row, "grade"))
tmp.append(getattr(row, "chinese_ability_overall"))
tmp.append(getattr(row, "english_ability_overall"))
tmp.append(getattr(row, "math_ability_overall"))
tmp.append(getattr(row, "pay_test"))
tmp.append(getattr(row, "seatwork_active_degree"))
tmp.append(getattr(row, "user_freshness"))
feature.append(tmp)
if getattr(row, "event") == 0:
target.append([1, 0])
else:
target.append([0, 1])
return feature, target
else:
raise StopIteration()
FIELD = ["mobile_os",
"province_id", "grade_id", "school_id", "city_id", "county_id",
"purchase_power",
"math_ability", "english_ability", "chinese_ability",
"activity_degree", "app_freshness", "ad_id", "user_id",
"log_hourtime",
##########CLICK##########
"is_click",
"label_1","label_2","label_3","label_4","label_5","label_6","label_7",
"rencent_behavior"
]
@deprecated(version="1.0.0", reason="This cls is deprecated, please use "
"HbaseDataIter to instead!")
class DataIter(DataGenerator):
def __init__(self, hbase: str, table: str, filter: str, request: list = None, batch_size: int = 128,
field=FIELD):
self.connection = happybase.Connection(hbase, autoconnect=False, timeout=10 * 1000,
# transport="framed",
# protocol="compact"
)
self.table = happybase.Table(table, self.connection)
self.filter = filter
self.request = request or []
assert isinstance(self.request, list), "request must be list!"
self.field = field.copy()
def get_data(self, batch_size=128):
index = 0
if os.path.exists(INDEX_PATH):
with open(INDEX_PATH, "rb") as f:
index = pickle.load(f)
for req in self.request[index:]:
data = []
self.connection.open()
print("consuming %s's data!" % (req))
if os.path.exists(INDEX_PATH):
os.remove(INDEX_PATH)
with open(INDEX_PATH, "wb") as f:
pickle.dump(self.request.index(req), f)
try:
for key, item in self.table.scan(filter=self.filter.format(req), batch_size=1, ):
tmp = {}
tag = False
try:
for k, v in item.items():
k = k.decode("utf8").split(":")[1]
v = v.decode("utf8")
if k in self.field:
if len(v) == 0:
tag = True
break
tmp[k] = v
if tag:
continue
except:
continue
ad_id = tmp["ad_id"]
try:
ad_id = int(ad_id)
except:
print("parse error")
continue
if ad_id < 10000:
continue
data.append(tmp)
if len(data) == batch_size:
yield data
data = []
except Exception as e:
logging.info(e)
finally:
if len(data) > 0:
yield data
if os.path.exists(INDEX_PATH):
os.remove(INDEX_PATH)
return
def __enter__(self):
self.connection.open()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.connection.close()
return True
@deprecated(version="1.1.0", reason="This cls is deprecated, please use "
"HbaseDataIterUpdate to instead!")
class HbaseDataIter(DataGenerator):
def __init__(self, host: str, table: str, filter: str, request: list = None,
field=FIELD):
self.connection = happybase.Connection(host, autoconnect=False, timeout=30 * 1000)
self.table = happybase.Table(table, self.connection)
self.filter = filter
self.request = request or []
assert isinstance(self.request, list), "request must be list!"
self.field = field.copy()
def get_data(self, batch_size=128, model_num=0):
try:
for req in self.request[:]:
data = []
self.connection.open()
print("consuming %s's data!" % (req))
try:
for key, item in self.table.scan(filter=self.filter.format(req), batch_size=1, ):
tmp = {}
tag = False
try:
for k, v in item.items():
k = k.decode("utf8").split(":")[1]
v = v.decode("utf8")
if k in self.field:
if len(v) == 0:
tag = True
break
tmp[k] = v
if tag:
continue
if 0 != model_num:
if int(tmp["user_id"]) % 4 != model_num - 1:
continue
except Exception as e:
print("parse data error: ", e)
continue
ad_id = tmp["ad_id"]
try:
ad_id = int(ad_id)
except:
print("parse int error: ", "can't int")
continue
if ad_id < 10000:
continue
data.append(tmp)
if len(data) == batch_size:
yield data
data = []
except Exception as e:
print("hbase conn error: ", e)
finally:
if len(data) > 0:
yield data
except:
## this only omit the GeneratorExit Error
## we can do something here,like release resources ... ,but no need!!!
pass
finally:
return
def __enter__(self):
self.connection.open()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.connection.close()
return True
class HbaseDataIterUpdate(DataGenerator):
def __init__(self, host: str, table: str, filter: str, request: list = None,
field=FIELD):
self.connection = happybase.Connection(host, autoconnect=False, timeout=30 * 1000)
self.table = happybase.Table(table, self.connection)
self.filter = filter
self.request = request or []
assert isinstance(self.request, list), "request must be list!"
self.field = field.copy()
def get_data(self, batch_size=128, model_num=0):
def __inner(scanner):
try:
yield from scanner
except Exception as e:
#inner hbase error: TTransportException(message='TSocket read 0 bytes', type=4)
print("inner hbase error: ", e)
return
try:
for req in self.request[:]:
data = []
self.connection.open()
print("consuming %s's data!" % (req))
for key, item in __inner(self.table.scan(filter=self.filter.format(req), batch_size=1, )):
tmp = {}
tag = False
try:
for k, v in item.items():
k = k.decode("utf8").split(":")[1]
v = v.decode("utf8")
if k in self.field:
if len(v) == 0:
tag = True
break
tmp[k] = v
if tag:
continue
if 0 != model_num:
if int(tmp["user_id"]) % 4 != model_num - 1:
continue
except Exception as e:
print("parse data error: ", e)
continue
ad_id = tmp["ad_id"]
try:
ad_id = int(ad_id)
except:
print("parse int error: ", "can't int")
continue
if ad_id < 10000:
continue
data.append(tmp)
if len(data) == batch_size:
yield data
data = []
if len(data) > 0:
yield data
except:
## this only omit the GeneratorExit Error
## we can do something here,like release resources ... ,but no need!!!
pass
finally:
return
def __enter__(self):
self.connection.open()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.connection.close()
return True
if __name__ == "__main__":
"""To Test"""
# t = TrainDataIter("train_filter.csv", batch_size=2000)
# for i in t:
# pass
#
# for i in t:
# print(i)
# filter_str = """RowFilter (=, 'substring:{}')"""
# request = ["2019-04-%02d" % (i) for i in range(12, 16)]
# with DataIter('10.9.135.235', b'midas_ctr_pro', filter_str, request, ) as d:
# for i in d.get_data(batch_size=128):
# pass
mime = "10.9.75.202"
other = "10.9.135.235"
conn = happybase.Connection(
host=mime,
# host="localhost",
# timeout=100,
)
conn.open()
table = happybase.Table(b"midas_offline", conn)
filter_str = """RowFilter (=, 'substring:{}')"""
# scan = table.scan(filter=filter_str.format("2019-06-12"),
# batch_size=1)
cnt = 1
# for key, value in scan:
# print(cnt, key, value, )
# cnt += 1
# if cnt >= 10:
# break
conn.close()
with HbaseDataIter("10.9.75.202", b'midas_offline_v1', filter_str, ["2019-07-17"], ) as d:
for i in d.get_data():
print(len(i), type(i))