如果我将层传递给两个 Keras 模型并且只训练一个模型,那么在前者训练后两个模型会共享权重吗

Posted

技术标签:

【中文标题】如果我将层传递给两个 Keras 模型并且只训练一个模型,那么在前者训练后两个模型会共享权重吗【英文标题】:If I pass layers to two Keras models and Train only one ,will both the model share weights after the former is trained 【发布时间】:2020-07-11 16:05:36 【问题描述】:

我尝试使用 Keras 构建一个简单的自动编码器,为此我从单个全连接神经层作为编码器和解码器开始。

> input_img = Input(shape=(784,)) 
>encoded = Dense(encoding_dim,activation='relu')(input_img) 
>decoded = Dense(784, activation='sigmoid')(encoded)
>autoencoder =Model(input_img, decoded)

我还借助

创建了一个单独的编码器模块
encoder = Model(input_img, encoded)

以及解码器模型:

encoded_input = Input(shape=(32,))
# retrieve the last layer of the autoencoder model
decoder_layer = autoencoder.layers[-1]
# create the decoder model
decoder = Model(encoded_input, decoder_layer(encoded_input))

然后我训练了模型

autoencoder.fit(x_train, x_train,
                epochs=50,
                batch_size=256,
                shuffle=True,
                validation_data=(x_test, x_test))

但即使我没有训练我的编码器和解码器,即使我在训练之前通过了层,它们也会共享自动编码器的权重。我只训练了编码器,但编码器和解码器都在接受训练。

encoded_imgs = encoder.predict(x_test)
decoded_imgs = decoder.predict(encoded_imgs)

【问题讨论】:

自动编码器不能这样工作。编码器和解码器都通过优化损失或再现误差一起训练。然后根据需要我们可以解耦编码器和解码器并相应地使用它。 【参考方案1】:

我在阅读文本时应该更加小心。 如果两个 Keras 模型共享一些层,当您训练第一个模型时,共享层的权重将在另一个模型中自动更新。

https://keras.io/getting-started/functional-api-guide/

此博客很好地说明了共享层的使用。

https://blog.keras.io/building-autoencoders-in-keras.html/

【讨论】:

以上是关于如果我将层传递给两个 Keras 模型并且只训练一个模型,那么在前者训练后两个模型会共享权重吗的主要内容,如果未能解决你的问题,请参考以下文章

Keras中的TypeError:即使已经提供了shuffle =“batch”,也要传递shuffle =“batch”

Keras模型根本不学习

从磁盘加载包含预训练 Keras 模型的 scikit-learn 管道

keras 如何保存训练集与验证集正确率的差最小那次epoch的网络及权重

keras构建前馈神经网络(feedforward neural network)进行多分类模型训练学习

使用大数据集在 Google Colab TPU 上训练 seq2seq 模型 - Keras