You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GPflow 2.9.0无法导入ParamList,求DNN均值函数重实现替代方案

在GPflow 2.9.0中替代ParamList实现DNN均值函数的方案

核心背景

GPflow 2.x(含2.9.0)已移除v1.x版本中的ParamList,转而基于TensorFlow的tf.Module(及GPflow封装的gpflow.Module)管理可训练参数——所有被模块追踪的gpflow.Parameter或tf.Variable都会自动纳入优化流程,无需手动维护参数列表。

替代方案1:手动基于gpflow.Module实现

直接继承gpflow.Module,将DNN的层参数作为模块属性存储,GPflow会自动识别并追踪这些参数:

import gpflow
import tensorflow as tf

class DNNMeanFunction(gpflow.Module):
    def __init__(self, input_dim, hidden_dims, output_dim):
        super().__init__()
        self.layers = []
        
        # 输入层到第一个隐藏层
        self.layers.append(gpflow.Parameter(tf.random.normal([input_dim, hidden_dims[0]])))
        self.layers.append(gpflow.Parameter(tf.random.normal([hidden_dims[0]])))
        
        # 隐藏层
        for i in range(len(hidden_dims)-1):
            self.layers.append(gpflow.Parameter(tf.random.normal([hidden_dims[i], hidden_dims[i+1]])))
            self.layers.append(gpflow.Parameter(tf.random.normal([hidden_dims[i+1]])))
        
        # 输出层
        self.layers.append(gpflow.Parameter(tf.random.normal([hidden_dims[-1], output_dim])))
        self.layers.append(gpflow.Parameter(tf.random.normal([output_dim])))
        
    def __call__(self, X):
        h = X
        # 遍历权重和偏置对
        for idx in range(0, len(self.layers), 2):
            W = self.layers[idx]
            b = self.layers[idx+1]
            h = tf.matmul(h, W) + b
            # 最后一层前的层添加激活函数
            if idx < len(self.layers) - 2:
                h = tf.nn.tanh(h)
        return h

替代方案2:结合TensorFlow Keras层实现

利用TensorFlow的Keras构建DNN,Keras层本身是tf.Module子类,GPflow可自动识别其参数,代码更简洁:

import gpflow
import tensorflow as tf

class KerasDNNMeanFunction(gpflow.Module):
    def __init__(self, input_dim, hidden_dims, output_dim):
        super().__init__()
        # 构建Keras序列模型
        self.dnn = tf.keras.Sequential()
        self.dnn.add(tf.keras.layers.Dense(hidden_dims[0], activation="tanh", input_shape=(input_dim,)))
        for hd in hidden_dims[1:]:
            self.dnn.add(tf.keras.layers.Dense(hd, activation="tanh"))
        self.dnn.add(tf.keras.layers.Dense(output_dim))
        
    def __call__(self, X):
        return self.dnn(X)

使用验证

将上述均值函数传入GPflow高斯过程模型即可,示例代码:

# 假设输入维度为2,隐藏层为[32, 16],输出维度为1
mean_func = DNNMeanFunction(input_dim=2, hidden_dims=[32, 16], output_dim=1)
# 或使用Keras版本
# mean_func = KerasDNNMeanFunction(input_dim=2, hidden_dims=[32, 16], output_dim=1)

# 构建GP模型
kernel = gpflow.kernels.SquaredExponential()
gp_model = gpflow.models.GPR(data=(X_train, y_train), kernel=kernel, mean_function=mean_func)

# 查看可训练参数
gpflow.utilities.print_summary(gp_model)

内容的提问来源于stack exchange,提问作者Viktoria S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 23:22:47