Python机器学习:超参数调优

开发 后端
那超参数应该如何设置呢?似乎没有捷径,去尝试不同的取值,比较不同的结果取最好的结果。

[[377792]]

 1.什么是超参数

超参数(hyper parameters)就是机器学习或深度学习算法中需要预先设置的参数,这些参数不是通过训练数据学习到的参数;原始算法一般只给出超参数的取值范围和含义,根据不同的应用场景,同一个算法的同一超参数设置也不同。

那超参数应该如何设置呢?似乎没有捷径,去尝试不同的取值,比较不同的结果取最好的结果。

本文整理了不同的尝试方法,如下:

  •  RandomSearch
  •  GridSearch
  •  贝叶斯优化(Bayesian optimization)

2. GridSearchCV

暴力穷举是寻找最优超参数一种简单有效的方法,但是对于算法庞大的超参数空间来说,穷举会损耗大量的时间,特别是多个超参数情况下。GridSearchCV的做法是缩减了超参数值的空间,只搜索人为重要的超参数和有限的固定值。同时结合了交叉验证的方式来搜索最优的超参数。

拿lightgbm为例子: 

  1. import pandas as pd  
  2. import numpy as np  
  3. import math  
  4. import warnings  
  5. import lightgbm as lgb  
  6. from sklearn.model_selection import GridSearchCV  
  7. from sklearn.model_selection import RandomizedSearchCV  
  8. lg = lgb.LGBMClassifier(silent=False 
  9. param_dist = {"max_depth": [2, 3, 4, 5, 7, 10],  
  10.               "n_estimators": [50, 100, 150, 200],  
  11.               "min_child_samples": [2,3,4,5,6]  
  12.              }  
  13. grid_search = GridSearchCV(estimator=lgn_jobs=10param_grid=param_distcv = 5scoring='f1'verbose=5 
  14. grid_search.fit(X_train, y)  
  15. grid_search.best_estimator_, grid_search.best_score_ 
  16. # Fitting 5 folds for each of 120 candidates, totalling 600 fits  
  17. # [Parallel(n_jobs=10)]: Using backend LokyBackend with 10 concurrent workers.  
  18. # [Parallel(n_jobs=10)]: Done  52 tasks      | elapsed:    2.5s  
  19. # [Parallel(n_jobs=10)]: Done 142 tasks      | elapsed:    6.6s  
  20. # [Parallel(n_jobs=10)]: Done 268 tasks      | elapsed:   14.0s  
  21. # [Parallel(n_jobs=10)]: Done 430 tasks      | elapsed:   25.5s  
  22. # [Parallel(n_jobs=10)]: Done 600 out of 600 | elapsed:   40.6s finished  
  23. # (LGBMClassifier(max_depth=10min_child_samples=6n_estimators=200 
  24. #                 silent=False), 0.6359524127649383) 

从上面可知,GridSearchCV搜索过程

  •  模型estimator:lgb.LGBMClassifier
  •  param_grid:模型的超参数,上面例子给出了3个参数,值得数量分别是6,4,5,组合起来的搜索空间是120个
  •  cv:交叉验证的折数(上面例子5折交叉), 算法训练的次数总共为120*5=600
  •  scoring:模型好坏的评价指标分数,如F1值
  •  搜索返回: 最好的模型 best_estimator_和最好的分数

https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html#sklearn.model_selection.GridSearchCV

3. RandomSearchCV

和GridSearchCV一样,RandomSearchCV也是在有限的超参数空间(人为重要的超参数)中搜索最优超参数。不一样的地方在于搜索超参数的值不是固定,是在一定范围内随机的值。不同超参数值的组合也是随机的。值的随机性可能会弥补GridSearchCV超参数值固定的有限组合,但也可能更坏。 

  1. Better than grid search in various senses but still expensive to guarantee good coverage 

 

  1. import pandas as pd  
  2. import numpy as np  
  3. import math  
  4. import warnings  
  5. import lightgbm as lgb  
  6. from scipy.stats import uniform  
  7. from sklearn.model_selection import GridSearchCV  
  8. from sklearn.model_selection import RandomizedSearchCV  
  9. lg = lgb.LGBMClassifier(silent=False 
  10. param_dist = {"max_depth": range(2,15,1),  
  11.               "n_estimators": range(50,200,4),  
  12.               "min_child_samples": [2,3,4,5,6],  
  13.              }  
  14. random_search = RandomizedSearchCV(estimator=lgn_jobs=10param_distparam_distributions=param_dist, n_iter=100cv = 5scoring='f1'verbose=5 
  15. random_search.fit(X_train, y)  
  16. random_search.best_estimator_, random_search.best_score_  
  17. # Fitting 5 folds for each of 100 candidates, totalling 500 fits  
  18. # [Parallel(n_jobs=10)]: Using backend LokyBackend with 10 concurrent workers.  
  19. # [Parallel(n_jobs=10)]: Done  52 tasks      | elapsed:    6.6s  
  20. # [Parallel(n_jobs=10)]: Done 142 tasks      | elapsed:   12.9s  
  21. # [Parallel(n_jobs=10)]: Done 268 tasks      | elapsed:   22.9s  
  22. # [Parallel(n_jobs=10)]: Done 430 tasks      | elapsed:   36.2s  
  23. # [Parallel(n_jobs=10)]: Done 500 out of 500 | elapsed:   42.0s finished  
  24. # (LGBMClassifier(max_depth=11min_child_samples=3n_estimators=198 
  25. #                 silent=False), 0.628180299445963) 

从上可知,基本和GridSearchCV类似,不同之处如下:

  •  n_iter:随机搜索值的数量
  •  param_distributions:搜索值的范围,除了list之外,也可以是某种分布如uniform均匀分布等

https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html#sklearn.model_selection.RandomizedSearchCV

4. 贝叶斯优化(Bayesian optimization)

不管是GridSearchCV还是RandomSearchCV, 都是在调参者给定的有限范围内搜索全部或者部分参数的组合情况下模型的最佳表现;可想而知最优模型参数取决于先验的模型参数和有限范围,某些情况下并一定是最优的, 而且暴力搜索对于大的候选参数空间也是很耗时的。

我们换了角度来看待参数搜索的问题:我们的目的是选择一个最优的参数组合,使得训练的模型在给定的数据集上表现最好,所以可以理解成是一个最优化问题。

我们通常使用梯度下降的方式来迭代的计算最优值,但是梯度下降要求优化的函数是固定并且是可导的,如交叉熵loss等。对于参数搜索问题, 我们要在众多模型(不同的超参)中找一个效果最好的模型,判断是否最好是由模型决定的,而模型是一个黑盒子,不知道是什么结构,以及是否是凸函数,是没办法使用梯度下降方法。

这种情况下,贝叶斯优化是一种解决方案。贝叶斯优化把搜索的模型空间假设为高斯分布,利用高斯过程,按迭代的方式每次计算得到比当前最优参数期望提升的新的最优参数。

通用的算法如下:

  •  Input:f是模型, M是高斯拟合函数, X是参数, S是参数选择算法Acquisition Function
  •  初始化高斯分布拟合的数据集D,为(x,y), x是超参数,y是超参数的x的执行结果(如精确率等)
  •  迭代T次
  •  每次迭代,用D数据集拟合高斯分布函数
  •  根据拟合的函数,根据Acquisition Function(如Expected improvement算法),在参数空间选择一个比当前最优解更优的参数xi
  •  将参数xi代入模型f(训练一个模型),得出相应的yi(新模型的精确率等)
  •  (xi,yi)重新加入拟合数据集D,再一次迭代

由此可知,贝叶斯优化每次都利用上一次参数选择。而GridSearchCV和RandomSearchCV每一次搜索都是独立的。

到此,简单介绍了贝叶斯优化的理论知识。有很多第三方库实现了贝叶斯优化的实现,如 advisor,bayesian-optimization,Scikit-Optimize和GPyOpt等。本文以GPyOpt和bayesian-optimization为例子。 

  1. pip install gpyopt  
  2. pip install bayesian-optimization 
  3. pip install scikit-optimize 
  •  gpyopt例子 
  1. import GPy  
  2. import GPyOpt  
  3. from GPyOpt.methods import BayesianOptimization  
  4. from sklearn.model_selection import train_test_split  
  5. from sklearn.model_selection import cross_val_score  
  6. from sklearn.datasets import load_iris  
  7. from xgboost import XGBRegressor  
  8. import numpy as np   
  9. iris = load_iris()  
  10. X = iris.data 
  11. y = iris.target  
  12. x_train, x_test, y_train, y_test = train_test_split(X,y,test_size = 0.3,random_state = 14 
  13. # 超参数搜索空间  
  14. bds = [{'name': 'learning_rate', 'type': 'continuous', 'domain': (0, 1)},  
  15.         {'name': 'gamma', 'type': 'continuous', 'domain': (0, 5)},  
  16.         {'name': 'max_depth', 'type': 'continuous', 'domain': (1, 50)}]   
  17. # Optimization objective 模型F  
  18. def cv_score(parameters): 
  19.      parametersparameters = parameters[0]  
  20.     score = cross_val_score 
  21.                 XGBRegressor(learning_rate=parameters[0],  
  22.                               gamma=int(parameters[1]),  
  23.                               max_depth=int(parameters[2])),  
  24.                 X, y, scoring='neg_mean_squared_error').mean()  
  25.     score = np.array(score)  
  26.     return score  
  27. # acquisition就是选择不同的Acquisition Function  
  28. optimizer = GPyOpt.methods.BayesianOptimization(f = cv_score,            # function to optimize         
  29.                                           domain = bds,         # box-constraints of the problem  
  30.                                           acquisition_type ='LCB',       # LCB acquisition  
  31.                                           acquisition_weight = 0.1)   # Exploration exploitation  
  32.  x_best = optimizer.X[np.argmax(optimizer.Y)]  
  33. print("Best parameters: learning_rate="+str(x_best[0])+",gamma="+str(x_best[1])+",max_depth="+str(x_best[2]))  
  34. # Best parameters: learning_rate=0.4272184438229706,gamma=1.4805727469635759,max_depth=41.8460390442754 
  •  bayesian-optimization例子 
  1. from sklearn.datasets import make_classification  
  2. from xgboost import XGBRegressor  
  3. from sklearn.model_selection import cross_val_score  
  4. from bayes_opt import BayesianOptimization  
  5. iris = load_iris()  
  6. X = iris.data  
  7. y = iris.target  
  8. x_train, x_test, y_train, y_test = train_test_split(X,y,test_size = 0.3,random_state = 14 
  9. bds ={'learning_rate': (0, 1),  
  10.         'gamma': (0, 5),  
  11.         'max_depth': (1, 50)}  
  12. # Optimization objective   
  13. def cv_score(learning_rate, gamma,  max_depth):  
  14.     score = cross_val_score 
  15.                 XGBRegressor(learning_ratelearning_rate=learning_rate,  
  16.                               gamma=int(gamma),  
  17.                               max_depth=int(max_depth)),   
  18.                 X, y, scoring='neg_mean_squared_error').mean()  
  19.     score = np.array(score)  
  20.     return score  
  21. rf_bo = BayesianOptimization 
  22.         cv_score,  
  23.         bds  
  24.     )  
  25. rf_bo.maximize()  
  26. rf_bo.max   
  27. |   iter    |  target   |   gamma   | learni... | max_depth |  
  28. -------------------------------------------------------------  
  29. |  1        | -0.0907   |  0.7711   |  0.1819   |  20.33    |  
  30. |  2        | -0.1339   |  4.933    |  0.6599   |  8.972    |  
  31. |  3        | -0.07285  |  1.55     |  0.8247   |  33.94    |  
  32. |  4        | -0.1359   |  4.009    |  0.3994   |  25.55    |  
  33. |  5        | -0.08773  |  1.666    |  0.9551   |  48.67    |  
  34. |  6        | -0.05654  |  0.0398   |  0.3707   |  1.221    |  
  35. |  7        | -0.08425  |  0.6883   |  0.2564   |  33.25    |  
  36. |  8        | -0.1113   |  3.071    |  0.8913   |  1.051    |  
  37. |  9        | -0.9167   |  0.0      |  0.0      |  2.701    |  
  38. |  10       | -0.05267  |  0.0538   |  0.1293   |  1.32     |  
  39. |  11       | -0.08506  |  1.617    |  1.0      |  32.68    |  
  40. |  12       | -0.09036  |  2.483    |  0.2906   |  33.21    |  
  41. |  13       | -0.08969  |  0.4662   |  0.3612   |  34.74    |  
  42. |  14       | -0.0723   |  1.295    |  0.2061   |  1.043    |  
  43. |  15       | -0.07531  |  1.903    |  0.1182   |  35.11    |  
  44. |  16       | -0.08494  |  2.977    |  1.0      |  34.57    |  
  45. |  17       | -0.08506  |  1.231    |  1.0      |  36.05    |  
  46. |  18       | -0.07023  |  2.81     |  0.838    |  36.16    |  
  47. |  19       | -0.9167   |  1.94     |  0.0      |  36.99    |  
  48. |  20       | -0.09041  |  3.894    |  0.9442   |  35.52    |  
  49. |  21       | -0.1182   |  3.188    |  0.01882  |  35.14    |  
  50. |  22       | -0.08521  |  0.931    |  0.05693  |  31.66    |  
  51. |  23       | -0.1003   |  2.26     |  0.07555  |  31.78    |  
  52. |  24       | -0.1018   |  0.08563  |  0.9838   |  32.22    |  
  53. |  25       | -0.1017   |  0.8288   |  0.9947   |  30.57    |  
  54. |  26       | -0.9167   |  1.943    |  0.0      |  30.2     |  
  55. |  27       | -0.08506  |  1.518    |  1.0      |  35.04    |  
  56. |  28       | -0.08494  |  3.464    |  1.0      |  32.36    |  
  57. |  29       | -0.1224   |  4.296    |  0.4472   |  33.47    |  
  58. |  30       | -0.1017   |  0.0      |  1.0      |  35.86    |  
  59. =============================================================  
  60. {'target': -0.052665895082105285,  
  61.  'params': {'gamma': 0.05379782654053811,  
  62.   'learning_rate': 0.1292986176550608,  
  63.   'max_depth': 1.3198257775801387}} 

bayesian-optimization只支持最大化,如果score是越小越好,可以加一个负号转化为最大值优化。

两者的优化结果并不是十分一致的,可能和实现方式和选择的算法不同,也和初始化的拟合数据集有关系。

5. 总结

本文介绍三种超参数优化的策略,希望对你有帮助。简要总结如下:

  •  GridSearchCV网格搜索,给定超参和取值范围,遍历所有组合得到最优参数。首先你要给定一个先验的取值,不能取得太多,否则组合太多,耗时太长。可以启发式的尝试。
  •  RandomSearchCV随机搜索,搜索超参数的值不是固定,是在一定范围内随机的值
  •  贝叶斯优化,采用高斯过程迭代式的寻找最优参数,每次迭代都是在上一次迭代基础上拟合高斯函数上,寻找比上一次迭代更优的参数,推荐gpyopt库 

 

责任编辑:庞桂玉 来源: Python中文社区(ID:python-china)
相关推荐

2022-10-31 11:33:30

机器学习参数调优

2022-08-30 00:31:12

机器学习超参数调优算法

2023-06-06 15:42:13

Optuna开源

2017-11-07 11:00:59

数据库调优DBMS

2010-03-04 10:56:52

JVM参数

2010-09-25 13:05:07

JVM参数

2021-03-26 06:05:17

Tomcat

2023-11-10 11:23:20

JVM内存

2023-07-28 14:49:00

黑盒优化机器学习

2013-03-20 17:30:18

2011-03-31 13:40:34

2012-01-10 14:35:08

JavaJVM

2010-09-17 17:02:24

JVM参数

2022-03-10 09:48:11

人工智能机器学习模型

2017-07-21 08:55:13

TomcatJVM容器

2021-09-06 11:02:17

JVM架构调优

2021-03-17 11:35:11

JVM代码Java

2022-01-27 23:32:03

Linux操作系统TCP

2017-08-08 14:54:54

机器学习模型参数超参数

2021-03-04 08:39:21

SparkRDD调优
点赞
收藏

51CTO技术栈公众号