超参数自动调参库介绍(超参数选择)
itomcoil 2025-03-14 18:07 26 浏览
前言
今天给大家聊聊机器学习领域中,存在的一些自动化超参数寻优库。优化基模型选择的耳熟能详的支持向量机模型,就用不同的自动化寻参工具来实现SVM参数的优化。
介绍
Auto-Sklearn
Auto-Sklearn 是一个用于自动特征工程和机器学习模型选择的库,是 Scikit-Learn 的扩展。这个库因为不支持windows环境,所以这里就暂时不讲解了。
Optuna
Optuna 是一个为机器学习提供最优化超参数的框架。它包括了对未知搜索空间的支持,以及针对计算资源进行高效优化的能力。
import optuna
from sklearn import datasets, svm
from sklearn.model_selection import train_test_split
import pickle
# 加载数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 划分训练集和验证集
X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.25, random_state=0)
# 定义目标函数
def objective(trial):
C = trial.suggest_loguniform('C', 1e-10, 1e10)
gamma = trial.suggest_loguniform('gamma', 1e-10, 1e10)
classifier_obj = svm.SVC(C=C, gamma=gamma)
classifier_obj.fit(X_train, y_train)
return classifier_obj.score(X_valid, y_valid)
# 创建一个study对象并找到最佳参数
study = optuna.create_study(direction='maximize')
study.optimize(objective, n_trials=100)
# 输出最佳参数
print('Best trial:')
trial = study.best_trial
print('Value: ', trial.value)
print('Params: ')
for key, value in trial.params.items():
print('{}: {}'.format(key, value))
# 使用最佳参数创建模型
best_params = study.best_params
best_model = svm.SVC(**best_params)
best_model.fit(X_train, y_train)
# 保存模型
with open('best_model.pkl', 'wb') as f:
pickle.dump(best_model, f)
Hyperopt
Hyperopt 是一个用于优化超参数的库。它使用了贝叶斯优化方法,并支持并行计算。
from sklearn import datasets, svm
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from hyperopt import hp, fmin, tpe, Trials, STATUS_OK
import pickle
# 加载数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 划分训练集和验证集
X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.25, random_state=0)
# 定义目标函数
def objective(params):
classifier_obj = svm.SVC(**params)
classifier_obj.fit(X_train, y_train)
pred = classifier_obj.predict(X_valid)
return {'loss': -accuracy_score(y_valid, pred), 'status': STATUS_OK}
# 定义搜索空间
space = {
'C': hp.loguniform('C', -10, 10),
'gamma': hp.loguniform('gamma', -10, 10)
}
# 执行优化
trials = Trials()
best = fmin(fn=objective, space=space, algo=tpe.suggest, max_evals=100, trials=trials)
# 输出最佳参数
print('Best: ', best)
# 使用最佳参数创建模型
best_model = svm.SVC(**best)
best_model.fit(X_train, y_train)
# 保存模型
with open('best_model.pkl', 'wb') as f:
pickle.dump(best_model, f)
Tune
Ray Tune 是一个用于深度学习和强化学习的库。它支持多种搜索算法和早停策略。接下来还是以SVM优化举例。
from sklearn import datasets, svm
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from ray import tune
# 加载数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 划分训练集和验证集
X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.25, random_state=0)
def train_model(config):
# 使用传入的参数创建模型
model = svm.SVC(**config)
model.fit(X_train, y_train)
# 验证模型并返回准确率
predictions = model.predict(X_valid)
acc = accuracy_score(y_valid, predictions)
tune.report(accuracy=acc)
# 定义搜索空间
search_space = {
'C': tune.loguniform(1e-10, 1e10),
'gamma': tune.loguniform(1e-10, 1e10)
}
# 执行优化
analysis = tune.run(train_model, config=search_space, num_samples=100, metric='accuracy', mode='max')
# 输出最佳参数
print('Best config: ', analysis.best_config)
# 使用最佳参数创建模型
best_model = svm.SVC(**analysis.best_config)
best_model.fit(X_train, y_train)
# 保存模型
import pickle
with open('best_model.pkl', 'wb') as f:
pickle.dump(best_model, f)
Keras Tuner
Keras Tuner 是一个专门为 Keras 库设计的超参数调优框架。所以不能使用它来优化svm了,就随便举个例子。
from tensorflow import keras
from kerastuner.tuners import RandomSearch
from sklearn import datasets
# 加载数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 划分训练集和验证集
X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.25, random_state=0)
def build_model(hp):
model = keras.Sequential()
model.add(keras.layers.Dense(units=hp.Int('units', min_value=32, max_value=512, step=32), activation='relu'))
model.add(keras.layers.Dense(10, activation='softmax'))
model.compile(optimizer=keras.optimizers.Adam(hp.Choice('learning_rate', values=[1e-2, 1e-3, 1e-4])), loss='categorical_crossentropy', metrics=['accuracy'])
return model
tuner = RandomSearch(build_model, objective='val_accuracy', max_trials=5)
tuner.search(X_train, y_train, epochs=5, validation_data=(X_valid, y_valid))
TPOT (Tree-based Pipeline Optimization Tool)
TPOT 使用遗传算法优化机器学习管道。
from tpot import TPOTClassifier
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
# 加载数据
digits = load_digits()
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target,
train_size=0.75, test_size=0.25)
# 设置 SVM 的配置字典
tpot_config = {
'sklearn.svm.SVC': {
'C': [1.0, 10.0, 100.0],
'kernel': ['linear', 'poly', 'rbf'],
'degree': [1, 2, 3, 4, 5],
'gamma': ['scale', 'auto']
},
}
# 创建 TPOT 分类器实例
pipeline_optimizer = TPOTClassifier(generations=5, population_size=20, verbosity=2,
config_dict=tpot_config)
# 在数据上训练 TPOT 分类器
pipeline_optimizer.fit(X_train, y_train)
# 打印最佳模型管道
print(pipeline_optimizer.fitted_pipeline_)
# 使用测试集评价模型性能
print(pipeline_optimizer.score(X_test, y_test))
Spearmint
Spearmint 是一个贝叶斯优化库,它将问题视作黑盒函数优化问题。
from sklearn import svm, datasets
from sklearn.model_selection import cross_val_score
# 加载数据集
iris = datasets.load_iris()
def svm_cv(C, kernel):
# 创建一个 SVM 分类器
svc = svm.SVC(C=C, kernel=kernel)
# 使用交叉验证评估模型
scores = cross_val_score(svc, iris.data, iris.target, cv=5)
# 返回平均精度的负值(因为 Spearmint 进行最小化)
return -scores.mean()
然后,创建一个 JSON 配置文件 (例如,config.json) 来指定优化的参数:
[
{
"name": "C",
"type": "float",
"min": 0.1,
"max": 100.0
},
{
"name": "kernel",
"type": "enum",
"options": ["linear", "poly", "rbf", "sigmoid"]
}
]
接着,在命令行中运行 Spearmint:
spearmint svm.py --config config.json
SMAC (Sequential Model-based Algorithm Configuration)
SMAC 通常用于优化算法的配置,但也可以用于机器学习模型的超参数优化。
import numpy as np
from sklearn import datasets, svm
from sklearn.model_selection import cross_val_score
from smac.configspace import ConfigurationSpace
from ConfigSpace.hyperparameters import CategoricalHyperparameter, UniformFloatHyperparameter
from smac.scenario.scenario import Scenario
from smac.facade.smac_hpo_facade import SMAC4HPO
# 加载数据
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 定义一个目标函数
def svm_from_cfg(cfg):
# 从配置中获取SVM参数
C = cfg["C"]
kernel = cfg["kernel"]
# 创建并评估 SVM 分类器
clf = svm.SVC(C=C, kernel=kernel, random_state=42)
scores = cross_val_score(clf, X, y, cv=5)
# SMAC 贝叶斯优化是最小化目标函数,因此我们取负值,即 - mean_accuracy
return -1 * np.mean(scores)
# 创建配置空间
cs = ConfigurationSpace()
# 添加相关的超参数
C = UniformFloatHyperparameter("C", 0.001, 100.0, default_value=1.0)
kernel = CategoricalHyperparameter("kernel", ["linear", "poly", "rbf", "sigmoid"], default_value="rbf")
cs.add_hyperparameters([C, kernel])
# 定义 scenario
scenario = Scenario({"run_obj": "quality",
"runcount-limit": 50,
"cs": cs,
"deterministic": "true"
})
# 创建一个 SMAC 对象
smac = SMAC4HPO(scenario=scenario, rng=np.random.default_rng(42),
tae_runner=svm_from_cfg)
# 运行优化过程
incumbent = smac.optimize()
# 输出优化结果
print("Optimized Value: %.2f" % -svm_from_cfg(incumbent))
print("Optimized Parameters: ", incumbent.get_dictionary())
FLAML
旨在自动化机器学习任务的各个方面,包括特征工程、模型选择和超参数调优。FLAML内置了很多集成模型和线性模型方法,但是不包括SVM,所以这里我们讲解怎么自定义模型。
from flaml import AutoML
from sklearn.datasets import load_digits
# 加载数据集
digits = load_digits()
X_train, y_train = digits.data, digits.target
# 初始化AutoML实例
automl = AutoML()
# 创建并添加一个新的学习器
class MySVMEstimator(LGBMEstimator):
base_class = 'sklearn.svm.SVC'
automl.add_learner(learner_name='svm', learner_class=MySVMEstimator)
# 设置参数
settings = {
"time_budget": 30, # 总共运行时间(秒)
"metric": 'accuracy', # 评价指标
"task": 'classification', # 任务类型
"estimator_list": ['svm'], # 指定待调整模型
"log_file_name": 'flaml.log', # 输出日志文件
}
# 进行自动化的机器学习搜索
automl.fit(X_train=X_train, y_train=y_train, **settings)
# 检查是否选择了SVM模型
best_model = automl.model
if isinstance(best_model, MySVMEstimator):
print("Selected model is SVM.")
print("Best hyperparameters:", automl.best_config)
print('Best accuracy on training data: {0:.4g}'.format(1-automl.best_loss))
else:
print(f"Selected model is not SVM. It's {type(best_model)}.")
我试了一下,发现并不是优化的svm参数,我看了官网,说FLAML可能会选择它认为最好的模型,这可能包括其他类型的模型,例如集成模型。这是因为FLAML旨在自动化地找出最佳的模型和超参数。
相关推荐
- python创建文件夹,轻松搞定,喝咖啡去了
-
最近经常在录视频课程,一个课程下面往往有许多小课,需要分多个文件夹来放视频、PPT和案例,这下可好了,一个一个手工创建,手酸了都做不完。别急,来段PYTHON代码,轻松搞定,喝咖啡去了!import...
- 如何编写第一个Python程序_pycharm写第一个python程序
-
一、第一个python程序[掌握]python:python解释器,将python代码解释成计算机认识的语言pycharm:IDE(集成开发环境),写代码的一个软件,集成了写代码,...
- Python文件怎么打包为exe程序?_python3.8打包成exe文件
-
PyInstaller是一个Python应用程序打包工具,它可以将Python程序打包为单个独立可执行文件。要使用PyInstaller打包Python程序,需要在命令行中使用py...
- 官方的Python环境_python环境版本
-
Python是一种解释型编程开发语言,根据Python语法编写出来的程序,需要经过Python解释器来进行执行。打开Python官网(https://www.python.org),找到下载页面,选择...
- [编程基础] Python配置文件读取库ConfigParser总结
-
PythonConfigParser教程显示了如何使用ConfigParser在Python中使用配置文件。文章目录1介绍1.1PythonConfigParser读取文件1.2Python...
- Python打包exe软件,用这个库真的很容易
-
初学Python的人会觉得开发一个exe软件非常复杂,其实不然,从.py到.exe文件的过程很简单。你甚至可以在一天之内用Python开发一个能正常运行的exe软件,因为Python有专门exe打包库...
- 2025 PyInstaller 打包说明(中文指南),python 打包成exe 都在这里
-
点赞标记,明天就能用上这几个技巧!linux运维、shell、python、网络爬虫、数据采集等定定做,请私信。。。PyInstaller打包说明(中文指南)下面按准备→基本使用→常用...
- Python自动化办公应用学习笔记40—文件路径2
-
4.特殊路径操作用户主目录·获取当前用户的主目录路径非常常用:frompathlibimportPathhome_dir=Path.home()#返回当前用户主目录的Path对象...
- Python内置tempfile模块: 生成临时文件和目录详解
-
1.引言在Python开发中,临时文件和目录的创建和管理是一个常见的需求。Python提供了内置模块tempfile,用于生成临时文件和目录。本文将详细介绍tempfile模块的使用方法、原理及相关...
- python代码实现读取文件并生成韦恩图
-
00、背景今天战略解码,有同学用韦恩图展示各个产品线的占比,效果不错。韦恩图(Venndiagram),是在集合论数学分支中,在不太严格的意义下用以表示集合的一种图解。它们用于展示在不同的事物群组之...
- Python技术解放双手,一键搞定海量文件重命名,一周工作量秒搞定
-
摘要:想象一下,周五傍晚,办公室的同事们纷纷准备享受周末,而你,面对着堆积如山的文件,需要将它们的文件名从美国日期格式改为欧洲日期格式,这似乎注定了你将与加班为伍。但别担心,Python自动化办公来...
- Python路径操作的一些基础方法_python路径文件
-
带你走进@机器人时代Discover点击上面蓝色文字,关注我们Python自动化操作文件避开不了路径操作方法,今天我们来学习一下路径操作的一些基础。Pathlib库模块提供的路径操作包括路径的...
- Python爬取下载m3u8加密视频,原来这么简单
-
1.前言爬取视频的时候发现,现在的视频都是经过加密(m3u8),不再是mp4或者avi链接直接在网页显示,都是经过加密形成ts文件分段进行播放。今天就教大家如果通过python爬取下载m3u8加密视频...
- 探秘 shutil:Python 高级文件操作的得力助手
-
在Python的标准库中,shutil模块犹如一位技艺精湛的工匠,为我们处理文件和目录提供了一系列高级操作功能。无论是文件的复制、移动、删除,还是归档与解压缩,shutil都能以简洁高效的方式完成...
- 怎么把 Python + Flet 开发的程序,打包为 exe ?这个方法很简单!
-
前面用Python+Flet开发的“我的计算器v3”,怎么打包为exe文件呢?这样才能分发给他人,直接“双击”运行使用啊!今天我给大家分享一个简单的、可用的,把Flet开发的程序打包为...
- 一周热门
- 最近发表
-
- python创建文件夹,轻松搞定,喝咖啡去了
- 如何编写第一个Python程序_pycharm写第一个python程序
- Python文件怎么打包为exe程序?_python3.8打包成exe文件
- 官方的Python环境_python环境版本
- [编程基础] Python配置文件读取库ConfigParser总结
- Python打包exe软件,用这个库真的很容易
- 2025 PyInstaller 打包说明(中文指南),python 打包成exe 都在这里
- Python自动化办公应用学习笔记40—文件路径2
- Python内置tempfile模块: 生成临时文件和目录详解
- python代码实现读取文件并生成韦恩图
- 标签列表
-
- ps图案在哪里 (33)
- super().__init__ (33)
- python 获取日期 (34)
- 0xa (36)
- super().__init__()详解 (33)
- python安装包在哪里找 (33)
- linux查看python版本信息 (35)
- python怎么改成中文 (35)
- php文件怎么在浏览器运行 (33)
- eval在python中的意思 (33)
- python安装opencv库 (35)
- python div (34)
- sticky css (33)
- python中random.randint()函数 (34)
- python去掉字符串中的指定字符 (33)
- python入门经典100题 (34)
- anaconda安装路径 (34)
- yield和return的区别 (33)
- 1到10的阶乘之和是多少 (35)
- python安装sklearn库 (33)
- dom和bom区别 (33)
- js 替换指定位置的字符 (33)
- python判断元素是否存在 (33)
- sorted key (33)
- shutil.copy() (33)