Search code examples
pythontensorflowmachine-learningkeras

Tensorflow TensorShape error on concatenating two models


I'm new to the functional API. I'm trying to concatenate two models into one to take one output like this:

cnn_model = Input(shape=(49, 10))
x = Conv1D(16, kernel_size=3, activation='relu')(cnn_model)
x = MaxPooling1D(pool_size=2)(x)
x = Conv1D(32, kernel_size=3, activation='relu')(x)
x = MaxPooling1D(pool_size=2)(x)
x = Flatten()(x)
x = Dense(32, activation='relu')

mlp_model = Input(shape=(4,))
y = Dense(64, activation='relu')(mlp_model)
y = Dense(32, activation='relu')(y)

combined = Concatenate()([x, y])

z = Dense(16, activation='relu')(combined)
output = Dense(1, activation='sigmoid')(z)

model = Model(inputs=[cnn_model, mlp_model], outputs=output)

This raises not defined on an unknown TensorShape error on here

combined = Concatenate()([x, y])

Error:

ValueError: as_list() is not defined on an unknown TensorShape.


Solution

  • The reason you are encountering the error is because you are trying to concentrate a Dense object and a KerasTensor. You forgot to pass the x Tensor from the Flatten layer to the following Dense layer.

    You need to change this line:

    x = Dense(32, activation='relu')
    

    with the following:

    x = Dense(32, activation='relu')(x)