HyperoptPipelineSelector.py 17 KB

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