HyperoptPipelineSelector.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Tue Oct 6 15:04:25 2020
  5. @author: tanya
  6. @description:a class for selecting a machine learning
  7. pipeline from a deterministic space of parameter distributions
  8. over multiple pipelines.
  9. The selection is though in such a way that a Trials object is being
  10. maintained during the tuning process from which one can retrieve
  11. the best pipeline so far as well as the entire tuning history
  12. if needed.
  13. """
  14. import os
  15. import pickle
  16. from copy import deepcopy
  17. import datetime
  18. from typing import Callable
  19. import pandas as pd
  20. import numpy as np
  21. from sklearn.pipeline import Pipeline
  22. from hyperopt import fmin, tpe, rand, Trials, space_eval
  23. from cdplib.pipeline_selector.PipelineSelector import PipelineSelector
  24. class HyperoptPipelineSelector(PipelineSelector):
  25. """
  26. Use this class to perform a search
  27. for a machine learning pipeline in a given parameter space.
  28. The parameter space can include multiple types of Pipelines
  29. (SVM, XGBOOST, random forest, etc),
  30. as well as parameter distributions for each pipeline parameter.
  31. See example in main for the expected space structure.
  32. The search can be performed either randomly
  33. or with a tree-based algorithm. (Other methods are currently
  34. developped by hyperopt creators).
  35. Attribute trials is responsible for book-keeping parameter
  36. combinations that have already been tried out. This attribute
  37. is saved to a binary file every n minutes as well as every time
  38. a better pipeline was found.
  39. """
  40. def __init__(self,
  41. cost_func: (Callable, str),
  42. greater_is_better: bool,
  43. trials_path: str,
  44. backup_trials_freq: int = None,
  45. cross_val_averaging_func: Callable = None,
  46. additional_metrics: dict = None,
  47. strategy_name: str = None,
  48. stdout_log_level: str = "INFO"):
  49. """
  50. :param callable cost_func: function to minimize or maximize
  51. :param bool greater_is_better: when True
  52. cost_func is maximized, else minimized.
  53. :param str trials_path: path at which the trials object is saved
  54. in binary format. From the trials object we can
  55. select information about the obtained scores, score variations,
  56. and pipelines, and parameters tried out so far. If a trials object
  57. already exists at the given path, it is loaded and the
  58. search is continued, else, the search is started from
  59. the beginning.
  60. :param backup_trials_freq: frequecy in interations (trials)
  61. of saving the trials object at the trials_path.
  62. :param str log_path: Optional, when not provided logs to stdout.
  63. :param callable averaging_func: optional,
  64. when not provided set to mean. Function
  65. to aggregate the cross-validated values of the cost function.
  66. Classic situation is to take the mean,
  67. another example is, for example mean() - c*var().
  68. :param additional_metics: dict of additional metrics to save
  69. of the form {"metric_name": metric} where metric is a Callable.
  70. :param str strategy_name: a name might be asigned to the trials,
  71. a strategy is defined by the data set, cv object, cost function.
  72. When the strategy changes, one should start with new trials.
  73. :param str stdout_log_level: can be INFO, WARNING, ERROR
  74. """
  75. super().__init__(cost_func=cost_func,
  76. greater_is_better=greater_is_better,
  77. trials_path=trials_path,
  78. backup_trials_freq=backup_trials_freq,
  79. cross_val_averaging_func=cross_val_averaging_func,
  80. additional_metrics=additional_metrics,
  81. strategy_name=strategy_name,
  82. stdout_log_level=stdout_log_level)
  83. self._trials = self._trials or Trials()
  84. def run_trials(self,
  85. niter: int,
  86. algo: callable = tpe.suggest):
  87. '''
  88. Method performing the search of the best pipeline in the given space.
  89. Calls fmin function from the hyperopt library to minimize the output of
  90. _objective.
  91. :params int niter: number of search iterations
  92. :param callable algo: now can only take values tpe for a tree-based
  93. random search or random for random search
  94. '''
  95. try:
  96. assert(self.attached_space)
  97. except AssertionError:
  98. err = ("Space must be attach to be able to "
  99. "retrieve this information.")
  100. self._logger.log_and_raise_error(err)
  101. try:
  102. assert(isinstance(niter, int))
  103. except AssertionError:
  104. err = "Parameter 'niter' must be of int type"
  105. self._logger.log_and_raise_error(err, ErrorType=NameError)
  106. try:
  107. # right now only two algorithms are provided by hyperopt
  108. assert(algo in [tpe.suggest, rand.suggest])
  109. except AssertionError:
  110. err = ("Parameter 'algo' can be now only tpe or random. "
  111. "If other algorithms have been developped by "
  112. "by hyperopt, plased add them to the list.")
  113. self._logger.log_and_raise_error(err)
  114. try:
  115. self._trials = self._trials or Trials()
  116. self._logger.info(("Starting {0} iterations of search "
  117. "additional to {1} previous"
  118. .format(niter, len(self._trials.trials))))
  119. best_trial = fmin(fn=self._objective,
  120. space=self._space,
  121. algo=algo,
  122. trials=self._trials,
  123. max_evals=len(self._trials.trials) + niter)
  124. self._logger.info(
  125. "Best score is {0} with variance {1}"
  126. .format(
  127. self._trials.best_trial["result"]["score"],
  128. self._trials.best_trial["result"]["score_variance"]))
  129. self._logger.info(("Finished {0} iterations of search.\n"
  130. "Best parameters are:\n {1} ")
  131. .format(niter,
  132. space_eval(self._space, best_trial)))
  133. self.finished_tuning = True
  134. self.total_tuning_time = datetime.datetime.today()\
  135. - self.start_tuning_time
  136. self._backup_trials()
  137. except Exception as e:
  138. raise ValueError(("Failed to select best "
  139. "pipeline! Exit with error: {}").format(e))
  140. @property
  141. def number_of_trials(self) -> int:
  142. """
  143. :return: number of trials run so far
  144. with the given Trials object
  145. """
  146. try:
  147. return len(self._trials.trials)
  148. except Exception as e:
  149. err = ("Failed to retrieve the number of trials. "
  150. "Exit with error {}".format(e))
  151. self._logger.log_and_raise_error(err)
  152. def _get_space_element_from_trial(self, trial) -> dict:
  153. """
  154. Hyperopt trials object does not contain the space
  155. elements that result in the corresponding trials.
  156. One has to use the function space_eval from
  157. hyperopt to get the space element.
  158. After retrieving the space element,
  159. parameters of the pipeline are set.
  160. """
  161. trial = deepcopy(trial)
  162. try:
  163. assert(self.attached_space)
  164. except AssertionError:
  165. err = "Hyperparameter space not attached."
  166. self._logger.log_and_raise_error(err)
  167. try:
  168. space_element = space_eval(self._space,
  169. {k: v[0] for k, v in
  170. trial['misc']['vals'].items()
  171. if len(v) > 0})
  172. pipeline = deepcopy(space_element["pipeline"])
  173. params = deepcopy(space_element["params"])
  174. pipeline.set_params(**params)
  175. space_element["pipeline"] = pipeline
  176. return space_element
  177. except Exception as e:
  178. err = ("Failed to retrieve a space element from a trial. "
  179. "Exit with error: {}".format(e))
  180. def _get_space_element_from_index(self, i: int) -> dict:
  181. """
  182. Gets the space element of shape
  183. {"name": NAME, "params": PARAMS, "pipeline": PIPELINE}
  184. from the trial number i.
  185. """
  186. try:
  187. assert(len(self._trials.trials) > i)
  188. except AssertionError:
  189. err = ("Trials object is not long enough "
  190. "to retrieve index {}".format(i))
  191. self._logger.log_and_raise_error(err, ErrorType=NameError)
  192. try:
  193. return self._get_space_element_from_trial(self._trials.trials[i])
  194. except Exception as e:
  195. err = ("Failed to get space element from index. "
  196. "Exit with error {}".format(e))
  197. self._logger.log_and_raise_error(err)
  198. def _get_pipeline_from_index(self, i: int) -> Pipeline:
  199. """
  200. Gets a pipeline with set parameters from the trial number i
  201. """
  202. try:
  203. space_element = self._get_space_element_from_index(i)
  204. return space_element["pipeline"]
  205. except Exception as e:
  206. err = ("Failed to retrieve pipeline from index. "
  207. "Exit with error: {}".format(e))
  208. self._logger.log_and_raise_error(err)
  209. @property
  210. def best_trial(self) -> dict:
  211. """
  212. :return: dictionary with the summary of the best trial
  213. and space element (name, pipeline, params)
  214. resulting in the best trial
  215. """
  216. if len(self._trials.trials) == 0:
  217. self._logger.log_and_throw_warning("Trials object is empty")
  218. return {}
  219. else:
  220. try:
  221. best_trial = deepcopy(self._trials.best_trial)
  222. if self.attached_space:
  223. space_element = self._get_space_element_from_trial(
  224. best_trial)
  225. else:
  226. space_element = {}
  227. warn = ("Space is not attached, "
  228. "To included the best pipeline "
  229. "attach the space")
  230. self._logger.log_and_throw_warning(warn)
  231. best_trial = deepcopy(self._trials.best_trial["result"])
  232. best_trial.update(space_element)
  233. return best_trial
  234. except Exception as e:
  235. err = "Failed to retrieve best trial. Exit with error: {}"\
  236. .format(e)
  237. self._logger.log_and_raise_error(err)
  238. @property
  239. def best_trial_score(self) -> float:
  240. """
  241. """
  242. try:
  243. if len(self.best_trial) > 0:
  244. return self.best_trial["score"]
  245. else:
  246. return np.nan
  247. except Exception as e:
  248. err = ("Failed to retrieve best trial score. "
  249. "Exit with error: {}".format(e))
  250. self._logger.log_and_raise_error(err)
  251. @property
  252. def best_trial_score_variance(self) -> float:
  253. """
  254. """
  255. try:
  256. if len(self.best_trial) > 0:
  257. return self.best_trial["score_variance"]
  258. else:
  259. return np.nan
  260. except Exception as e:
  261. err = ("Failed to retrieve best trial score variance. "
  262. "Exit with error: {}".format(e))
  263. self._logger.log_and_raise_error(err)
  264. @property
  265. def best_trial_pipeline(self) -> Pipeline:
  266. """
  267. """
  268. try:
  269. if len(self.best_trial) > 0:
  270. return self.best_trial["pipeline"]
  271. else:
  272. return np.nan
  273. except Exception as e:
  274. err = ("Failed to retrieve best trial pipeline. "
  275. "Exit with error: {}".format(e))
  276. self._logger.log_and_raise_error(err)
  277. def get_n_best_trial_pipelines(self, n: int) -> list:
  278. """
  279. :return: the list of n best pipelines
  280. documented in trials
  281. """
  282. try:
  283. if len(self._trials.trials) == 0:
  284. return []
  285. else:
  286. n_best_trials = sorted(self._trials.trials,
  287. key=lambda x: x["result"]["score"],
  288. reverse=True)[:n]
  289. return [self._get_space_element_from_trial(trial)["pipeline"]
  290. for trial in n_best_trials]
  291. except Exception as e:
  292. err = ("Failed to retrieve n best pipelines. "
  293. "Exit with error: {}".format(e))
  294. self._logger.log_and_raise_error(err)
  295. def get_n_best_trial_pipelines_of_each_type(self, n: int) -> dict:
  296. """
  297. :return: a dictiionry where keys are pipeline names,
  298. and values are lists of best pipelines with this name
  299. """
  300. scores = [trial["result"]["score"] for trial in self._trials.trials]
  301. names = [self._get_space_element_from_trial(trial)["name"]
  302. for trial in self._trials.trials]
  303. return pd.DataFrame({"name": names, "score": scores})\
  304. .sort_values(by=["name", "score"], ascending=False)\
  305. .groupby("name")\
  306. .head(n)\
  307. .reset_index()\
  308. .assign(pipeline=lambda x: x["index"]
  309. .apply(self._get_pipeline_from_index))\
  310. .groupby("name")["pipeline"]\
  311. .apply(lambda x: list(x))\
  312. .to_dict()
  313. def trials_to_excel(self, path: str = None):
  314. """
  315. Saves an excel file with pipeline names, scores,
  316. parameters, and timestamps.
  317. """
  318. results = [trial["result"] for trial in self._trials.trials]
  319. space_elements = [self._get_space_element_from_trial(trial)
  320. for trial in self._trials.trials]
  321. pd.DataFrame([{**result, **space_element}
  322. for result, space_element in
  323. zip(results, space_elements)]).to_excel(path)
  324. if __name__ == '__main__':
  325. # elementary example
  326. from sklearn.metrics import roc_auc_score, precision_score
  327. from sklearn.datasets import load_breast_cancer
  328. from cdplib.log import Log
  329. from cdplib.db_handlers import MongodbHandler
  330. from cdplib.hyperopt.space_sample import space
  331. # from cdplib.hyperopt.composed_space_sample import space
  332. trials_path = "hyperopt_trials_TEST.pkl"
  333. additional_metrics = {"precision": precision_score}
  334. strategy_name = "strategy_1"
  335. data_path = "data_TEST.h5"
  336. cv_path = "cv_TEST.pkl"
  337. collection_name = 'TEST_' + strategy_name
  338. logger = Log("HyperoptPipelineSelector__TEST:")
  339. logger.info("Start test")
  340. data_loader = load_breast_cancer()
  341. X = data_loader["data"]
  342. y = data_loader["target"]
  343. pd.DataFrame(X).to_hdf(data_path, key="X_train")
  344. pd.Series(y).to_hdf(data_path, key="y_train")
  345. cv = [(list(range(len(X)//3)), list(range(len(X)//3, len(X)))),
  346. (list(range(2*len(X)//3)), list(range(2*len(X)//3, len(X))))]
  347. pickle.dump(cv, open(cv_path, "wb"))
  348. hs = HyperoptPipelineSelector(cost_func=roc_auc_score,
  349. greater_is_better=True,
  350. trials_path=trials_path,
  351. additional_metrics=additional_metrics,
  352. strategy_name=strategy_name,
  353. stdout_log_level="WARNING")
  354. hs.attach_space(space=space)
  355. hs.attach_data_from_hdf5(data_hdf5_store_path=data_path,
  356. cv_pickle_path=cv_path)
  357. save_method = MongodbHandler().insert_data_into_collection
  358. save_kwargs = {'collection_name': collection_name}
  359. hs.configer_summary_saving(save_method=save_method,
  360. kwargs=save_kwargs)
  361. hs.run_trials(niter=10)
  362. logger.info("Best Trial: {}".format(hs.best_trial))
  363. logger.info("Total tuning time: {}".format(hs.total_tuning_time))
  364. for file in [trials_path, data_path, cv_path]:
  365. os.remove(file)
  366. logger.info("End test")