这是一个简单的代码实现,在Python的scikit-learn中我使用高斯过程回归(GPR)进行二维输入(即x1
和x2
上的网格)和1-尺寸输出(y
)。
import numpy as np
from matplotlib import pyplot as plt
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, ConstantKernel as C
from mpl_toolkits.mplot3d import Axes3D
# Example independent variable (observations)
X = np.array([[0.,0.], [1.,0.], [2.,0.], [3.,0.], [4.,0.],
[5.,0.], [6.,0.], [7.,0.], [8.,0.], [9.,0.], [10.,0.],
[11.,0.], [12.,0.], [13.,0.], [14.,0.],
[0.,1.], [1.,1.], [2.,1.], [3.,1.], [4.,1.],
[5.,1.], [6.,1.], [7.,1.], [8.,1.], [9.,1.], [10.,1.],
[11.,1.], [12.,1.], [13.,1.], [14.,1.],
[0.,2.], [1.,2.], [2.,2.], [3.,2.], [4.,2.],
[5.,2.], [6.,2.], [7.,2.], [8.,2.], [9.,2.], [10.,2.],
[11.,2.], [12.,2.], [13.,2.], [14.,2.]])#.T
# Example dependent variable (observations) - noiseless case
y = np.array([4.0, 3.98, 4.01, 3.95, 3.9, 3.84,3.8,
3.73, 2.7, 1.64, 0.62, 0.59, 0.3,
0.1, 0.1,
4.4, 3.9, 4.05, 3.9, 3.5, 3.4,3.3,
3.23, 2.6, 1.6, 0.6, 0.5, 0.32,
0.05, 0.02,
4.0, 3.86, 3.88, 3.76, 3.6, 3.4,3.2,
3.13, 2.5, 1.6, 0.55, 0.51, 0.23,
0.11, 0.01])
x1 = np.linspace(0, 14, 20)
x2 = np.linspace(0, 5, 100)
i = 0
inputs_x = []
while i < len(x1):
j = 0
while j < len(x2):
inputs_x.append([x1[i],x2[j]])
j = j + 1
i = i + 1
inputs_x_array = np.array(inputs_x)
# Instantiate a Gaussian Process model
kernel = C(1.0, (1e-3, 1e3)) * RBF((1e-2, 1e2), (1e-2, 1e2))
gp = GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=20)
gp.fit(X, y.reshape(-1,1)) #removing reshape results in a different error
y_pred, sigma = gp.predict(inputs_x_array, return_std=True)
它可以工作,但是在定义内核时,如何确保为不同的输入(即x1
和x2
)设置不同的超参数(例如,不同的标度长度)?在上面的示例中,使用的标准内核是径向基函数(RBF),尽管有两个输入维,它似乎具有单个长度比例。但是如何训练该内核(或自定义内核,例如双曲正切)以说明不同输入维的不同超参数呢?
答案 0 :(得分:4)
您将需要各向异性内核,目前只有sklearn中的几个内核支持。 RBF是这样的示例,您可以在其中提供列表作为length_scale
参数的输入。例如,RBF(length_scale = [1, 10], length_scale_bounds=(1e-5, 1e5))
是完全有效的,其中x1
保留1,x2
保留10。
但是,sklearn中的大多数内核都是各向同性的,目前不支持各向异性情况。如果您想要更多的自由,我建议您看看其他软件包(例如GPy),或者您始终可以尝试实现自己的各向异性内核。