HyperoptPipelineSelector.py 17 KB

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