Keras tensorflow modify model NN to CNN

Viewed 126

I'm trying to rewrite a Neural Network model which used to classify satellite images, I want to use some conv layers in that model,like #keras.layers.Conv2D(filters=64, kernel_size=(3, 3), activation='relu', padding = 'same',input_shape=(1,nBands)), but I can't get the input_shape parameter right, can anyone help me?

the previous NN model is this:

# Print the shape of reshaped data
print(xTrain.shape, xTest.shape, featuresHyderabad.shape)
#(2519025, 1, 6) (1679351, 1, 6) (1391808, 1, 6)
# Define the parameters of the model
model = keras.Sequential([

    #keras.layers.Conv2D(filters=64, kernel_size=(3, 3), activation='relu', padding = 'same',input_shape=(1,nBands)),
    keras.layers.Flatten(input_shape=(1, nBands)), 
    keras.layers.Dense(128, activation='relu',kernel_initializer='glorot_normal'),
    keras.layers.Dense(2, activation='softmax')])

# Define the accuracy metrics and parameters
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])

# Run the model
model.fit(xTrain, yTrain, epochs=2,batch_size=10)
2 Answers

The input shape must be the shape of the images. for exemple if you train your model with 48x48 black and white images the input shape will be (48,48, 1) or (1, 48, 48) if the chanel value is placed before the height and width.

Great question, and I think you'll find CNNs perform much better than training NNs on flattened images. For the input shape in Conv2D layers, the shape can be given in one of two forms:

  1. "Channels last" (Keras uses this by default): (image height, image width, 6), where 6 refers to the number of channels (3 for RGB, 1 for grayscale).

  2. "Channels first" (you can select this option by setting data_option="channels_first" when you define the Conv2D layer): (6, image height, image width).

On a more intuitive note, you can think of the input size as being the size of the image you are giving to the network, which is (image height, image width, number of bands). I found this documentation from Keras helpful as well: https://keras.io/api/layers/convolution_layers/convolution2d/.

Related