Sør*_*sen 5 python optimization bayesian hyperopt
我正在为我的主项目演示 hyperopt 的 TPE 算法,但似乎无法让算法收敛。根据我从原始论文和 YouTube讲座中了解到的,TPE 算法按以下步骤工作:
(下文中,x=超参数,y=损失)
我已经在 python 中对目标函数 f(x) = x^2 实现了这一点,但算法无法收敛到最小值。
import numpy as np
import scipy as sp
from matplotlib import pyplot as plt
from scipy.stats import gaussian_kde
def objective_func(x):
return x**2
def measure(x):
noise = np.random.randn(len(x))*0
return x**2+noise
def split_meassures(x_obs,y_obs,gamma=1/2):
#split x and y observations into two sets and return a seperation threshold (y_star)
size = int(len(x_obs)//(1/gamma))
l = {'x':x_obs[:size],'y':y_obs[:size]}
g = {'x':x_obs[size:],'y':y_obs[size:]}
y_star = (l['y'][-1]+g['y'][0])/2
return l,g,y_star
#sample objective function values for ilustration
x_obj = np.linspace(-5,5,10000)
y_obj = objective_func(x_obj)
#start by sampling a parameter search history
x_obs = np.linspace(-5,5,10)
y_obs = measure(x_obs)
nr_iterations = 100
for i in range(nr_iterations):
#sort observations according to loss
sort_idx = y_obs.argsort()
x_obs,y_obs = x_obs[sort_idx],y_obs[sort_idx]
#split sorted observations in two groups (l and g)
l,g,y_star = split_meassures(x_obs,y_obs)
#aproximate distributions for both groups using kernel density estimation
kde_l = gaussian_kde(l['x']).evaluate(x_obj)
kde_g = gaussian_kde(g['x']).evaluate(x_obj)
#define our evaluation measure for sampling a new point
eval_measure = kde_g/kde_l
if i%10==0:
plt.figure()
plt.subplot(2,2,1)
plt.plot(x_obj,y_obj,label='Objective')
plt.plot(x_obs,y_obs,'*',label='Observations')
plt.plot([-5,5],[y_star,y_star],'k')
plt.subplot(2,2,2)
plt.plot(x_obj,kde_l)
plt.subplot(2,2,3)
plt.plot(x_obj,kde_g)
plt.subplot(2,2,4)
plt.semilogy(x_obj,eval_measure)
plt.draw()
#find point to evaluate and add the new observation
best_search = x_obj[np.argmin(eval_measure)]
x_obs = np.append(x_obs,[best_search])
y_obs = np.append(y_obs,[measure(np.asarray([best_search]))])
plt.show()
Run Code Online (Sandbox Code Playgroud)
我怀疑发生这种情况是因为我们不断在最确定的地方采样,从而使 l(x) 在这一点附近变得越来越窄,这根本不会改变我们采样的位置。那么我的理解哪里还不够呢?
所以,我还在学习TPE。但这段代码存在两个问题:
这段代码只会评估一些独特的点。因为最佳位置是根据核密度函数推荐的最佳位置计算出来的,但代码无法对搜索空间进行探索。例如,获取函数的作用。
因为这段代码只是将新的观察结果附加到 x 和 y 列表中。它增加了很多重复项。重复项会导致一组倾斜的观察结果,从而导致非常奇怪的分裂,您可以在后面的图中轻松看到这一点。开始eval_measure
时与目标函数类似,但后来有所不同。
如果删除重复项x_obs
,y_obs
就可以解决问题。2. 然而,第一个问题只能通过添加某种探索搜索空间的方法来解决。