首页
/ 在BoTorch中使用已训练GP的均值和协方差函数构建新GP模型

在BoTorch中使用已训练GP的均值和协方差函数构建新GP模型

2025-06-25 12:12:20作者:段琳惟

背景介绍

在贝叶斯优化和机器学习领域,高斯过程(Gaussian Process, GP)是一种强大的非参数模型。BoTorch作为基于PyTorch的贝叶斯优化库,提供了灵活的高斯过程建模能力。本文将探讨一个在BoTorch中使用已训练GP模型的均值和协方差函数来构建新GP模型的技术实现。

问题场景

假设我们有以下三个高斯过程模型:

  1. gp1:基于小数据集训练
  2. gp2:基于大数据集训练,与gp1来自相同领域
  3. gp3:目标是使用gp2训练好的均值函数和协方差函数,同时基于gp1的小数据集进行训练(一种迁移学习的方法)

技术实现

基础模型构建

首先,我们需要定义基础的GP训练函数:

def train_gp(train_X, train_Y, mean_module=None, covar_module=None, bounds=None):
    if bounds.ndim == 1:
        bounds = bounds.reshape(-1, 1)
    
    d = train_X.shape[1]
    input_transform = Normalize(d=d, bounds=bounds) if bounds is not None else Normalize(d=d)
    
    gp = SingleTaskGP(
        train_X=train_X,
        train_Y=train_Y,
        mean_module=mean_module,
        covar_module=covar_module,
        outcome_transform=Standardize(m=1),
        input_transform=input_transform,
    )
    mll = ExactMarginalLogLikelihood(gp.likelihood, gp)
    fit_gpytorch_mll(mll)
    
    return gp

自定义均值和协方差函数

为了实现模型间的知识迁移,我们需要自定义均值和协方差函数:

class ConditionalMean(Mean):
    def __init__(self, gp):
        super().__init__()
        self.gp = gp

    def forward(self, x):
        with no_grad():
            self.gp.eval()
            m = self.gp(x).mean.squeeze(-1)
        return m

class ConditionalScaledMaternKernel(Kernel):
    has_lengthscale = True
    
    def __init__(self, gp):
        super().__init__()
        self.gp = gp
        self.scaled_matern_kernel = ScaleKernel(MaternKernel())

    def forward(self, x1, x2, **params):
        with no_grad():
            self.gp.eval()
            sigma = self.gp(x1).covariance_matrix.diagonal(dim1=-2, dim2=-1).sqrt().unsqueeze(-1)
            sigma_ = self.gp(x2).covariance_matrix.diagonal(dim1=-2, dim2=-1).sqrt().unsqueeze(-1)
            B = sigma @ sigma_.T
        A = self.scaled_matern_kernel(x1, x2)
        K = A + B
        return K

关键实现细节

  1. 梯度控制:为了防止已训练模型gp2的参数被更新,需要显式关闭其参数的梯度:
for param_name, param in mll.named_parameters():
    if 'gp' in param_name:
        param.requires_grad = False
  1. 模型评估模式:在自定义函数中使用gp.eval()确保模型处于评估模式,避免不必要的计算图构建。

  2. 输入输出转换处理:直接使用gp(x)而非gp.posterior(x)可以避免输入输出转换的重复应用问题。

实际应用效果

通过上述方法构建的gp3模型能够:

  • 继承gp2在大数据集上学到的模式
  • 在小数据集上保持适当的灵活性
  • 合理反映不同区域的预测不确定性

注意事项

  1. 当不使用输入输出转换时,实现会更为简单,但可能牺牲一些数值稳定性。

  2. 两种均值计算方式(gp(x).meangp.posterior(x).mean)在有无转换的情况下表现不同,需要根据实际场景选择。

  3. 模型间的知识迁移效果需要通过多个不同数据集验证,以确保其泛化能力。

总结

在BoTorch中通过自定义均值和协方差函数实现GP模型间的知识迁移是一种有效的技术手段。这种方法特别适用于数据获取成本不同的场景,如部分高质量小样本数据和大量低质量数据并存的情况。通过合理控制模型参数更新和评估模式,可以实现灵活而强大的模型组合。

登录后查看全文
热门项目推荐
相关项目推荐