Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keras - use part of the input at later stage in sequential model

I'm training a CNN. My input is an image and a few metadata. I'd like to train a CNN that only looks at the image in the convolutional stages, and then uses the output of the convolutional stages and the metadata in the final dense layers.

metadata -----------------
                          |-> dense -> output
image    -> Convolutions -

How can I do this with Keras? Can I feed input that has not a rectangular shape?

For instance if the image is (255, 255, 3) and the metadata (10) how would this work?

I've found this issue that seems related but I don't get how they split the input and merge the second part with the intermediate output later on.

like image 681
Guig Avatar asked Jun 18 '17 22:06

Guig


People also ask

What is input shape in Keras sequential?

What Is The Input Shape In A Keras Layer? In a Keras layer, the input shape is generally the shape of the input data provided to the Keras model while training. The model cannot know the shape of the training data. The shape of other tensors(layers) is computed automatically.

In which layer do we give input to our model?

There are three layers; an input layer, hidden layers, and an output layer. Inputs are inserted into the input layer, and each node provides an output value via an activation function. The outputs of the input layer are used as inputs to the next hidden layer.

What is the difference between sequential and model in Keras?

Sequential class : Sequential groups a linear stack of layers into a tf. keras. Model . Model class : Model group's layers into an object with training and inference features.

When should you avoid using the Keras function adapt ()?

Typically, a vocabulary larger than 500MB would be considered "very large". In such a case, for best performance, you should avoid using adapt() .


1 Answers

You need to use the Functional API with a multi-input model.

An example could be:

from keras.layers import Input, Conv1D, Dense, concatenate
#Image data
conv_input = Input(shape=conv_input_shape)
conv_output = Conv1D(nfilters,kernel_shape)(conv_input)

#Metadata
metadata_input = Input(shape=metadata_shape)

#Merge and add dense layer
merge_layer = concatenate([metadata_input, conv_output])
main_output = Dense(dense_size)(merge_layer)

# Define model with two inputs
model = Model(inputs=[conv_input, metadata_input], outputs=[main_output])

Hope this helps!

like image 155
Michele Tonutti Avatar answered Oct 06 '22 08:10

Michele Tonutti