Ahmad
Ahmad

Reputation: 9658

Getting a part of a Keras Model

I have a model for an AutoEncoder as follows:

height, width = 28, 28

input_img = Input(shape=(height * width,))
encoding_dim = height * width//256

x = Dense(height * width, activation='relu')(input_img)

encoded1 = Dense(height * width//2, activation='relu')(x)
encoded2 = Dense(height * width//8, activation='relu')(encoded1)

y = Dense(encoding_dim, activation='relu')(encoded2)

decoded2 = Dense(height * width//8, activation='relu')(y)
decoded1 = Dense(height * width//2, activation='relu')(decoded2)

z = Dense(height * width, activation='sigmoid')(decoded1)
autoencoder = Model(input_img, z)

#encoder is the model of the autoencoder slice in the middle 
encoder = Model(input_img, y)
decoder = Model(y, z)
print(encoder)
print(decoder)

The encoder part is retrived using the code above, however I can't get the decoder part using the code I added above:

I recieve the following error:

ValueError: Graph disconnected: cannot obtain value for tensor Tensor("input_39:0", shape=(?, 784), dtype=float32) at layer "input_39". The following previous layers were accessed without issue: []

Could you please guide me how to get that part?

Upvotes: 1

Views: 993

Answers (1)

Kilian Obermeier
Kilian Obermeier

Reputation: 7118

The decoder Model needs to have an input layer. For example, the decoder_input here:

height, width = 28, 28

# Encoder layers
input_img = Input(shape=(height * width,))
encoding_dim = height * width//256

x = Dense(height * width, activation='relu')(input_img)
encoded1 = Dense(height * width//2, activation='relu')(x)
encoded2 = Dense(height * width//8, activation='relu')(encoded1)
y = Dense(encoding_dim, activation='relu')(encoded2)

# Decoder layers
decoder_input = Input(shape=(encoding_dim,))
decoded2 = Dense(height * width//8, activation='relu')(decoder_input)
decoded1 = Dense(height * width//2, activation='relu')(decoded2)
z = Dense(height * width, activation='sigmoid')(decoded1)

# Build the encoder and decoder models
encoder = Model(input_img, y)
decoder = Model(decoder_input, z)

# Finally, glue encoder and decoder together by feeding the encoder 
# output to the decoder
autoencoder = Model(input_img, decoder(y))

Upvotes: 3

Related Questions