HyperoptPipelineSelector.py 18 KB

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