引言
Optuna 是一个特别为机器学习设计的自动超参数优化软件框架。它具有命令式的,define-by-run 风格的 API。由于这种 API 的存在,用 Optuna 编写的代码模块化程度很高,Optuna 的用户因此也可以动态地构造超参数的搜索空间。
更多功能可参见optuna
基本介绍
简单介绍一下optuna里最重要的几个term。
在optuna里最重要的三个term:
(1)Trial:目标函数的单次执行过程
(2)Study:基于目标函数的优化过程, 一个优化超参的session,由一系列的trials组成;
(3)Parameter:需要优化的超参;
study
在optuna里,study对象用来管理对超参的优化,optuna.create_study()返回一个study对象。
study又有很多有用的 property:
(1)study.best_params:搜出来的最优超参;
(2)study.best_value:最优超参下,objective函数返回的值 (如最高的Acc,最低的Error rate等);
(3)study.best_trial:最优超参对应的trial,有一些时间、超参、trial编号等信息;
(4)study.optimize(objective, n_trials):对objective函数里定义的超参进行搜索;
搜索方式
optuna支持很多种搜索方式:
(1)trial.suggest_categorical(‘optimizer’, [‘MomentumSGD’, ‘Adam’]):表示从SGD和adam里选一个使用;
(2)trial.suggest_int(‘num_layers’, 1, 3):从1~3范围内的int里选;
(3)trial.suggest_uniform(‘dropout_rate’, 0.0, 1.0):从0~1内的uniform分布里选;
(4)trial.suggest_loguniform(‘learning_rate’, 1e-5, 1e-2):从1e-5~1e-2的log uniform分布里选;
(5)trial.suggest_discrete_uniform(‘drop_path_rate’, 0.0, 1.0, 0.1):从0~1且step为0.1的离散uniform分布里选;
一个 study 的目的是通过多次 trial (例如 n_trials=100 ) 来找出最佳的超参数值集,而 Optuna 旨在加速和自动化此类 study 优化过程。
github上示例
XGBoostPruningCallback
"""
Optuna example that demonstrates a pruner for XGBoost.
In this example, we optimize the validation accuracy of cancer detection using XGBoost.——
We optimize both the choice of booster model and their hyperparameters. Throughout
training of models, a pruner observes intermediate results and stop unpromising trials.
You can run this example as follows:
$ python xgboost_integration.py
"""
import numpy as np
import sklearn.datasets
import sklearn.metrics
from sklearn.model_selection import train_test_split
import xgboost as xgb
import optuna
# FYI: Objective functions can take additional arguments
# (https://optuna.readthedocs.io/en/stable/faq.html#objective-func-additional-args).
def objective(<