Home > Software engineering >  A `Concatenate` layer requires inputs with matching shapes except for the concatenation axis. Receiv
A `Concatenate` layer requires inputs with matching shapes except for the concatenation axis. Receiv

Time:04-20

"""
Defining two sets of inputs
Input_A: input from the features
Input_B: input from images
my train_features has (792,192) shape
my train_images has (792,28,28) shape
"""

input_A = Input(shape=(192,), name="wide_input")
input_B = Input(shape=(28,28), name="deep_input")
#connecting the first layer with the input from the features
x= Dense(600, activation='relu')(input_A)
x=Dense(100, activation='relu')(x)
x=Dense(28, activation='relu')(x)
x=keras.Model(inputs=input_A, outputs=x)

#connecting the second layer using the input from the images
         
y= Dense(28, activation='relu')(input_B)
y=Dense(7, activation='relu')(y)
y=Dense(28, activation='relu')(y)
y=keras.Model(inputs=input_B, outputs=y)

concat =  concatenate([x.output, y.output])

output = Dense(1, name="output")(concat)

model = keras.Model(inputs=[x.input, y.input], outputs=[output])

it keeps throwing this error: ValueError: A Concatenate layer requires inputs with matching shapes except for the concatenation axis. Received: input_shape=[(None, 28), (None, 28, 28)]

CodePudding user response:

You cannot concatenate tensors with different shapes. That is what the error message is saying. Try applying a Flatten layer to y.output. Here is a working a example:

import tensorflow as tf

input_A = tf.keras.layers.Input(shape=(192,), name="wide_input")
input_B = tf.keras.layers.Input(shape=(28,28), name="deep_input")
#connecting the first layer with the input from the features
x= tf.keras.layers.Dense(600, activation='relu')(input_A)
x=tf.keras.layers.Dense(100, activation='relu')(x)
x=tf.keras.layers.Dense(28, activation='relu')(x)
x=tf.keras.Model(inputs=input_A, outputs=x)

#connecting the second layer using the input from the images
         
y= tf.keras.layers.Dense(28, activation='relu')(input_B)
y=tf.keras.layers.Dense(7, activation='relu')(y)
y=tf.keras.layers.Dense(28, activation='relu')(y)
y=tf.keras.Model(inputs=input_B, outputs=y)

concat =  tf.keras.layers.concatenate([x.output, tf.keras.layers.Flatten()(y.output)])

output = tf.keras.layers.Dense(1, name="output")(concat)

model = tf.keras.Model(inputs=[x.input, y.input], outputs=[output])
  • Related