1. Optuna简介
Optuna 是一个特别为机器学习设计的自动超参数优化软件框架
2. 组件概念
- Study: 基于目标函数的优化过程
- Trial: 目标函数的单次执行过程
3. 基本使用
3.1 参数采样方法
- optuna.trial.Trial.suggest_categorical() :用于类别参数
- optuna.trial.Trial.suggest_int() :用于整形参数
- optuna.trial.Trial.suggest_float() :用于浮点型参数
3.2 参数采样算法
- optuna.samplers.TPESampler :实现的 Tree-structured Parzen Estimator 算法
- optuna.samplers.CmaEsSampler: 实现的 CMA-ES 算法
- optuna.samplers.GridSampler :实现的网格搜索
- optuna.samplers.RandomSampler: 实现的随机搜索
默认的采样器是 optuna.samplers.TPESampler
3.3 使用例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import optuna
import lightgbm as lgb
import sklearn.datasets
import sklearn.metrics
from sklearn.model_selection import train_test_split
def objective(trial):
data, target = sklearn.datasets.load_breast_cancer(return_X_y=True)
train_x, valid_x, train_y, valid_y = train_test_split(data, target, test_size=0.25)
dtrain = lgb.Dataset(train_x, label=train_y)
dvalid = lgb.Dataset(valid_x, label=valid_y)
param = {
"objective": "binary",
"metric": "auc",
"verbosity": -1,
"boosting_type": "gbdt",
"lambda_l1": trial.suggest_float("lambda_l1", 1e-8, 10.0, log=True),
"lambda_l2": trial.suggest_float("lambda_l2", 1e-8, 10.0, log=True),
"num_leaves": trial.suggest_int("num_leaves", 2, 256),
"feature_fraction": trial.suggest_float("feature_fraction", 0.4, 1.0),
"bagging_fraction": trial.suggest_float("bagging_fraction", 0.4, 1.0),
"bagging_freq": trial.suggest_int("bagging_freq", 1, 7),
"min_child_samples": trial.suggest_int("min_child_samples", 5, 100),
}
# Add a callback for pruning.
pruning_callback = optuna.integration.LightGBMPruningCallback(trial, "auc")
evals_result = {}
evals_result_callback = lgb.record_evaluation(evals_result)
gbm = lgb.train(param, dtrain, valid_sets=[dvalid], callbacks=[pruning_callback, evals_result_callback])
preds = gbm.predict(valid_x)
accuracy = sklearn.metrics.roc_auc_score(valid_y, preds)
return accuracy
# return max(evals_result['valid_0']['auc'])
if __name__ == "__main__":
study = optuna.create_study(
study_name="lightGBM 01", storage="sqlite:///db.sqlite3",
pruner=optuna.pruners.MedianPruner(n_warmup_steps=10), direction="maximize"
)
# study = optuna.create_study(pruner=optuna.pruners.MedianPruner(n_warmup_steps=10), direction="maximize")
study.optimize(objective, n_trials=500)
# study.optimize(objective)
print("Number of finished trials: {}".format(len(study.trials)))
print("Best trial:")
trial = study.best_trial
print(" Value: {}".format(trial.value))
print(" Params: ")
for key, value in trial.params.items():
print(" {}: {}".format(key, value))
- 写一个
objective
方法,返回机器学习算法的Metrics
,例如例子中的AUC
值 - 使用
optuna.create_study
创建一个Study
- study_name:改Study任务的名称,一般与
storage
一起使用 - storage:数据存储地址
- pruner:剪枝算法
- direction:机器学习算法
**Metric**
的优化方向,例如AUC是越大越好,则传入maximize
,如果存在多个metrics,则传入数组即可
- study_name:改Study任务的名称,一般与
- 调用
study.optimize
优化参数- objective:上面定义的方法
- n_trials:训练次数
- callbacks:回调方法,例如提前停止等