Optuna 可视化 API 详解optuna.visualization 参考文档与 Plotly/Matplotlib 双后端完全实战指南【免费下载链接】optunaA hyperparameter optimization framework项目地址: https://gitcode.com/GitHub_Trending/op/optuna本文围绕 Optuna 官方参考文档docs/source/reference/visualization/index.rst所描述的optuna.visualization模块展开系统梳理其 12 个绘图函数与is_available的用法、公共参数语义target/target_name/params、Plotly 与 Matplotlib 双后端的对应关系并结合仓库源码剖析绘图数据层与渲染层的解耦设计。读完本篇你可以直接根据任意Study对象生成全部 12 类优化分析图并知道如何自定义图形、在 Jupyter 中正确渲染以及定位绘图相关的源码与测试。参考文档页的组织方式index.rst 到底包含什么参考文档入口 本身只有几行 Sphinx 指令但它是整个可视化 API 参考的装配页.. include:: ./generated/index.rst .. note:: The following :mod:optuna.visualization.matplotlib module uses Matplotlib as a backend. .. toctree:: :maxdepth: 1 matplotlib/index .. seealso:: The :ref:visualization tutorial provides use-cases with examples.include:: ./generated/index.rst引入由 Sphinx-Gallery 在文档构建时生成的reference/visualization/generated/index.rst其中聚合了 docs/visualization_examples/ 目录下 12 个示例脚本每个plot_*函数一个如 plot_contour 示例渲染出的缩略图、输出图与源码下方的 note 与 toctree 声明存在一个以Matplotlib 为后端的平行子模块optuna.visualization.matplotlib其参考页位于 matplotlib/index.rstseealso指向的:ref:visualization 即教程 tutorial/10_key_features/005_visualization.py它演示了全部绘图函数在真实训练场景FashionMNIST TPE MedianPruner下的用法。也就是说参考文档页 「自动生成的函数级示例画廊Plotly 后端」「Matplotlib 后端子模块」「教程交叉引用」。下面按模块实际 API 逐一展开。两个同构后端optuna.visualization 与 optuna.visualization.matplotlib从 optuna/visualization/init.py 与 optuna/visualization/matplotlib/init.py 的__all__列表可以确认两个模块导出同名同参的 12 个绘图函数唯一差异是绘图后端optuna.visualization基于Plotly返回plotly.graph_objects.Figure图形可交互悬停、缩放optuna.visualization.matplotlib基于Matplotlib返回matplotlib.axes.Axes适合离线出图与静态报告。函数用途所属文件Plotly 后端plot_optimization_history优化历史曲线每轮目标值 累计最优值支持error_bar_optimization_history.pyplot_intermediate_values各 trial 的训练/迭代过程曲线学习曲线基于trial.report_intermediate_values.pyplot_parallel_coordinate高维参数关系平行坐标图_parallel_coordinate.pyplot_contour双参数关系等高线图_contour.pyplot_slice单参数切片散点图参数值 vs 目标值_slice.pyplot_rank双参数散点图按目标值着色_rank.pyplot_edf目标值的经验分布函数EDF曲线_edf.pyplot_param_importances超参数重要性条形图基于 fANOVA 等评估器_param_importances.pyplot_pareto_front多目标 Pareto 前沿_pareto_front.pyplot_hypervolume_history超体积hypervolume随时间变化_hypervolume_history.pyplot_terminator_improvement终止条件terminator改善度量_terminator_improvement.pyplot_timelinetrial 执行时间线起止、状态着色_timeline.py两个模块各自还导出一个is_available()用于运行时探测后端是否可用Plotly 版见 optuna/visualization/_utils.py#L26-L40。官方教程中给出的切换方式非常直接把from optuna.visualization import ...换成from optuna.visualization.matplotlib import ...调用代码无需其他改动。安装与可用性检查教程 005_visualization.py 开头明确了依赖前提# Plotly 后端 pip install plotly # 若需要 Matplotlib 后端 pip install matplotlib从源码看is_available()的本质是一次导入探测Plotly 版调用_plotly_imports._imports.is_successful()并在 docstring 中注明要求 plotly 4.0.0 及以上Matplotlib 版则要求 matplotlib 3.0.0 及以上。若未安装绘图函数会在运行时通过_imports.check()抛出带安装提示的ImportError如 matplotlib 版实现 中_imports.check()的位置。实际使用建议import optuna from optuna.visualization import plot_optimization_history if not optuna.visualization.is_available(): raise RuntimeError(请先执行: pip install plotly) fig plot_optimization_history(study) fig.show() # 浏览器/Jupyter 中展示 Plotly Figure一个需要注意的 Jupyter 场景gallery 头部说明 指出optuna.visualization生成的 Plotly 图形在 JupyterLab 中默认不能直接渲染需要按 Plotly 官方的 JupyterLab 支持说明配置输出格式例如设置plotly.io.renderers默认渲染器。核心使用模式1. 所有函数都以 Study 为第一参数绘图函数的统一形态是plot_xxx(study, **kwargs)其中study可以是单个optuna.study.Study也可以是多个 Study 组成的序列用于同图对比多个研究。参数解析统一经过共享工具 optuna/visualization/_utils.pydef _check_plot_args( study: Study | Sequence[Study], target: Callable[[FrozenTrial], float] | None, target_name: str, ) - None: studies: Sequence[Study] if isinstance(study, Study): studies [study] else: studies study if target is None and any(study._is_multi_objective() for study in studies): raise ValueError( If the study is being used for multi-objective optimization, please specify the target. ) ...见 optuna/visualization/_utils.py#L49-L69这解释了最常见的报错多目标 Study 不指定target时抛ValueError——因为一个 trial 有多个目标值绘图函数无法自行决定画哪一个。2. 公共参数target与target_name大量函数支持target: Callable[[FrozenTrial], float]用于指定以 trial 的哪个量作为纵轴默认为None单目标时画trial.value指定后可以画任意派生量例如教程中的训练时长分析optuna.visualization.plot_param_importances( study, targetlambda t: t.duration.total_seconds(), target_nameduration, )注意配套规则指定了target但target_name仍是默认值Objective Value时_check_plot_args会发出警告提示轴标签名与实际内容不符——这正是上述示例中同时传target_nameduration的原因。3. 参数选择参数paramsplot_contour、plot_slice、plot_parallel_coordinate等参数关系图接受params: list[str] | NoneNone时取全部参数传入列表则只画指定参数教程中的用法plot_contour(study, params[lr, n_layers])。4. 非有限值的自动剔除所有以目标值纵轴的函数在取数时会经过_filter_nonfiniteoptuna/visualization/_utils.py#L98-L139值为nan/inf的 trial 会被剔除并打 warning 日志Trial {n} is omitted in visualization because its objective value is inf or nan.无法转成 float 的目标值则会抛出异常。这意味着出现约束违反导致的 inf 惩罚值时图中不会出现异常尖峰但你需要在日志里核对被剔除的 trial。5. 对数轴与数值/类别参数的自动判别绘图内部用_is_log_scale检查该参数在任一 trial 中是否以 log 分布FloatDistribution/IntDistribution且logTrue记录从而自动切换对数坐标轴_is_numerical则把全部取值为数字的CategoricalDistribution也视为数值参数处理源码注释说明这是仅为可视化保留的宽松行为见 optuna/visualization/_utils.py#L72-L95。各绘图函数实战以下示例基于官方教程 tutorial/10_key_features/005_visualization.py 的真实工作流TPE 采样 MedianPruner 优化一个 PyTorch 全连接分类器目标为验证集准确率trial.report(val_accuracy, epoch)记录逐 epoch 中间值。study optuna.create_study( directionmaximize, sampleroptuna.samplers.TPESampler(seedSEED), pruneroptuna.pruners.MedianPruner(), ) study.optimize(objective, n_trials30, timeout300)优化过程类from optuna.visualization import ( plot_optimization_history, plot_intermediate_values, plot_edf, plot_timeline, ) plot_optimization_history(study) # 每轮目标值 累计最优值两条曲线 plot_intermediate_values(study) # 各 trial 的 epoch 级学习曲线被剪枝的 trial 也会显示到剪枝点 plot_edf(study) # 经验分布函数P(优化到某目标值) 的累积曲线 plot_timeline(study) # 时间线每个 trial 的横条按状态着色可观察并行/耗时plot_optimization_history额外支持error_bar: bool False用于展示带误差棒的统计量当target返回均值类指标时配合使用。从源码 optuna/visualization/_optimization_history.py#L50-L109 可以看到其数据层细节非COMPLETE状态的 trial 记为 NaN_ValueState.Incomplete保证 x 轴序号与trial.number对齐被剪枝的 trial 在图上留白累计最优值用np.minimum.accumulate/np.maximum.accumulate计算且在约束优化场景下只统计可行解trial.constraints全为 ≤0 才视为 Feasible不可行 trial 对 best 曲线贡献 ±inf指定了target时不绘制 best 曲线因为源码注释说明无法判断用户自定义目标的方向性。参数关系类from optuna.visualization import ( plot_contour, plot_slice, plot_parallel_coordinate, plot_rank, plot_param_importances, ) plot_contour(study) # 等高线图两两参数对 plot_contour(study, params[lr, n_layers]) plot_slice(study) # 每个参数一张子图参数值 vs 目标值 plot_parallel_coordinate(study) # 平行坐标高维参数 vs 目标值 plot_rank(study) # 两两参数散点点色深浅 目标值排序 plot_param_importances(study) # 超参数重要性fANOVA以plot_contour为例文档站示例 docs/visualization_examples/optuna.visualization.plot_contour.py 给出了最小可运行版本import optuna from plotly.io import show def objective(trial): x trial.suggest_float(x, -100, 100) y trial.suggest_categorical(y, [-1, 0, 1]) return x**2 y sampler optuna.samplers.TPESampler(seed10) study optuna.create_study(samplersampler) study.optimize(objective, n_trials30) fig optuna.visualization.plot_contour(study, params[x, y]) show(fig)其中y是类别参数、x是连续参数该示例也印证了等高线图支持混合类型参数。多目标 Study 使用这些函数时同样需要target参数例如plot_edf(study, targetlambda t: t.values[0], target_nameaccuracy)具体可选参数以各函数 docstring 为准。多目标与专用图from optuna.visualization import ( plot_pareto_front, plot_hypervolume_history, plot_terminator_improvement, ) plot_pareto_front(study) # 多目标 Pareto 前沿散点 plot_hypervolume_history(study) # hypervolume 随 trial 数增长曲线 plot_terminator_improvement(study) # 配合 optuna.terminator 使用的改善度量图plot_pareto_front是少数必须用于多目标 Study的函数单目标场景没有意义plot_hypervolume_history与参考文档 docs/source/reference/visualization/index.rst 同级教程中的多目标章节配合使用。Matplotlib 后端同样提供这三个函数见 optuna/visualization/matplotlib/init.py 的导出列表。自定义与保存图形教程明确说明Plotly 后端返回可编辑的Figure对象Matplotlib 后端返回Axes都可以用各自库的 API 二次加工。教程中的标准示例是替换标题与轴标签fig plot_intermediate_values(study) fig.update_layout( titleHyperparameter optimization for FashionMNIST classification, xaxis_titleEpoch, yaxis_titleValidation Accuracy, )保存方式对应各自生态Plotly 用fig.write_html(fig.html)/fig.write_image(fig.png)后者需要 kaleidoMatplotlib 用plt.savefig(fig.png)。源码级实现剖析数据层与渲染层解耦从源码结构看optuna/visualization的实现分为两层这也是双后端同构能成立的关键Plotly 后端文件里混放数据层 渲染层。以 optuna/visualization/_optimization_history.py 为例模块顶层定义了与渲染无关的数据结构_ValueStateFeasible/Infeasible/Incomplete、_ValuesInfo、_OptimizationHistoryInfo以及纯数据函数_get_optimization_history_info_list(study, target, target_name, error_bar)——它遍历study.get_trials()处理非完成状态、约束可行性、best 累积并调用_check_plot_args做参数校验随后的plot_optimization_history才基于 Plotly 的go对象渲染。Matplotlib 后端直接复用 Plotly 文件中的数据层。optuna/visualization/matplotlib/_optimization_history.py#L9-L11 直接from optuna.visualization._optimization_history import _get_optimization_history_info_list然后只负责把 info_list 画成 Matplotlib 图形。其plot_optimization_history签名与 Plotly 版完全一致study, *, targetNone, target_nameObjective Value, error_barFalse返回Axesoptuna/visualization/matplotlib/_optimization_history.py#L30-L67。视觉风格对齐。Matplotlib 渲染时显式plt.style.use(ggplot)并选用tab10色图源码注释写明为接近 plotly 的输出效果optuna/visualization/matplotlib/_optimization_history.py#L74-L80保证同一 Study 在两个后端下的读数体验一致。悬停信息统一序列化。Plotly 图的 hovertext 由_make_hovertextoptuna/visualization/_utils.py#L155-L167生成内容是 trial 的 number/values/params/user_attrs 的 JSON 摘要非 JSON 兼容值会被_make_json_compatible转成字符串——因此你用trial.set_user_attr写入的元数据会原样出现在图形的悬停提示里。这些实现对应的测试集中在 tests/visualization_tests/ 目录含 Plotly 与 Matplotlib 两组测试如test_optimization_history.py、test_contour.py修改参数语义时可用于回归验证。文档站的生成机制理解 reference 页的来源如果你本地构建过文档docs/Makefile可以看到 docs/source/conf.py 中的 Sphinx-Gallery 配置把四个示例目录分别映射到四个画廊输出目录sphinx_gallery_conf { examples_dirs: [ ../../tutorial/10_key_features, ../../tutorial/20_recipes, ../visualization_examples, ../visualization_matplotlib_examples, ], gallery_dirs: [ tutorial/10_key_features, tutorial/20_recipes, reference/visualization/generated, reference/visualization/matplotlib/generated, ], ... image_scrapers: (matplotlib, plotly.io._sg_scraper.plotly_sg_scraper), }docs/visualization_examples/下每个脚本命名与函数一一对应optuna.visualization.plot_contour.py等gallery 执行它们并把输出图通过 plotly/matplotlib image scraper 抓取渲染进generated/index.rst——这正是index.rst第一行include的文件Matplotlib 侧同理docs/visualization_matplotlib_examples/ 生成reference/visualization/matplotlib/generated/index.rst这两个 generated 目录在构建后被exclude_patterns排除出常规文档索引仅作为 include 片段使用plotly_io默认渲染器被设为sphinx_gallery/sphinx_gallery_png保证文档里内嵌的是静态 PNG 而非交互式 HTML。理解这一点后你在浏览线上参考文档时看到的函数列表 缩略图 源码折叠块其权威来源就是docs/visualization_examples/中这些可独立运行的脚本。实操要点与常见坑汇总多目标必须传target否则在_check_plot_args处抛ValueError指定target时建议同时更新target_name否则会有默认轴名警告。inf/nan 目标值会被静默剔除仅 warning 日志绘图前建议先study.get_trials()检查plot_optimization_history中非 COMPLETE trial 表现为断点而非连线。指定了target时plot_optimization_history不画 best 曲线源码明确无法推断用户目标的方向。JupyterLab 中 Plotly 图默认不显示需配置 Plotly 的 JupyterLab 渲染支持。后端切换零成本仅需替换 import 前缀为optuna.visualization.matplotlib函数名、参数、返回可编辑对象三要素不变用is_available()做环境探测。并行度观察plot_timeline的横条重叠/空隙直接反映study.optimize(n_jobs...)的实际并行情况是分布式/多进程调优的实用工具。约束优化场景best 曲线只由可行解更新不可行 trial 以独立状态着色区分_ValueState.Infeasible。关键文件索引内容路径参考文档入口Plotly 后端docs/source/reference/visualization/index.rst参考文档子页Matplotlib 后端docs/source/reference/visualization/matplotlib/index.rstPlotly 后端 APIoptuna/visualization/init.pyMatplotlib 后端 APIoptuna/visualization/matplotlib/init.py共享工具is_available/参数校验/过滤optuna/visualization/_utils.py优化历史数据层optuna/visualization/_optimization_history.pyMatplotlib 渲染层示例optuna/visualization/matplotlib/_optimization_history.py函数级示例脚本docs/visualization_examples/可视化教程全流程tutorial/10_key_features/005_visualization.py文档构建配置docs/source/conf.py测试tests/visualization_tests/【免费下载链接】optunaA hyperparameter optimization framework项目地址: https://gitcode.com/GitHub_Trending/op/optuna创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考