任何人都可以在此错误消息中帮助我:ValueError:未知层:DenseVariational。请确保将此对象传递给custom_objects
参数。
当我尝试使用 tf.keras 加载经过训练的贝叶斯神经网络模型时,就会发生这种情况。它不断返回未知层:DenseVariational。但是训练代码运行良好。有谁知道如何解决这个问题?
我们尝试修改 Densevariational_v2 模块中的 get_config 函数,但它不起作用。谢谢并感激!!
加载模型的代码:
model = tf.keras.models.load_model('model.h5')
print("Model restored.")
model.summary()
训练和保存模型的代码:
bnn = tf.keras.Sequential(layers=[tfpl.DenseVariational(20,make_posterior_fn=posterior,make_prior_fn=prior,kl_weight= 1 / train_size,activation = activation, input_shape = (2,))]+ \
[tfpl.DenseVariational(hidden_layer[i],make_posterior_fn=posterior,make_prior_fn=prior,kl_weight= 1 / train_size, activation = activation) for i in range(1, len(hidden_layer))] + \
[tfpl.DenseVariational(1, make_posterior_fn=posterior,make_prior_fn=prior,kl_weight= 1 / train_size, activation = tf.keras.activations.softplus)],name="bnn")
losses = []
print("START TRAINING")
for epoch in range(n_epochs):
for batch in range(n_batches):
X_train, X_train_ = get_batch2(stock_path, batch_size) # get batch of theoretical options
training_op(X_train.astype(np.float32), X_train_.astype(np.float32))
epoch_loss = loss(X_test.astype(np.float32), X_test_.astype(np.float32))
losses.append(epoch_loss)
print('Epoch:', epoch, 'Loss:', epoch_loss)
bnn.save('model.h5')
print("model saved")
训练代码工作正常,我没有在这里复制整个内容,但它可以将模型保存到 .h5 文件中。只是加载部分,它无法完成。提前致谢!