0

I am playing with Keras Code. When i write the code like this,

model = Sequential()
model.add(Dense(64, activation='relu', input_shape=(784,) ))
model.add(Dense(128, activation='relu'))
model.add(Dense(784, activation='relu'))
model.compile(optimizer='adam', loss='mean_squared_error')

it works without any trouble. But If achieve this by passing the previous layer to next layer as a parameter, then i get the error.

layer1 = Dense(64, activation='relu', input_shape=(784,) )
layer2 = Dense(128, activation='relu') (layer1)
layer3 = Dense(784, activation='relu') (layer2)
model = Model(layer1, layer3)
model.compile(optimizer='adam', loss='mean_squared_error')

Below is the error

ValueError: Layer dense_2 was called with an input that isn't a symbolic tensor. Received type: <class 'keras.layers.core.Dense'>. Full input: [<keras.layers.core.Dense object at 0x7f1317396310>]. All inputs to the layer should be tensors.

How can i fix this?

desertnaut
  • 57,590
  • 26
  • 140
  • 166
Whoami
  • 13,930
  • 19
  • 84
  • 140
  • 1
    Please put a meaningful title to your question, the current one doesn't make much sense given the problem in the question body. – Dr. Snoopy Sep 12 '18 at 07:01

1 Answers1

1

You miss Input layer.

x = Input((784,))
layer1 = Dense(64, activation='relu')(x)
layer2 = Dense(128, activation='relu') (layer1)
layer3 = Dense(784, activation='relu') (layer2)
model = Model(inputs=x, outputs=layer3)
model.compile(optimizer='adam', loss='mean_squared_error')
Kota Mori
  • 6,510
  • 1
  • 21
  • 25
  • But there is something called input_shape as a parameter, that which carries input dimension. In that case when we need to write a separate for Input() alone? – Whoami Sep 12 '18 at 06:15
  • `input_shape` is optional except for the first layer of your model, since keras kindly guesses the input shape for middle layers from the previous. – Kota Mori Sep 12 '18 at 06:21
  • If you use `Sequential` and `add` methods to create a model, you need to specify the input shape for the first `Dense` layer, since there is no clue to guess it. This can be seen as a syntax sugar of `Input` + `Dense` in the functional API approach. – Kota Mori Sep 12 '18 at 06:26
  • Yes, input_shape is only for Sequential models, for functional models you have to use the Input class – Dr. Snoopy Sep 12 '18 at 07:01
  • 1
    @Whoami indeed, there is a slight difference on how an input layer is handled between the Sequential & Functional APIs; see [Keras Sequential model input layer](https://stackoverflow.com/questions/46572674/keras-sequential-model-input-layer/46574294#46574294) – desertnaut Sep 12 '18 at 09:44