如何实现您自己的可视化函数

本节将展示如何实现您自己的可视化函数。在这里,我们将实现一个绘制优化历史的可视化函数。

首先,导入 optuna 和其他必需的模块。

from __future__ import annotations

import matplotlib
import matplotlib.pyplot as plt
import optuna
import plotly.graph_objects as go

如果您使用 plotly 进行可视化,函数应该返回一个 plotly.graph_objects.Figure 对象。

def plot_optimizaiton_history(study: optuna.study.Study) -> go.Figure:
    trials = study.trials
    values = [trial.value for trial in trials]
    best_values = [min(values[: i + 1]) for i in range(len(values))]  # type: ignore
    iterations = list(range(len(trials)))

    fig = go.Figure()
    fig.add_trace(
        go.Scatter(
            x=iterations,
            y=best_values,
            mode="lines+markers",
        )
    )
    fig.update_layout(title="Optimization history")
    return fig

如果您使用 matplotlib 进行可视化,函数应该返回一个 matplotlib.figure.Figure 对象。

def plot_optimizaiton_history_matplotlib(study: optuna.study.Study) -> matplotlib.figure.Figure:
    trials = study.trials
    values = [trial.value for trial in trials]
    best_values = [min(values[: i + 1]) for i in range(len(values))]  # type: ignore

    fig, ax = plt.subplots()
    ax.set_title("Optimization history")
    ax.plot(best_values, marker="o")
    return fig

使用实现的可视化函数绘制优化历史。这里,我们使用简单的二次函数作为目标函数。

def objective(trial: optuna.trial.Trial) -> float:
    x = trial.suggest_float("x", -10, 10)
    return x**2


study = optuna.create_study()
study.optimize(objective, n_trials=100)

fig = plot_optimizaiton_history(study)
fig.show()  # plt.show() for matplotlib

实现您自己的可视化函数后,您可以将其注册到 OptunaHub。关于如何向 OptunaHub 注册您的可视化函数,请参阅 如何向 OptunaHub 注册您的包

脚本总运行时间: (0 分钟 0.363 秒)

由 Sphinx-Gallery 生成的图库