Mercurial > repos > bgruening > stacking_ensemble_models
comparison stacking_ensembles.py @ 3:0a1812986bc3 draft
planemo upload for repository https://github.com/bgruening/galaxytools/tree/master/tools/sklearn commit 9981e25b00de29ed881b2229a173a8c812ded9bb
| author | bgruening |
|---|---|
| date | Wed, 09 Aug 2023 11:10:37 +0000 |
| parents | 38c4f8a98038 |
| children |
comparison
equal
deleted
inserted
replaced
| 2:38c4f8a98038 | 3:0a1812986bc3 |
|---|---|
| 1 import argparse | 1 import argparse |
| 2 import ast | 2 import ast |
| 3 import json | 3 import json |
| 4 import mlxtend.regressor | |
| 5 import mlxtend.classifier | |
| 6 import pandas as pd | |
| 7 import pickle | |
| 8 import sklearn | |
| 9 import sys | 4 import sys |
| 10 import warnings | 5 import warnings |
| 11 from sklearn import ensemble | 6 from distutils.version import LooseVersion as Version |
| 12 | 7 |
| 13 from galaxy_ml.utils import (load_model, get_cv, get_estimator, | 8 import mlxtend.classifier |
| 14 get_search_params) | 9 import mlxtend.regressor |
| 10 from galaxy_ml import __version__ as galaxy_ml_version | |
| 11 from galaxy_ml.model_persist import dump_model_to_h5, load_model_from_h5 | |
| 12 from galaxy_ml.utils import get_cv, get_estimator | |
| 13 | |
| 14 warnings.filterwarnings("ignore") | |
| 15 | |
| 16 N_JOBS = int(__import__("os").environ.get("GALAXY_SLOTS", 1)) | |
| 15 | 17 |
| 16 | 18 |
| 17 warnings.filterwarnings('ignore') | 19 def main(inputs_path, output_obj, base_paths=None, meta_path=None): |
| 18 | |
| 19 N_JOBS = int(__import__('os').environ.get('GALAXY_SLOTS', 1)) | |
| 20 | |
| 21 | |
| 22 def main(inputs_path, output_obj, base_paths=None, meta_path=None, | |
| 23 outfile_params=None): | |
| 24 """ | 20 """ |
| 25 Parameter | 21 Parameter |
| 26 --------- | 22 --------- |
| 27 inputs_path : str | 23 inputs_path : str |
| 28 File path for Galaxy parameters | 24 File path for Galaxy parameters |
| 33 base_paths : str | 29 base_paths : str |
| 34 File path or paths concatenated by comma. | 30 File path or paths concatenated by comma. |
| 35 | 31 |
| 36 meta_path : str | 32 meta_path : str |
| 37 File path | 33 File path |
| 38 | |
| 39 outfile_params : str | |
| 40 File path for params output | |
| 41 """ | 34 """ |
| 42 with open(inputs_path, 'r') as param_handler: | 35 with open(inputs_path, "r") as param_handler: |
| 43 params = json.load(param_handler) | 36 params = json.load(param_handler) |
| 44 | 37 |
| 45 estimator_type = params['algo_selection']['estimator_type'] | 38 estimator_type = params["algo_selection"]["estimator_type"] |
| 46 # get base estimators | 39 # get base estimators |
| 47 base_estimators = [] | 40 base_estimators = [] |
| 48 for idx, base_file in enumerate(base_paths.split(',')): | 41 for idx, base_file in enumerate(base_paths.split(",")): |
| 49 if base_file and base_file != 'None': | 42 if base_file and base_file != "None": |
| 50 with open(base_file, 'rb') as handler: | 43 model = load_model_from_h5(base_file) |
| 51 model = load_model(handler) | |
| 52 else: | 44 else: |
| 53 estimator_json = (params['base_est_builder'][idx] | 45 estimator_json = params["base_est_builder"][idx]["estimator_selector"] |
| 54 ['estimator_selector']) | |
| 55 model = get_estimator(estimator_json) | 46 model = get_estimator(estimator_json) |
| 56 | 47 |
| 57 if estimator_type.startswith('sklearn'): | 48 if estimator_type.startswith("sklearn"): |
| 58 named = model.__class__.__name__.lower() | 49 named = model.__class__.__name__.lower() |
| 59 named = 'base_%d_%s' % (idx, named) | 50 named = "base_%d_%s" % (idx, named) |
| 60 base_estimators.append((named, model)) | 51 base_estimators.append((named, model)) |
| 61 else: | 52 else: |
| 62 base_estimators.append(model) | 53 base_estimators.append(model) |
| 63 | 54 |
| 64 # get meta estimator, if applicable | 55 # get meta estimator, if applicable |
| 65 if estimator_type.startswith('mlxtend'): | 56 if estimator_type.startswith("mlxtend"): |
| 66 if meta_path: | 57 if meta_path: |
| 67 with open(meta_path, 'rb') as f: | 58 meta_estimator = load_model_from_h5(meta_path) |
| 68 meta_estimator = load_model(f) | |
| 69 else: | 59 else: |
| 70 estimator_json = (params['algo_selection'] | 60 estimator_json = params["algo_selection"]["meta_estimator"][ |
| 71 ['meta_estimator']['estimator_selector']) | 61 "estimator_selector" |
| 62 ] | |
| 72 meta_estimator = get_estimator(estimator_json) | 63 meta_estimator = get_estimator(estimator_json) |
| 73 | 64 |
| 74 options = params['algo_selection']['options'] | 65 options = params["algo_selection"]["options"] |
| 75 | 66 |
| 76 cv_selector = options.pop('cv_selector', None) | 67 cv_selector = options.pop("cv_selector", None) |
| 77 if cv_selector: | 68 if cv_selector: |
| 69 if Version(galaxy_ml_version) < Version("0.8.3"): | |
| 70 cv_selector.pop("n_stratification_bins", None) | |
| 78 splitter, groups = get_cv(cv_selector) | 71 splitter, groups = get_cv(cv_selector) |
| 79 options['cv'] = splitter | 72 options["cv"] = splitter |
| 80 # set n_jobs | 73 # set n_jobs |
| 81 options['n_jobs'] = N_JOBS | 74 options["n_jobs"] = N_JOBS |
| 82 | 75 |
| 83 weights = options.pop('weights', None) | 76 weights = options.pop("weights", None) |
| 84 if weights: | 77 if weights: |
| 85 weights = ast.literal_eval(weights) | 78 weights = ast.literal_eval(weights) |
| 86 if weights: | 79 if weights: |
| 87 options['weights'] = weights | 80 options["weights"] = weights |
| 88 | 81 |
| 89 mod_and_name = estimator_type.split('_') | 82 mod_and_name = estimator_type.split("_") |
| 90 mod = sys.modules[mod_and_name[0]] | 83 mod = sys.modules[mod_and_name[0]] |
| 91 klass = getattr(mod, mod_and_name[1]) | 84 klass = getattr(mod, mod_and_name[1]) |
| 92 | 85 |
| 93 if estimator_type.startswith('sklearn'): | 86 if estimator_type.startswith("sklearn"): |
| 94 options['n_jobs'] = N_JOBS | 87 options["n_jobs"] = N_JOBS |
| 95 ensemble_estimator = klass(base_estimators, **options) | 88 ensemble_estimator = klass(base_estimators, **options) |
| 96 | 89 |
| 97 elif mod == mlxtend.classifier: | 90 elif mod == mlxtend.classifier: |
| 98 ensemble_estimator = klass( | 91 ensemble_estimator = klass( |
| 99 classifiers=base_estimators, | 92 classifiers=base_estimators, meta_classifier=meta_estimator, **options |
| 100 meta_classifier=meta_estimator, | 93 ) |
| 101 **options) | |
| 102 | 94 |
| 103 else: | 95 else: |
| 104 ensemble_estimator = klass( | 96 ensemble_estimator = klass( |
| 105 regressors=base_estimators, | 97 regressors=base_estimators, meta_regressor=meta_estimator, **options |
| 106 meta_regressor=meta_estimator, | 98 ) |
| 107 **options) | |
| 108 | 99 |
| 109 print(ensemble_estimator) | 100 print(ensemble_estimator) |
| 110 for base_est in base_estimators: | 101 for base_est in base_estimators: |
| 111 print(base_est) | 102 print(base_est) |
| 112 | 103 |
| 113 with open(output_obj, 'wb') as out_handler: | 104 dump_model_to_h5(ensemble_estimator, output_obj) |
| 114 pickle.dump(ensemble_estimator, out_handler, pickle.HIGHEST_PROTOCOL) | |
| 115 | |
| 116 if params['get_params'] and outfile_params: | |
| 117 results = get_search_params(ensemble_estimator) | |
| 118 df = pd.DataFrame(results, columns=['', 'Parameter', 'Value']) | |
| 119 df.to_csv(outfile_params, sep='\t', index=False) | |
| 120 | 105 |
| 121 | 106 |
| 122 if __name__ == '__main__': | 107 if __name__ == "__main__": |
| 123 aparser = argparse.ArgumentParser() | 108 aparser = argparse.ArgumentParser() |
| 124 aparser.add_argument("-b", "--bases", dest="bases") | 109 aparser.add_argument("-b", "--bases", dest="bases") |
| 125 aparser.add_argument("-m", "--meta", dest="meta") | 110 aparser.add_argument("-m", "--meta", dest="meta") |
| 126 aparser.add_argument("-i", "--inputs", dest="inputs") | 111 aparser.add_argument("-i", "--inputs", dest="inputs") |
| 127 aparser.add_argument("-o", "--outfile", dest="outfile") | 112 aparser.add_argument("-o", "--outfile", dest="outfile") |
| 128 aparser.add_argument("-p", "--outfile_params", dest="outfile_params") | |
| 129 args = aparser.parse_args() | 113 args = aparser.parse_args() |
| 130 | 114 |
| 131 main(args.inputs, args.outfile, base_paths=args.bases, | 115 main(args.inputs, args.outfile, base_paths=args.bases, meta_path=args.meta) |
| 132 meta_path=args.meta, outfile_params=args.outfile_params) |
