comparison train_test_eval.py @ 26:685046e0381a draft

planemo upload for repository https://github.com/bgruening/galaxytools/tree/master/tools/sklearn commit 60f0fbc0eafd7c11bc60fb6c77f2937782efd8a9-dirty
author bgruening
date Fri, 09 Aug 2019 07:16:21 -0400
parents
children 4952fe39b61d
comparison
equal deleted inserted replaced
25:9ac0b78c6b6d 26:685046e0381a
1 import argparse
2 import joblib
3 import json
4 import numpy as np
5 import pandas as pd
6 import pickle
7 import warnings
8 from itertools import chain
9 from scipy.io import mmread
10 from sklearn.base import clone
11 from sklearn import (cluster, compose, decomposition, ensemble,
12 feature_extraction, feature_selection,
13 gaussian_process, kernel_approximation, metrics,
14 model_selection, naive_bayes, neighbors,
15 pipeline, preprocessing, svm, linear_model,
16 tree, discriminant_analysis)
17 from sklearn.exceptions import FitFailedWarning
18 from sklearn.metrics.scorer import _check_multimetric_scoring
19 from sklearn.model_selection._validation import _score, cross_validate
20 from sklearn.model_selection import _search, _validation
21 from sklearn.utils import indexable, safe_indexing
22
23 from galaxy_ml.model_validations import train_test_split
24 from galaxy_ml.utils import (SafeEval, get_scoring, load_model,
25 read_columns, try_get_attr, get_module)
26
27
28 _fit_and_score = try_get_attr('galaxy_ml.model_validations', '_fit_and_score')
29 setattr(_search, '_fit_and_score', _fit_and_score)
30 setattr(_validation, '_fit_and_score', _fit_and_score)
31
32 N_JOBS = int(__import__('os').environ.get('GALAXY_SLOTS', 1))
33 CACHE_DIR = './cached'
34 NON_SEARCHABLE = ('n_jobs', 'pre_dispatch', 'memory', '_path',
35 'nthread', 'callbacks')
36 ALLOWED_CALLBACKS = ('EarlyStopping', 'TerminateOnNaN', 'ReduceLROnPlateau',
37 'CSVLogger', 'None')
38
39
40 def _eval_swap_params(params_builder):
41 swap_params = {}
42
43 for p in params_builder['param_set']:
44 swap_value = p['sp_value'].strip()
45 if swap_value == '':
46 continue
47
48 param_name = p['sp_name']
49 if param_name.lower().endswith(NON_SEARCHABLE):
50 warnings.warn("Warning: `%s` is not eligible for search and was "
51 "omitted!" % param_name)
52 continue
53
54 if not swap_value.startswith(':'):
55 safe_eval = SafeEval(load_scipy=True, load_numpy=True)
56 ev = safe_eval(swap_value)
57 else:
58 # Have `:` before search list, asks for estimator evaluatio
59 safe_eval_es = SafeEval(load_estimators=True)
60 swap_value = swap_value[1:].strip()
61 # TODO maybe add regular express check
62 ev = safe_eval_es(swap_value)
63
64 swap_params[param_name] = ev
65
66 return swap_params
67
68
69 def train_test_split_none(*arrays, **kwargs):
70 """extend train_test_split to take None arrays
71 and support split by group names.
72 """
73 nones = []
74 new_arrays = []
75 for idx, arr in enumerate(arrays):
76 if arr is None:
77 nones.append(idx)
78 else:
79 new_arrays.append(arr)
80
81 if kwargs['shuffle'] == 'None':
82 kwargs['shuffle'] = None
83
84 group_names = kwargs.pop('group_names', None)
85
86 if group_names is not None and group_names.strip():
87 group_names = [name.strip() for name in
88 group_names.split(',')]
89 new_arrays = indexable(*new_arrays)
90 groups = kwargs['labels']
91 n_samples = new_arrays[0].shape[0]
92 index_arr = np.arange(n_samples)
93 test = index_arr[np.isin(groups, group_names)]
94 train = index_arr[~np.isin(groups, group_names)]
95 rval = list(chain.from_iterable(
96 (safe_indexing(a, train),
97 safe_indexing(a, test)) for a in new_arrays))
98 else:
99 rval = train_test_split(*new_arrays, **kwargs)
100
101 for pos in nones:
102 rval[pos * 2: 2] = [None, None]
103
104 return rval
105
106
107 def main(inputs, infile_estimator, infile1, infile2,
108 outfile_result, outfile_object=None,
109 outfile_weights=None, groups=None,
110 ref_seq=None, intervals=None, targets=None,
111 fasta_path=None):
112 """
113 Parameter
114 ---------
115 inputs : str
116 File path to galaxy tool parameter
117
118 infile_estimator : str
119 File path to estimator
120
121 infile1 : str
122 File path to dataset containing features
123
124 infile2 : str
125 File path to dataset containing target values
126
127 outfile_result : str
128 File path to save the results, either cv_results or test result
129
130 outfile_object : str, optional
131 File path to save searchCV object
132
133 outfile_weights : str, optional
134 File path to save deep learning model weights
135
136 groups : str
137 File path to dataset containing groups labels
138
139 ref_seq : str
140 File path to dataset containing genome sequence file
141
142 intervals : str
143 File path to dataset containing interval file
144
145 targets : str
146 File path to dataset compressed target bed file
147
148 fasta_path : str
149 File path to dataset containing fasta file
150 """
151 warnings.simplefilter('ignore')
152
153 with open(inputs, 'r') as param_handler:
154 params = json.load(param_handler)
155
156 # load estimator
157 with open(infile_estimator, 'rb') as estimator_handler:
158 estimator = load_model(estimator_handler)
159
160 # swap hyperparameter
161 swapping = params['experiment_schemes']['hyperparams_swapping']
162 swap_params = _eval_swap_params(swapping)
163 estimator.set_params(**swap_params)
164
165 estimator_params = estimator.get_params()
166
167 # store read dataframe object
168 loaded_df = {}
169
170 input_type = params['input_options']['selected_input']
171 # tabular input
172 if input_type == 'tabular':
173 header = 'infer' if params['input_options']['header1'] else None
174 column_option = (params['input_options']['column_selector_options_1']
175 ['selected_column_selector_option'])
176 if column_option in ['by_index_number', 'all_but_by_index_number',
177 'by_header_name', 'all_but_by_header_name']:
178 c = params['input_options']['column_selector_options_1']['col1']
179 else:
180 c = None
181
182 df_key = infile1 + repr(header)
183 df = pd.read_csv(infile1, sep='\t', header=header,
184 parse_dates=True)
185 loaded_df[df_key] = df
186
187 X = read_columns(df, c=c, c_option=column_option).astype(float)
188 # sparse input
189 elif input_type == 'sparse':
190 X = mmread(open(infile1, 'r'))
191
192 # fasta_file input
193 elif input_type == 'seq_fasta':
194 pyfaidx = get_module('pyfaidx')
195 sequences = pyfaidx.Fasta(fasta_path)
196 n_seqs = len(sequences.keys())
197 X = np.arange(n_seqs)[:, np.newaxis]
198 for param in estimator_params.keys():
199 if param.endswith('fasta_path'):
200 estimator.set_params(
201 **{param: fasta_path})
202 break
203 else:
204 raise ValueError(
205 "The selected estimator doesn't support "
206 "fasta file input! Please consider using "
207 "KerasGBatchClassifier with "
208 "FastaDNABatchGenerator/FastaProteinBatchGenerator "
209 "or having GenomeOneHotEncoder/ProteinOneHotEncoder "
210 "in pipeline!")
211
212 elif input_type == 'refseq_and_interval':
213 path_params = {
214 'data_batch_generator__ref_genome_path': ref_seq,
215 'data_batch_generator__intervals_path': intervals,
216 'data_batch_generator__target_path': targets
217 }
218 estimator.set_params(**path_params)
219 n_intervals = sum(1 for line in open(intervals))
220 X = np.arange(n_intervals)[:, np.newaxis]
221
222 # Get target y
223 header = 'infer' if params['input_options']['header2'] else None
224 column_option = (params['input_options']['column_selector_options_2']
225 ['selected_column_selector_option2'])
226 if column_option in ['by_index_number', 'all_but_by_index_number',
227 'by_header_name', 'all_but_by_header_name']:
228 c = params['input_options']['column_selector_options_2']['col2']
229 else:
230 c = None
231
232 df_key = infile2 + repr(header)
233 if df_key in loaded_df:
234 infile2 = loaded_df[df_key]
235 else:
236 infile2 = pd.read_csv(infile2, sep='\t',
237 header=header, parse_dates=True)
238 loaded_df[df_key] = infile2
239
240 y = read_columns(
241 infile2,
242 c=c,
243 c_option=column_option,
244 sep='\t',
245 header=header,
246 parse_dates=True)
247 if len(y.shape) == 2 and y.shape[1] == 1:
248 y = y.ravel()
249 if input_type == 'refseq_and_interval':
250 estimator.set_params(
251 data_batch_generator__features=y.ravel().tolist())
252 y = None
253 # end y
254
255 # load groups
256 if groups:
257 groups_selector = (params['experiment_schemes']['test_split']
258 ['split_algos']).pop('groups_selector')
259
260 header = 'infer' if groups_selector['header_g'] else None
261 column_option = \
262 (groups_selector['column_selector_options_g']
263 ['selected_column_selector_option_g'])
264 if column_option in ['by_index_number', 'all_but_by_index_number',
265 'by_header_name', 'all_but_by_header_name']:
266 c = groups_selector['column_selector_options_g']['col_g']
267 else:
268 c = None
269
270 df_key = groups + repr(header)
271 if df_key in loaded_df:
272 groups = loaded_df[df_key]
273
274 groups = read_columns(
275 groups,
276 c=c,
277 c_option=column_option,
278 sep='\t',
279 header=header,
280 parse_dates=True)
281 groups = groups.ravel()
282
283 # del loaded_df
284 del loaded_df
285
286 # handle memory
287 memory = joblib.Memory(location=CACHE_DIR, verbose=0)
288 # cache iraps_core fits could increase search speed significantly
289 if estimator.__class__.__name__ == 'IRAPSClassifier':
290 estimator.set_params(memory=memory)
291 else:
292 # For iraps buried in pipeline
293 new_params = {}
294 for p, v in estimator_params.items():
295 if p.endswith('memory'):
296 # for case of `__irapsclassifier__memory`
297 if len(p) > 8 and p[:-8].endswith('irapsclassifier'):
298 # cache iraps_core fits could increase search
299 # speed significantly
300 new_params[p] = memory
301 # security reason, we don't want memory being
302 # modified unexpectedly
303 elif v:
304 new_params[p] = None
305 # handle n_jobs
306 elif p.endswith('n_jobs'):
307 # For now, 1 CPU is suggested for iprasclassifier
308 if len(p) > 8 and p[:-8].endswith('irapsclassifier'):
309 new_params[p] = 1
310 else:
311 new_params[p] = N_JOBS
312 # for security reason, types of callback are limited
313 elif p.endswith('callbacks'):
314 for cb in v:
315 cb_type = cb['callback_selection']['callback_type']
316 if cb_type not in ALLOWED_CALLBACKS:
317 raise ValueError(
318 "Prohibited callback type: %s!" % cb_type)
319
320 estimator.set_params(**new_params)
321
322 # handle scorer, convert to scorer dict
323 scoring = params['experiment_schemes']['metrics']['scoring']
324 scorer = get_scoring(scoring)
325 scorer, _ = _check_multimetric_scoring(estimator, scoring=scorer)
326
327 # handle test (first) split
328 test_split_options = (params['experiment_schemes']
329 ['test_split']['split_algos'])
330
331 if test_split_options['shuffle'] == 'group':
332 test_split_options['labels'] = groups
333 if test_split_options['shuffle'] == 'stratified':
334 if y is not None:
335 test_split_options['labels'] = y
336 else:
337 raise ValueError("Stratified shuffle split is not "
338 "applicable on empty target values!")
339
340 X_train, X_test, y_train, y_test, groups_train, groups_test = \
341 train_test_split_none(X, y, groups, **test_split_options)
342
343 exp_scheme = params['experiment_schemes']['selected_exp_scheme']
344
345 # handle validation (second) split
346 if exp_scheme == 'train_val_test':
347 val_split_options = (params['experiment_schemes']
348 ['val_split']['split_algos'])
349
350 if val_split_options['shuffle'] == 'group':
351 val_split_options['labels'] = groups_train
352 if val_split_options['shuffle'] == 'stratified':
353 if y_train is not None:
354 val_split_options['labels'] = y_train
355 else:
356 raise ValueError("Stratified shuffle split is not "
357 "applicable on empty target values!")
358
359 X_train, X_val, y_train, y_val, groups_train, groups_val = \
360 train_test_split_none(X_train, y_train, groups_train,
361 **val_split_options)
362
363 # train and eval
364 if hasattr(estimator, 'validation_data'):
365 if exp_scheme == 'train_val_test':
366 estimator.fit(X_train, y_train,
367 validation_data=(X_val, y_val))
368 else:
369 estimator.fit(X_train, y_train,
370 validation_data=(X_test, y_test))
371 else:
372 estimator.fit(X_train, y_train)
373
374 if hasattr(estimator, 'evaluate'):
375 scores = estimator.evaluate(X_test, y_test=y_test,
376 scorer=scorer,
377 is_multimetric=True)
378 else:
379 scores = _score(estimator, X_test, y_test, scorer,
380 is_multimetric=True)
381 # handle output
382 for name, score in scores.items():
383 scores[name] = [score]
384 df = pd.DataFrame(scores)
385 df = df[sorted(df.columns)]
386 df.to_csv(path_or_buf=outfile_result, sep='\t',
387 header=True, index=False)
388
389 memory.clear(warn=False)
390
391 if outfile_object:
392 main_est = estimator
393 if isinstance(estimator, pipeline.Pipeline):
394 main_est = estimator.steps[-1][-1]
395
396 if hasattr(main_est, 'model_') \
397 and hasattr(main_est, 'save_weights'):
398 if outfile_weights:
399 main_est.save_weights(outfile_weights)
400 del main_est.model_
401 del main_est.fit_params
402 del main_est.model_class_
403 del main_est.validation_data
404 if getattr(main_est, 'data_generator_', None):
405 del main_est.data_generator_
406 del main_est.data_batch_generator
407
408 with open(outfile_object, 'wb') as output_handler:
409 pickle.dump(estimator, output_handler,
410 pickle.HIGHEST_PROTOCOL)
411
412
413 if __name__ == '__main__':
414 aparser = argparse.ArgumentParser()
415 aparser.add_argument("-i", "--inputs", dest="inputs", required=True)
416 aparser.add_argument("-e", "--estimator", dest="infile_estimator")
417 aparser.add_argument("-X", "--infile1", dest="infile1")
418 aparser.add_argument("-y", "--infile2", dest="infile2")
419 aparser.add_argument("-O", "--outfile_result", dest="outfile_result")
420 aparser.add_argument("-o", "--outfile_object", dest="outfile_object")
421 aparser.add_argument("-w", "--outfile_weights", dest="outfile_weights")
422 aparser.add_argument("-g", "--groups", dest="groups")
423 aparser.add_argument("-r", "--ref_seq", dest="ref_seq")
424 aparser.add_argument("-b", "--intervals", dest="intervals")
425 aparser.add_argument("-t", "--targets", dest="targets")
426 aparser.add_argument("-f", "--fasta_path", dest="fasta_path")
427 args = aparser.parse_args()
428
429 main(args.inputs, args.infile_estimator, args.infile1, args.infile2,
430 args.outfile_result, outfile_object=args.outfile_object,
431 outfile_weights=args.outfile_weights, groups=args.groups,
432 ref_seq=args.ref_seq, intervals=args.intervals,
433 targets=args.targets, fasta_path=args.fasta_path)