我正在使用高斯进程,当我使用scikit-learn GP模块时,我很难使用gridsearchcv
创建和优化自定义内核。描述这个问题的最好方法是使用classic Mauna Loa example,其中适当的内核是使用已经定义的内核(如RBF
和RationalQuadratic
)的组合来构造的。在该示例中,自定义内核的参数没有被优化,而是被视为给定的参数。如果我想运行更一般的情况,希望使用交叉验证来估计这些超参数,该怎么办?我应该如何构建自定义内核,然后为网格搜索构建相应的param_grid
对象?
以一种非常天真的方式,我可以使用如下内容构建一个自定义内核:
def custom_kernel(a,ls,l,alpha,nl):
kernel = a*RBF(length_scale=ls) \
+ b*RationalQuadratic(length_scale=l,alpha=alpha) \
+ WhiteKernel(noise_level=nl)
return kernel
但是,当然不能使用GaussianProcessRegressor(kernel=custom_kernel(a,ls,l,alpha,nl))
从gridsearchcv
调用此函数。
this SO question提供了一种可能的解决方法,但是我想知道是否有比从头开始编写内核(以及它的超参数)更容易的方法来解决这个问题,因为我希望使用标准内核的组合,也有可能将它们混合在一起。
发布于 2020-02-28 16:54:11
这就是我得到的结果。它回答了这个问题,但是对于毛纳罗亚的例子来说,它真的很慢,然而,这可能是一个很难处理的数据集:
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.model_selection import GridSearchCV
from sklearn.gaussian_process.kernels import ConstantKernel,RBF,WhiteKernel,RationalQuadratic,ExpSineSquared
import numpy as np
from sklearn.datasets import fetch_openml
# from https://scikit-learn.org/stable/auto_examples/gaussian_process/plot_gpr_co2.html
def load_mauna_loa_atmospheric_co2():
ml_data = fetch_openml(data_id=41187)
months = []
ppmv_sums = []
counts = []
y = ml_data.data[:, 0]
m = ml_data.data[:, 1]
month_float = y + (m - 1) / 12
ppmvs = ml_data.target
for month, ppmv in zip(month_float, ppmvs):
if not months or month != months[-1]:
months.append(month)
ppmv_sums.append(ppmv)
counts.append(1)
else:
# aggregate monthly sum to produce average
ppmv_sums[-1] += ppmv
counts[-1] += 1
months = np.asarray(months).reshape(-1, 1)
avg_ppmvs = np.asarray(ppmv_sums) / counts
return months, avg_ppmvs
X, y = load_mauna_loa_atmospheric_co2()
# Kernel with parameters given in GPML book
k1 = ConstantKernel(constant_value=66.0**2) * RBF(length_scale=67.0) # long term smooth rising trend
k2 = ConstantKernel(constant_value=2.4**2) * RBF(length_scale=90.0) \
* ExpSineSquared(length_scale=1.3, periodicity=1.0) # seasonal component
# medium term irregularity
k3 = ConstantKernel(constant_value=0.66**2) \
* RationalQuadratic(length_scale=1.2, alpha=0.78)
k4 = ConstantKernel(constant_value=0.18**2) * RBF(length_scale=0.134) \
+ WhiteKernel(noise_level=0.19**2) # noise terms
kernel_gpml = k1 + k2 + k3 + k4
gp = GaussianProcessRegressor(kernel=kernel_gpml)
# print parameters
print(gp.get_params())
param_grid = {'alpha': np.logspace(-2, 4, 5),
'kernel__k1__k1__k1__k1__constant_value': np.logspace(-2, 4, 5),
'kernel__k1__k1__k1__k2__length_scale': np.logspace(-2, 2, 5),
'kernel__k2__k2__noise_level':np.logspace(-2, 1, 5)
}
grid_gp = GridSearchCV(gp,cv=5,param_grid=param_grid,n_jobs=4)
grid_gp.fit(X, y)
对我有帮助的是,首先将模型初始化为gp = GaussianProcessRegressor(kernel=kernel_gpml)
,然后使用get_params
属性来获得模型超参数的列表。
最后,我注意到在他们的book中,拉斯穆森和威廉姆斯似乎使用了留下一个交叉验证来调优超参数。
https://stackoverflow.com/questions/58938819
复制相似问题