-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathdataset.py
216 lines (159 loc) · 6.29 KB
/
dataset.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
#! /usr/local/bin/python3
# -*- utf-8 -*-
"""
Generate datasets for training and validating, and load dataset of testing.
"""
from datetime import datetime, timedelta
import logging
import sys
import os
import numpy as np
import pandas as pd
import features
import Path
import IO
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG,
format='%(asctime)s %(name)s %(levelname)s\t%(message)s')
logger = logging.getLogger('dataset')
def load_test():
"""
Load dataset for testing.
Returns
-------
X: numpy ndarray, shape: (num_of_enrollments, num_of_features)
Rows of features.
"""
logger.debug('loading test set')
pkl_path = Path.of_cache('test_X.pkl')
X = IO.fetch_cache(pkl_path)
if X is None:
base_date = datetime(2014, 8, 1, 22, 0, 47)
X = IO.load_enrollment_test()
for f in features.METHODS:
X_ = f.extract(base_date)
if X_ is None:
print('%s returns None' % repr(f.__name__))
continue
if np.any(pd.isnull(X_)):
raise RuntimeError('%s can generate NA(s)' % repr(f.__name__))
X = pd.merge(X, X_, how='left', on='enrollment_id')
if np.any(pd.isnull(X)):
raise RuntimeError('%s does not generate features of all '
'enrollments' % repr(f.__name__))
del X['enrollment_id']
del X['username']
del X['course_id']
X = X.as_matrix()
IO.cache(X, pkl_path)
logger.debug('test set loaded')
return X
def __enroll_ids_with_log__(log, enroll_ids, base_date):
log_eids = set(log[log['time'] <= base_date]['enrollment_id'].unique())
return np.array([eid for eid in enroll_ids if eid in log_eids])
def __load_dataset__(log, enroll_ids, base_date):
"""get all instances in this time window"""
X = IO.load_enrollments().set_index('enrollment_id')\
.ix[enroll_ids].reset_index()
for f in features.METHODS:
X_ = f.extract(base_date)
if X_ is None:
print('%s returns None' % repr(f.__name__))
continue
if np.any(pd.isnull(X_)):
raise RuntimeError('%s can generate NA(s)' % repr(f.__name__))
X = pd.merge(X, X_, how='left', on='enrollment_id')
if np.any(pd.isnull(X)):
raise RuntimeError('%s does not generate features of all '
'enrollments' % repr(f.__name__))
active_eids = set(log[(log['time'] > base_date) &
(log['time'] <= base_date + timedelta(days=10))]
['enrollment_id'])
y = [int(eid not in active_eids) for eid in enroll_ids]
del X['enrollment_id']
del X['username']
del X['course_id']
return X.as_matrix(), np.array(y, dtype=np.int)
def load_train(depth=0):
"""
Load dataset for training and validating.
*NOTE* If you need a validating set, you SHOULD split from training set
by yourself.
Args
----
depth: int, 0 by default
Maximum moves of time window. 0 means no need to move time window.
Returns
-------
X: numpy ndarray, shape: (num_of_enrollments, num_of_features)
Rows of features. It is the features of all time if cache_only is True.
y: numpy ndarray, shape: (num_of_enrollments,)
Vector of labels. It is the labels of all time if cache_only is True.
"""
logger.debug('loading train set of depth %d', depth)
enroll_set = IO.load_enrollment_train()
log_all = IO.load_logs()
base_date = datetime(2014, 8, 1, 22, 0, 47)
logger.debug('loading features before %s', base_date)
enroll_ids = __enroll_ids_with_log__(log_all, enroll_set['enrollment_id'],
base_date)
pkl_X_path = Path.of_cache('train_X.%s.pkl' % base_date)
pkl_y_path = Path.of_cache('train_y.%s.pkl' % base_date)
X = IO.fetch_cache(pkl_X_path)
y = IO.fetch_cache(pkl_y_path)
if X is None or y is None:
logger.debug('cache missed, calculating ...')
X, _ = __load_dataset__(log_all, enroll_ids, base_date)
y_with_id = IO.load_train_y()
y = np.array(pd.merge(enroll_set, y_with_id, how='left',
on='enrollment_id')['y'])
if np.any(np.isnan(y)):
logger.fatal('something wrong with y')
raise RuntimeError('something wrong with y')
IO.cache(X, pkl_X_path)
IO.cache(y, pkl_y_path)
base_date = datetime(2014, 7, 22, 22, 0, 47)
Dw = timedelta(days=7)
enroll_ids = __enroll_ids_with_log__(log_all, enroll_ids, base_date)
for _ in range(depth):
if enroll_ids.size <= 0:
break
logger.debug('loading features before %s', base_date)
# get instances and labels
pkl_X_path = Path.of_cache('train_X.%s.pkl' % base_date)
pkl_y_path = Path.of_cache('train_y.%s.pkl' % base_date)
X_temp = IO.fetch_cache(pkl_X_path)
y_temp = IO.fetch_cache(pkl_y_path)
if X_temp is None or y_temp is None:
logger.debug('cache missed, calculating ...')
X_temp, y_temp = __load_dataset__(log_all, enroll_ids, base_date)
IO.cache(X_temp, pkl_X_path)
IO.cache(y_temp, pkl_y_path)
# update instances and labels
X = np.r_[X, X_temp]
y = np.append(y, y_temp)
# update base_date and enroll_ids
base_date -= Dw
enroll_ids = __enroll_ids_with_log__(log_all, enroll_ids, base_date)
logger.debug('train set loaded')
if np.any(np.isinf(X)):
logger.debug('train set has INF')
return X, y
if __name__ == '__main__':
import glob
if sys.argv[1] == 'clean':
cached_files = glob.glob(Path.of_cache('train_X*.pkl'))
cached_files += glob.glob(Path.of_cache('train_y*.pkl'))
cached_files += glob.glob(Path.of_cache('test_X.pkl'))
for f in cached_files:
print('Removing %s ...' % f)
os.remove(f)
elif sys.argv[1] == 'gen':
d = 1
if len(sys.argv) > 2:
d = int(sys.argv[2])
print('depth: %d' % d)
X, y = load_train(depth=d)
print('X.shape: %d x %d' % X.shape)
print('y.shape: %d' % y.shape)
X_test = load_test()
print('X_test.shape: %d x %d' % X_test.shape)