-
Notifications
You must be signed in to change notification settings - Fork 20
/
prepare.py
258 lines (210 loc) · 10.2 KB
/
prepare.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
import sys
import os
import pandas as pd
import subprocess
import argparse
import pdb
import pickle
from eis import setup_environment
"""
Code to take top performing recent models and
put them in the evaluation webapp for further
examination.
Examples:
--------
python prepare.py '2016-08-03' 'auc'
python prepare.py '2016-08-03' 'recall@' -p '0.01'
python prepare.py '2016-08-03' 'precision@' -p '10.0' -n 10
python prepare.py '2016-08-03' 'precision@' -p '10.0' -n 10 -d 'example_directory/'
"""
engine = setup_environment.get_database()
try:
con = engine.raw_connection()
con.cursor().execute("SET SCHEMA '{}'".format('models'))
except:
pass
def get_metric_best_models(timestamp, metric, parameter=None, number=25):
"""
--------------------------------------------------------
Get the EVALUATION METRIC VALUE of the best models
by the specified timestamp and given metric
--------------------------------------------------------
ARGUMENTS:
timestamp: models run on or after given timestamp
example: '2016-08-03'
metric: metric to be optimized
example: 'precision@'
parameter: parameter value or threshold if any
default=None
example: '10.0'
number: maximum number of desired results
default = 25
--------------------------------------------------------
"""
if parameter is None:
query = (" SELECT value FROM results.evaluations JOIN results.models \
ON evaluations.model_id=models.model_id \
WHERE run_time >= '{}' \
AND value is not null \
AND metric = '{}' \
ORDER BY value DESC LIMIT {} ; ").format(timestamp, metric, number)
elif parameter is not None:
query = (" SELECT value FROM results.evaluations JOIN results.models \
ON evaluations.model_id=models.model_id \
WHERE run_time >= '{}' \
AND value is not null \
AND metric = '{}' \
AND parameter = '{}' \
ORDER BY value DESC LIMIT {} ; ").format(timestamp, metric, parameter, number)
df_models = pd.read_sql(query, con=con)
output = df_models["value"].apply(lambda x: str(x)).values
statement = "Resulting metric for models with best {} run on or after {}: \n".format(metric, timestamp)
print (statement, output)
return output
def get_best_models_id(timestamp, metric, parameter=None, number=25):
"""
--------------------------------------------------------
Get the MODEL ID of the best models
by the specified timestamp and given metric
--------------------------------------------------------
ARGUMENTS:
timestamp: models run on or after given timestamp
example: '2016-08-03'
metric: metric to be optimized
example: 'precision@'
parameter: parameter value or threshold if any
default=None
example: '10.0'
number: maximum number of desired results
default = 25
--------------------------------------------------------
"""
if parameter is None:
query = (" SELECT run_time FROM results.evaluations JOIN results.models \
ON evaluations.model_id=models.model_id \
WHERE run_time >= '{}' \
AND value is not null \
AND metric = '{}' \
ORDER BY value DESC LIMIT {} ; ").format(timestamp, metric, number)
elif parameter is not None:
query = (" SELECT run_time FROM results.evaluations JOIN results.models \
ON evaluations.model_id=models.model_id \
WHERE run_time >= '{}' \
AND value is not null \
AND metric = '{}' \
AND parameter = '{}' \
ORDER BY value DESC LIMIT {} ; ").format(timestamp, metric, parameter, number)
df_models = pd.read_sql(query, con=con)
output = df_models['run_time'].apply(lambda x: str(x).replace(' ', 'T')).values
print(output)
return output
def get_best_models(timestamp, metric, parameter=None, number=25):
"""
--------------------------------------------------------
Get the REPORT of the best models
by the specified timestamp and given metric
RETURNS RUN TIME, MODEL TYPE, METRIC, and VALUE
OR
RUN TIME, MODEL TYPE, METRIC, PARAMETER, and VALUE
--------------------------------------------------------
ARGUMENTS:
timestamp: models run on or after given timestamp
example: '2016-08-03'
metric: metric to be optimized
example: 'precision@'
parameter: parameter value or threshold if any
default=None
example: '10.0'
number: maximum number of desired results
default = 25
--------------------------------------------------------
"""
if parameter is None:
query = (" SELECT run_time, model_type, metric, value FROM results.evaluations JOIN results.models \
ON evaluations.model_id=models.model_id \
WHERE run_time >= '{}' \
AND value is not null \
AND metric = '{}' \
ORDER BY value DESC LIMIT {} ; ").format(timestamp, metric, number)
elif parameter is not None:
query = (" SELECT run_time, model_type, metric, parameter, value FROM results.evaluations JOIN results.models \
ON evaluations.model_id=models.model_id \
WHERE run_time >= '{}' \
AND value is not null \
AND metric = '{}' \
AND parameter = '{}' \
ORDER BY value DESC LIMIT {} ; ").format(timestamp, metric, parameter, number)
df_models = pd.read_sql(query, con=con)
output = df_models
statement = "Resulting top models with best {} run on or after {}: \n".format(metric, timestamp)
print (statement, output)
return output
def get_pickle_best_models(timestamp, metric, parameter=None, number=25, directory="results/"):
"""
--------------------------------------------------------
Get the PICKLE FILE of the best models
by the specified timestamp and given metric
RETURNS the PICKLE FILE to a DIRECTORY
--------------------------------------------------------
ARGUMENTS:
timestamp: models run on or after given timestamp
example: '2016-08-03'
metric: metric to be optimized
example: 'precision@'
parameter: parameter value or threshold if any
default=None
example: '10.0'
number: maximum number of desired results
default = 25
--------------------------------------------------------
"""
if parameter is None:
query = ("SELECT pickle_blob, run_time FROM \
(SELECT evaluations.model_id, run_time \
FROM results.evaluations JOIN results.models \
ON evaluations.model_id=models.model_id \
WHERE run_time >= '{}' \
AND value is not null \
AND metric = '{}' \
ORDER BY value DESC LIMIT {}) \
AS top_models \
INNER JOIN results.data \
ON top_models.model_id=data.model_id ; " ).format(timestamp, metric, number)
elif parameter is not None:
query = ("SELECT pickle_blob, run_time FROM \
(SELECT evaluations.model_id, run_time \
FROM results.evaluations JOIN results.models \
ON evaluations.model_id=models.model_id \
WHERE run_time >= '{}' \
AND value is not null \
AND metric = '{}' \
AND parameter = '{}' \
ORDER BY value DESC LIMIT {}) \
AS top_models \
INNER JOIN results.data \
ON top_models.model_id=data.model_id ; " ).format(timestamp, metric, parameter, number)
df_models = pd.read_sql(query, con=con)
N = len(df_models['pickle_blob'])
for file_number in range(0, N):
pickle_file = pickle.loads(df_models['pickle_blob'].iloc[file_number])
file_name = df_models['run_time'].apply(lambda x: str(x).replace(' ', 'T')).iloc[file_number]
if parameter is None:
full_file_name = "police_eis_results_"+"top_"+metric+"any"+"_"+file_name+".pkl"
elif parameter is not None:
full_file_name = "police_eis_results_"+"top_"+metric+parameter+"_"+file_name+".pkl"
file_path = directory+full_file_name
pickle.dump(pickle_file, open( file_path, "wb" ) )
return None
if __name__=='__main__':
parser = argparse.ArgumentParser()
parser.add_argument("timestamp", type=str, help="show models more recent than a given timestamp")
parser.add_argument("metric", type=str, help="specify a desired metric to optimize")
parser.add_argument("-p", "--parameter", default=None, type=str, help="specify a desired parameter or threshold for your metric, default=None")
parser.add_argument("-n", "--number", default=25, type=int, help="maximum number of results to return, default=25")
parser.add_argument("-d", "--directory", default="results/", type=str, help="file directory for pickle files, default='results/'")
args = parser.parse_args()
print("[*] Updating model list...")
models = get_best_models(args.timestamp, args.metric, args.parameter, args.number)
print("[*] Dumping requested pickle files to results...")
pickles = get_pickle_best_models(args.timestamp, args.metric, args.parameter, args.number, args.directory)
print("[*] Done!")