hyperparameter-tuning
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "hyperparameter-tuning" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-2a68da6833f7918a84a6cbfb139a003408c78430b3221d701d74d147a0cfc869. Verify the upstream source and version against https://skillhub.cn/skills/org-02qudk26/hyperparameter-tuning before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
skillhub.cn
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
Use grid search, random search, Bayesian optimization, and Hyperband methods to find and tune model hyperparameters within a given compute budget to maximize machine learning model performance.
Introduction source: third_party · org-02qudk26 · 1.0.0 Reference
SkillPi interpretation
- Tasks
- Translation pending; see source documentation.
- Audience
- Not specified in the source documentation.
- Inputs and outputs
- Not specified in the source documentation.
- Software, accounts and paid services
- Not specified in the source documentation.
- Limits and differences
- Not specified in the source documentation.
- Testing
- Not tested
Browse files
Frontmatter
name: hyperparameter-tuning
description: 使用网格搜索、随机搜索、贝叶斯优化和 Hyperband,在算力预算内最大化模型性能,优化机器学习模型超参数。
license: MIT
metadata:
author: AI Agent Skills
version: 1.0.0超参数调优
本技能让 AI Agent 系统地搜索机器学习模型的最优超参数配置。涵盖定义搜索空间、选择搜索策略(网格、随机、贝叶斯、Hyperband)、用交叉验证运行试验、应用早停以剪枝不良配置,以及分析结果以识别表现最佳的参数。Agent 在探索与利用之间取得平衡,在给定的算力预算内找到强劲的配置。
工作流
-
定义搜索空间: 指定每个超参数的类型(类别型、整数型、浮点型)和范围。对跨越数量级的参数(例如学习率从 1e-5 到 1e-1)使用对数均匀分布。将相关参数分组,并定义条件搜索空间——某些参数仅在其他参数取特定值时才适用。
-
选择搜索策略: 根据算力预算和搜索空间大小选择调优算法。网格搜索是穷举式的,但仅适用于小空间。随机搜索是一个强大的基线,扩展性更好。贝叶斯优化(树结构 Parzen 估计器或高斯过程)对昂贵的评估最具样本效率。Hyperband 和 ASHA 将早停与随机搜索结合,适用于深度学习工作负载。
-
配置评估: 对中至小型数据集设置 k 折交叉验证(通常为 5 折)以获得可靠的性能估计。对大型数据集或昂贵模型,使用单一留出验证集。定义要优化的目标度量(例如验证集 F1、AUC-ROC、RMSE)以及是最小化还是最大化它。
-
运行带剪枝的试验: 执行搜索,尽可能并行启动试验。启用剪枝,基于中间结果(例如训练几个 epoch 后)提前终止表现不佳的试验,为更有希望的配寘释放算力。
-
分析并选择结果: 检查优化历史,了解哪些超参数最重要(重要性分析)。用等高线图或平行坐标图可视化参数交互。选择最佳配置,并用这些参数在整个训练集上重新训练最终模型。
支持技术
- 框架: Optuna、Ray Tune、scikit-learn GridSearchCV/RandomizedSearchCV、Hyperopt、Keras Tuner
- 剪枝算法: 中位数剪枝、Hyperband(逐次减半)、ASHA
- 贝叶斯方法: TPE(树结构 Parzen 估计器)、GP(高斯过程)、CMA-ES
- 可视化: Optuna 可视化(plotly)、TensorBoard HParams、Weights & Biases Sweeps
- 分布式执行: Ray Tune 集群、带分布式存储(MySQL、PostgreSQL)的 Optuna
使用方式
为 Agent 提供模型、数据集、待调优的超参数及其范围、算力预算(试验次数或挂钟时间),以及目标度量。Agent 将执行调优工作流,并返回最佳超参数配置及性能分析。
示例
示例 1:调优随机森林的 Optuna 研究
import optuna
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score
import numpy as np
X, y = load_breast_cancer(return_X_y=True)
def objective(trial):
params = {
"n_estimators": trial.suggest_int("n_estimators", 50, 500, step=50),
"max_depth": trial.suggest_int("max_depth", 3, 30),
"min_samples_split": trial.suggest_int("min_samples_split", 2, 20),
"min_samples_leaf": trial.suggest_int("min_samples_leaf", 1, 10),
"max_features": trial.suggest_categorical("max_features", ["sqrt", "log2", None]),
"criterion": trial.suggest_categorical("criterion", ["gini", "entropy"]),
}
clf = RandomForestClassifier(**params, random_state=42, n_jobs=-1)
scores = cross_val_score(clf, X, y, cv=5, scoring="f1")
return scores.mean()
study = optuna.create_study(direction="maximize", sampler=optuna.samplers.TPESampler(seed=42))
study.optimize(objective, n_trials=100, show_progress_bar=True)
print(f"Best F1: {study.best_value:.4f}")
print(f"Best params: {study.best_params}")
# Visualization
fig_importance = optuna.visualization.plot_param_importances(study)
fig_history = optuna.visualization.plot_optimization_history(study)
fig_contour = optuna.visualization.plot_contour(study, params=["n_estimators", "max_depth"])
示例 2:带早停的 Ray Tune 神经网络
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset, random_split
from ray import tune
from ray.tune.schedulers import ASHAScheduler
from ray.air import session
import numpy as np
def train_nn(config):
X = torch.randn(2000, 20)
y = (X[:, 0] + X[:, 1] * 2 > 0).long()
dataset = TensorDataset(X, y)
train_set, val_set = random_split(dataset, [1600, 400])
train_loader = DataLoader(train_set, batch_size=config["batch_size"], shuffle=True)
val_loader = DataLoader(val_set, batch_size=256)
model = nn.Sequential(
nn.Linear(20, config["hidden_size"]),
nn.ReLU(),
nn.Dropout(config["dropout"]),
nn.Linear(config["hidden_size"], config["hidden_size"] // 2),
nn.ReLU(),
nn.Linear(config["hidden_size"] // 2, 2),
)
optimizer = torch.optim.Adam(model.parameters(), lr=config["lr"], weight_decay=config["weight_decay"])
criterion = nn.CrossEntropyLoss()
for epoch in range(50):
model.train()
for xb, yb in train_loader:
loss = criterion(model(xb), yb)
optimizer.zero_grad()
loss.backward()
optimizer.step()
model.eval()
correct, total = 0, 0
with torch.no_grad():
for xb, yb in val_loader:
correct += (model(xb).argmax(1) == yb).sum().item()
total += yb.size(0)
session.report({"val_accuracy": correct / total})
search_space = {
"hidden_size": tune.choice([64, 128, 256]),
"lr": tune.loguniform(1e-4, 1e-1),
"dropout": tune.uniform(0.1, 0.5),
"batch_size": tune.choice([32, 64, 128]),
"weight_decay": tune.loguniform(1e-5, 1e-2),
}
scheduler = ASHAScheduler(max_t=50, grace_period=5, reduction_factor=3)
result = tune.run(
train_nn,
config=search_space,
num_samples=50,
scheduler=scheduler,
metric="val_accuracy",
mode="max",
resources_per_trial={"cpu": 2},
)
print(f"Best config: {result.best_config}")
print(f"Best val accuracy: {result.best_result['val_accuracy']:.4f}")
最佳实践
- 对学习率、权重衰减和正则化强度使用对数均匀分布,因为最优值往往跨越多个数量级。
- 从随机搜索开始,先快速识别搜索空间中有希望的区域,再切换到贝叶斯优化进行细粒度探索。
- 启用早停 / 剪枝,以避免在计算上浪费在几个 epoch 后就明显落后的配置上。
- 始终使用交叉验证来获取小数据集(< 50k 样本)上的目标分数,以减少性能估计的方差,并避免对单一验证切分的过拟合。
- 调优后运行超参数重要性分析,以了解哪些参数真正重要——通常只有 2–3 个参数驱动了大部分性能差异。
- 预先设定算力预算(试验次数、GPU 小时数或挂钟时间),并选择能最佳利用该预算的搜索策略。
边缘情况
- 巨大的搜索空间(> 10 维): 贝叶斯优化在高维下退化。先用随机搜索或 Hyperband 做第一轮,再对第一轮识别出的前 3–5 个最重要参数运行贝叶斯优化。
- 有噪声的目标: 当交叉验证分数方差很大时,单次试验结果不可靠。在比较配置前,增加 CV 折数、使用重复 k 折,或在多个随机种子上取平均。
- 相关超参数: 某些超参数强烈交互(例如学习率和批大小)。使用 Optuna 的等高线图或 fANOVA 重要性来检测交互,并考虑对相关组一起调优。
- 昂贵的评估(每次试验 > 1 小时): 使用 Hyperband 等多保真度方法,先用小预算训练,只将有望的配置提升到完整训练。也可考虑用代理基准或较小的代理数据集做初步筛选。
- 类别型爆炸: 当多个类别型超参数造成组合爆炸时,使用条件搜索空间来剪枝无效组合,并缩减有效空间大小。
Current listing version
1.0.0
Safety and assessment details
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 提供完整的超参数调优工作流,覆盖搜索空间定义、策略选择、评估配置、剪枝试验和结果分析
- 支持主流框架(Optuna、Ray Tune、scikit-learn、Hyperopt、Keras Tuner),具备广泛实用价值
- 包含具体可运行的代码示例,帮助用户快速上手
Highlights
- 触发词精准覆盖网格搜索、随机搜索、贝叶斯优化、Hyperband 等核心方法
- description 完整清晰,边界明确,不易与其他 Skill 混淆
Areas to improve
-
缺少 When to Use 显式章节 Reported severity: Minor
文档结构完整但未设置显式的 When to Use 章节
Recommendation: 建议在使用方式章节前增加 When to Use 显式标题,提升结构规范性
Highlights
- 工作流分5步清晰呈现,逻辑连贯
- 提供双框架示例(Optuna + Ray Tune),覆盖不同场景
- frontmatter 完整,包含许可证和元数据
Highlights
- 示例代码参数正确,可直接运行
- 边缘情况处理完善(高维空间、噪声目标、昂贵评估等)
- 推荐使用交叉验证和早停机制,提升结果可靠性
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
These common operations were not identified in the main document. This does not mean no permissions or risks exist.
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Not specified in the source documentation.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.