简体   繁体   中英

If I pass layers to two Keras models and Train only one ,will both the model share weights after the former is trained

I tried to build a simple Autoencoder using Keras for this I started with a single fully-connected neural layer as an encoder and as a decoder.

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

I also created a separate encoder module with the help of

encoder = Model(input_img, encoded)

As well as the decoder model:

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))

Then I trained the model

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

but even if i didn't train my encoder and decoder, Those are sharing the weights of autoencoder even if I passed the layers before training. I trained only the encoder but both encoder and decoder are getting trained.

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

I should have been more careful while reading the text. If two Keras models are sharing some layers, when you train the first model, the weights from the shared layers will be updated automatically in the other model.

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

This blog illustrates the use of shared layers nicely.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM