首页 机器学习 - Optuna超参优化
文章
取消

机器学习 - Optuna超参优化

1. Optuna简介

Optuna 是一个特别为机器学习设计的自动超参数优化软件框架

2. 组件概念

默认的采样器是 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))

  1. 写一个objective方法,返回机器学习算法的Metrics,例如例子中的AUC
  2. 使用optuna.create_study创建一个Study
    1. study_name:改Study任务的名称,一般与storage一起使用
    2. storage:数据存储地址
    3. pruner:剪枝算法
    4. direction:机器学习算法**Metric**的优化方向,例如AUC是越大越好,则传入maximize,如果存在多个metrics,则传入数组即可
  3. 调用study.optimize优化参数
    1. objective:上面定义的方法
    2. n_trials:训练次数
    3. callbacks:回调方法,例如提前停止等

参考

本文由作者按照 CC BY 4.0 进行授权

机器学习 - 特征缩放详解

Python - 缺少C++构建工具