01. 基础教程
在本教程中,您将学习如何
- 定义搜索空间
- 优化目标函数
本教程介绍如何使用 HyperOpt 优化超参数,无需对 HyperOpt 中实现的任何算法有数学理解。
# Import HyperOpt Library
from hyperopt import tpe, hp, fmin
声明一个用于优化的目标函数。在本教程中,我们将优化一个名为 objective 的简单函数,它是一个简单的二次函数。
$$ y = (x-3)^2 + 2 $$
objective = lambda x: (x-3)**2 + 2
现在,让我们可视化这个目标函数。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-10, 10, 100)
y = objective(x)
fig = plt.figure()
plt.plot(x, y)
plt.show()

我们尝试通过改变超参数 $x$ 来优化目标函数。这就是为什么我们将为 $x$ 声明一个搜索空间。与搜索空间相关的函数实现在 hyperopt.hp 中。列表如下。
hp.randint(label, upper)或hp.randint(label, low, high)hp.uniform(label, low, high)hp.loguniform(label, low, high)hp.normal(label, mu, sigma)hp.lognormal(label, mu, sigma)hp.quniform(label, low, high, q)hp.qloguniform(label, low, high, q)hp.qnormal(label, mu, sigma, q)hp.qlognormal(label, mu, sigma, q)hp.choice(label, list)hp.pchoice(label, p_list)其中p_list是(概率, 选项)对的列表hp.uniformint(label, low, high, q)或hp.uniformint(label, low, high),因为q = 1.0
在本教程中,我们将使用最基本的 hp.uniform。
# Define the search space of x between -10 and 10.
space = hp.uniform('x', -10, 10)
现在,只剩下最后一步了。到目前为止,我们已经定义了一个目标函数,并为 $x$ 定义了搜索空间。现在我们可以通过搜索空间 $x$ 来寻找能够优化目标函数的值。HyperOpt 使用 fmin 执行此操作。
best = fmin(
fn=objective, # Objective Function to optimize
space=space, # Hyperparameter's Search Space
algo=tpe.suggest, # Optimization algorithm
max_evals=1000 # Number of optimization attempts
)
print(best)
100%|██████████| 1000/1000 [00:04<00:00, 228.56trial/s, best loss: 2.000001036046408]
{'x': 3.0010178636491283}
HyperOpt 找到的最优 $x$ 值约为 3.0。这非常接近 $y=(x-3)^2+2$ 的解。