Keras Conv2D CNN - Error when checking target - expected smaller output - python

I am stacking 6 layers of 2D satellite imagery (x data) and attempting to run a CNN over them to classify the landcover (using 8 land cover classes taken from a reformatted USDA Crop Data Layer - y data).
The x data is shaped (2004, 2753, 6) and the y is shaped (2004, 2753, 8) originally and I have used data_x.reshape(-1,2004,2752,6) (same for y) to add an extra dimension as the model.
The 8 categories in the y data-set represent 8 possible land-cover categories in numerical format in 8 bands (i.e. 1st band is corn and represented by 1's for positive and 0 for not corn).
However, when i try to run the model the expected shape does not match what is being passed through to it. I am unsure if I am using the correct model structure or data structure - one idea would be to take the 8 bands of the y dataset
Based on some serious googling i have been learning how to get the data into the correct format with the right number of dimensions etc but feel I am falling at the last hurdle with regards to dimensions (and most likely correct preparation of the x & y data sets).
Below is the CNN model
input_shape=([2004, 2753, 6])
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),strides=(1, 1),activation='relu',input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2, 2), padding="same"))
model.add(Conv2D(32, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), padding="same"))
model.add(Dropout(0.25))
#model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(8, activation='softmax'))
#model.add(Flatten())
model.summary()
Model Summary - expecting 500, 687, 8 out at the end
Layer (type) Output Shape Param #
=================================================================
conv2d_54 (Conv2D) (None, 2002, 2751, 32) 1760
_________________________________________________________________
max_pooling2d_52 (MaxPooling (None, 1001, 1376, 32) 0
_________________________________________________________________
conv2d_55 (Conv2D) (None, 999, 1374, 32) 9248
_________________________________________________________________
max_pooling2d_53 (MaxPooling (None, 500, 687, 32) 0
_________________________________________________________________
dropout_57 (Dropout) (None, 500, 687, 32) 0
_________________________________________________________________
dense_59 (Dense) (None, 500, 687, 128) 4224
_________________________________________________________________
dropout_58 (Dropout) (None, 500, 687, 128) 0
_________________________________________________________________
dense_60 (Dense) (None, 500, 687, 8) 1032
=================================================================
Total params: 16,264
Trainable params: 16,264
Non-trainable params: 0
_________________________________________________________________
compile
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy',
optimizer='sgd',
metrics=['accuracy'])
fit - and where i get the error message
history = model.fit(x_train3d, y_train3d,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_split=0.2, validation_data=None)
shape of x_train3D = (1, 2004, 2753, 6)
shape of y_train3D = (1, 2004, 2753, 8)
error message
ValueError: Error when checking target: expected dense_58 to have shape (500, 687, 8) but got array with shape (2004, 2753, 8)
Again, I suspect this is down to needing to get the data in the right format both for the input and output but also likely something wrong in the specification of the model. Would appreciate some guidance as i'm new to Keras.

Can you please explain what are you trying to classifiy and what is your expected y_train3D (is it an image or some value for classificaton e.g. 1/2/3.. or x/y/z..etc)

Just for an update on this - I have managed to clear the error (and now onto a memory error but that's another question).
Solved the issue in 2 ways.
1. Added upsampling to the end of the model to get the data back into the original size - new code in below
model = Sequential()
model.add(Conv2D(32, (3, 3), padding="same", activation="relu",input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2),strides=(2, 2)))
model.add(Conv2D(64, (3, 3), padding="same", activation="relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(128, (3, 3), padding="same", activation="relu"))
#Upsampling
model.add(UpSampling2D(size=(2,2),interpolation='nearest'))
model.add(UpSampling2D(size=(2,2),interpolation='nearest'))
model.add(Dense(8, activation='relu'))
model.summary()
Give me the below summary
Layer (type) Output Shape Param #
=================================================================
conv2d_1 (Conv2D) (None, 2004, 2752, 32) 1760
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 1002, 1376, 32) 0
_________________________________________________________________
conv2d_2 (Conv2D) (None, 1002, 1376, 64) 18496
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 501, 688, 64) 0
_________________________________________________________________
conv2d_3 (Conv2D) (None, 501, 688, 128) 73856
_________________________________________________________________
up_sampling2d_1 (UpSampling2 (None, 1002, 1376, 128) 0
_________________________________________________________________
up_sampling2d_2 (UpSampling2 (None, 2004, 2752, 128) 0
_________________________________________________________________
dense_1 (Dense) (None, 2004, 2752, 8) 1032
=================================================================
Total params: 95,144
Trainable params: 95,144
Non-trainable params: 0
Part 2 - was ensuring the x and y data arrays were dividable by 4, otherwise this meant as I was losing some of the data through the model through rounding. The below is specific to my code and not robust but worked
if x_train3d.shape[2] % 2:
x_train3d_adj = x_train3d_adj[:,:,:-1,:]
y_train3d_adj = y_train3d_adj[:,:,:-1,:]
Not a complete solution yet but does get me closer to the end goal

Related

Python Neural Networks - Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (700, 128, 33)

So I am working on a "music genre classification" project and I am working with the GTZAN dataset to create a simple CNN network to classify the genre for an audio file.
My code for the model training , validation and testing is below:
input_shape = (genre_features.train_X.shape[1], genre_features.train_X.shape[2],1)
print("Build CNN model ...")
model = Sequential()
model.add(Conv2D(24, (5, 5), strides=(1, 1), input_shape=input_shape))
model.add(AveragePooling2D((2, 2), strides=(2,2)))
model.add(Activation('relu'))
model.add(Conv2D(48, (5, 5), padding="same"))
model.add(AveragePooling2D((2, 2), strides=(2,2)))
model.add(Activation('relu'))
model.add(Conv2D(48, (5, 5), padding="same"))
model.add(AveragePooling2D((2, 2), strides=(2,2)))
model.add(Activation('relu'))
model.add(Flatten())
model.add(Dropout(rate=0.5))
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(rate=0.5))
model.add(Dense(10))
model.add(Activation('softmax'))
print("Compiling ...")
opt = Adam()
model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"])
model.summary()
print("Training ...")
batch_size = 35 # num of training examples per minibatch
num_epochs = 400
model.fit(
genre_features.train_X,
genre_features.train_Y,
batch_size=batch_size,
epochs=num_epochs
)
print("\nValidating ...")
score, accuracy = model.evaluate(
genre_features.dev_X, genre_features.dev_Y, batch_size=batch_size, verbose=1
)
print("Dev loss: ", score)
print("Dev accuracy: ", accuracy)
print("\nTesting ...")
score, accuracy = model.evaluate(
genre_features.test_X, genre_features.test_Y, batch_size=batch_size, verbose=1
)
print("Test loss: ", score)
print("Test accuracy: ", accuracy)
# Creates a HDF5 file 'lstm_genre_classifier.h5'
model_filename = "lstm_genre_classifier_lstm.h5"
print("\nSaving model: " + model_filename)
model.save(model_filename)
And when I try to train the file I get the following Error ( I also printed the Train , Validation and Test Shape before compiling model)
Training X shape: (700, 128, 33)
Training Y shape: (700, 10)
Dev X shape: (200, 128, 33)
Dev Y shape: (200, 10)
Test X shape: (100, 128, 33)
Test Y shape: (100, 10)
Build CNN model ...
2020-12-25 15:46:58.410663: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
Compiling ...
Model: "sequential_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d_1 (Conv2D) (None, 124, 29, 24) 624
_________________________________________________________________
average_pooling2d_1 (Average (None, 62, 14, 24) 0
_________________________________________________________________
activation_1 (Activation) (None, 62, 14, 24) 0
_________________________________________________________________
conv2d_2 (Conv2D) (None, 62, 14, 48) 28848
_________________________________________________________________
average_pooling2d_2 (Average (None, 31, 7, 48) 0
_________________________________________________________________
activation_2 (Activation) (None, 31, 7, 48) 0
_________________________________________________________________
conv2d_3 (Conv2D) (None, 31, 7, 48) 57648
_________________________________________________________________
average_pooling2d_3 (Average (None, 15, 3, 48) 0
_________________________________________________________________
activation_3 (Activation) (None, 15, 3, 48) 0
_________________________________________________________________
flatten_1 (Flatten) (None, 2160) 0
_________________________________________________________________
dropout_1 (Dropout) (None, 2160) 0
_________________________________________________________________
dense_1 (Dense) (None, 64) 138304
_________________________________________________________________
activation_4 (Activation) (None, 64) 0
_________________________________________________________________
dropout_2 (Dropout) (None, 64) 0
_________________________________________________________________
dense_2 (Dense) (None, 10) 650
_________________________________________________________________
activation_5 (Activation) (None, 10) 0
=================================================================
Total params: 226,074
Trainable params: 226,074
Non-trainable params: 0
_________________________________________________________________
Training ...
Traceback (most recent call last):
File "cnn.py", line 82, in <module>
epochs=400
File "C:\Users\Bharat.000\miniconda3\lib\site-packages\keras\engine\training.py", line 1154, in fit
batch_size=batch_size)
File "C:\Users\Bharat.000\miniconda3\lib\site-packages\keras\engine\training.py", line 579, in _standardize_user_data
exception_prefix='input')
File "C:\Users\Bharat.000\miniconda3\lib\site-packages\keras\engine\training_utils.py", line 135, in standardize_input_data
'with shape ' + str(data_shape))
ValueError: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (700, 128, 33)
I tried few solutions from some similar questions , but I could not understood much since I am new to this topic. Any help apprecitated about what do I change to get proper output.
Your input dimension is wrong. Are you sure your data is 2D (like images) and not 1D (like sound waves)? If your data is 1D then you should be doing 1 dimensional convolutions. The reason why an error occurs is because your train data has the shape (700 (how many datapoints), 128, 33). In Conv2D in keras you need to have (batch size, image_height, image_width, channels) -- channels could be first or last but its not really relevant. What I am trying to say is that instead of the (image_height, image_width) tuple required by 2Dconv you only provide the number 128. Maybe what you're looking for is 1 Dimensional conv.

Tensorflow: Prediction of float value from image always returns 0

I have a model as follows:
from tensorflow import keras
from tensorflow.keras.layers import Dense, Conv2D, Flatten, MaxPooling2D
model = keras.Sequential([
Conv2D(16, (3, 3), padding='same', activation='relu', input_shape=(480, 640, 3), data_format="channels_last"),
MaxPooling2D(),
Conv2D(32, (3, 3), padding='same', activation='relu'),
MaxPooling2D(),
Conv2D(64, (3, 3), padding='same', activation='relu'),
MaxPooling2D(),
Flatten(),
Dense(480, activation='relu'),
Dense(1, activation="relu")
])
model.compile(optimizer='adam',
loss=keras.losses.MeanSquaredError(),
metrics=['accuracy'])
epochs = 3
model.fit(
x=train_images,
y=train_values,
epochs=epochs
)
The variable train_images is an array of PNG images (640x480 pixels) and train_values is an array of floats (e.g: [1.11842, -17.894, 2.03, ...].
My goal is to predict the float value (at least, to find some approximate value), so I suppose that MSE should be the loss function in this case.
However, after training the model, I only get zeros not only with model.predict(test_images) but also with model.predict(train_images).
Note: I have to recall that my batch contains only 37 images, and my test sample contains 14. I know that the size is ridiculous, but this script is just a concept for something bigger.
If it helps, here is the result of model.summary():
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d (Conv2D) (None, 480, 640, 16) 448
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 240, 320, 16) 0
_________________________________________________________________
conv2d_1 (Conv2D) (None, 240, 320, 32) 4640
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 120, 160, 32) 0
_________________________________________________________________
conv2d_2 (Conv2D) (None, 120, 160, 64) 18496
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 60, 80, 64) 0
_________________________________________________________________
flatten (Flatten) (None, 307200) 0
_________________________________________________________________
dense (Dense) (None, 480) 147456480
_________________________________________________________________
dense_1 (Dense) (None, 1) 481
=================================================================
Total params: 147,480,545
Trainable params: 147,480,545
Non-trainable params: 0
To start with change your activation function, relu limits values so anything below 0 = 0, thats not desire-able
Secondly normalize your y values, as it stands your values could be anywhere from -inf to +inf, range normalize them and store the normalization parameters. At run time you could always reverse this and get actual values
Also pump up the epochs, with that small a train set i suggest try overfitting the network, if a network overfits it will most likely train well
For now try these suggestions out, i think normalization is quite important
ALSO :: I suggest make the network much deeper, you need to extract the shapes and textures in the image and your network might not be deep enough (or as a matter of fact even be dense enough) to do that. I suggest use keras to load a pre trained model like VGG16, strip the head off add regression layers and transfer learn it onto your dataset. That could be better

1D Convolutional Neural Network Input Shape `ValueError`

I am generating a 1D Convolution and have some trouble with the input shape of my data. I had a look at some posts and it seems the error was that the data has to be 3D but my data is already 3D.
# shape
# x_train shape: (1228, 1452, 20)
# y_train shape: (1228, 1452, 8)
# x_val shape: (223, 680, 20)
# x_val shape: (223, 680, 8)
###
n_outputs = 8
n_timesteps = 1452
n_features = 20
model = Sequential()
model.add(Conv1D(filters=64, kernel_size=3, activation='relu', input_shape=(x_train.shape[1:]))) # ie 1452, 20
model.add(Conv1D(filters=64, kernel_size=3, activation='relu'))
model.add(Dropout(0.5))
model.add(MaxPooling1D(pool_size=2))
model.add(Flatten())
model.add(Dense(100, activation='relu'))
model.add(Dense(n_outputs, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=9,
batch_size=64,
shuffle=True)
But I keep on getting this error message:
ValueError: A target array with shape (1228, 1452, 8) was passed for an output of shape (None, 8) while using as loss `categorical_crossentropy`. This loss expects targets to have the same shape as the output.
What I gather from this is that target shape which is 3 dimensional is not the same as the 2 dimensional output and so it can't work out the loss, but I just need to find a way to reshape so that they are equal.
EDIT
model.summary() is shown below
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv1d (Conv1D) (None, 1450, 64) 3904
_________________________________________________________________
conv1d_1 (Conv1D) (None, 1448, 64) 12352
_________________________________________________________________
dropout (Dropout) (None, 1448, 64) 0
_________________________________________________________________
max_pooling1d (MaxPooling1D) (None, 724, 64) 0
_________________________________________________________________
flatten (Flatten) (None, 46336) 0
_________________________________________________________________
dense (Dense) (None, 100) 4633700
_________________________________________________________________
dense_1 (Dense) (None, 8) 808
=================================================================
Total params: 4,650,764
Traceback (most recent call last):
Trainable params: 4,650,764
Non-trainable params: 0
The issue in my case was that the target vector was 3D whilst the output vector was 2D and so there is an obvious mismatch. To fix the issue change the shape of the y_train to (batch, 8) or use return_sequences=True to return the same shape from the previous LSTM layer.

Shapes error in Convolutional Neural Network

I'm trying to train a neural network with the following structure:
model = Sequential()
model.add(Conv1D(filters = 300, kernel_size = 5, activation='relu', input_shape=(4000, 1)))
model.add(Conv1D(filters = 300, kernel_size = 5, activation='relu'))
model.add(MaxPooling1D(3))
model.add(Conv1D(filters = 320, kernel_size = 5, activation='relu'))
model.add(MaxPooling1D(3))
model.add(Dropout(0.5))
model.add(Dense(num_labels, activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
return model
And I'm getting this error:
expected dense_1 to have shape (442, 3) but got array with shape (3, 1)
My input is a set of phrases (12501 total) that have been tokenized for the 4000 most relevant words, and there's 3 possible classification. Therefore my input is train_x.shape = (12501, 4000). I reshaped this to (12501, 4000, 1) for the Conv1D layer. Now, my train_y.shape = (12501,3), and I reshaped that into (12501,3, 1).
I'm using the fit function as follows:
model.fit(train_x, train_y, batch_size=32, epochs=10, verbose=1, validation_split=0.2, shuffle=True)
What am I doing wrong?
There's no need to convert label shape for classification. And you can look at your network structure.
print(model.summary())
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv1d_1 (Conv1D) (None, 3996, 300) 1800
_________________________________________________________________
conv1d_2 (Conv1D) (None, 3992, 300) 450300
_________________________________________________________________
max_pooling1d_1 (MaxPooling1 (None, 1330, 300) 0
_________________________________________________________________
conv1d_3 (Conv1D) (None, 1326, 320) 480320
_________________________________________________________________
max_pooling1d_2 (MaxPooling1 (None, 442, 320) 0
_________________________________________________________________
dropout_1 (Dropout) (None, 442, 320) 0
_________________________________________________________________
dense_1 (Dense) (None, 442, 3) 963
=================================================================
Total params: 933,383
Trainable params: 933,383
Non-trainable params: 0
_________________________________________________________________
The last output of the model is (None, 442, 3), but the shape of your label is (None, 3, 1). You should eventually ending in either a global pooling layer GlobalMaxPooling1D() or a Flatten layer Flatten(), turning the 3D outputs into 2D outputs, for classification or regression.

Keras 2D input to 2D output

First, I have read this and this questions with similar names to mine and still do not have an answer.
I want to build a feedforward network for sequence prediction. (I realize that RNNs are more suitable for this task, but I have my reasons). The sequences are of length 128 and each element is a vector with 2 entries, so each batch should be of shape (batch_size, 128, 2) and the target is the next step in the sequence, so the target tensor should be of shape (batch_size, 1, 2).
The network architecture is something like this:
model = Sequential()
model.add(Dense(50, batch_input_shape=(None, 128, 2), kernel_initializer="he_normal" ,activation="relu"))
model.add(Dense(20, kernel_initializer="he_normal", activation="relu"))
model.add(Dense(5, kernel_initializer="he_normal", activation="relu"))
model.add(Dense(2))
But trying to train I get the following error:
ValueError: Error when checking target: expected dense_4 to have shape (128, 2) but got array with shape (1, 2)
I've tried variations like:
model.add(Dense(50, input_shape=(128, 2), kernel_initializer="he_normal" ,activation="relu"))
but get the same error.
If you take a look at the model.summary() output you will see that what the issue is:
Layer (type) Output Shape Param #
=================================================================
dense_13 (Dense) (None, 128, 50) 150
_________________________________________________________________
dense_14 (Dense) (None, 128, 20) 1020
_________________________________________________________________
dense_15 (Dense) (None, 128, 5) 105
_________________________________________________________________
dense_16 (Dense) (None, 128, 2) 12
=================================================================
Total params: 1,287
Trainable params: 1,287
Non-trainable params: 0
_________________________________________________________________
As you can see, the output of the model is (None, 128,2) and not (None, 1, 2) (or (None, 2)) as you expected. So, you may or may not know that Dense layer is applied on the last axis of its input array and as a result, as you see above, the time axis and dimension is preserved until the end.
How to resolve this? You mentioned you don't want to use a RNN layer, therefore you have two options: you need to either use Flatten layer somewhere in the model or you can also use some Conv1D + Pooling1D layers or even a GlobalPooling layer. For example (these are just for demonstration, you may do it differently):
using Flatten layer
model = models.Sequential()
model.add(Dense(50, batch_input_shape=(None, 128, 2), kernel_initializer="he_normal" ,activation="relu"))
model.add(Dense(20, kernel_initializer="he_normal", activation="relu"))
model.add(Dense(5, kernel_initializer="he_normal", activation="relu"))
model.add(Flatten())
model.add(Dense(2))
model.summary()
Model summary:
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense_17 (Dense) (None, 128, 50) 150
_________________________________________________________________
dense_18 (Dense) (None, 128, 20) 1020
_________________________________________________________________
dense_19 (Dense) (None, 128, 5) 105
_________________________________________________________________
flatten_1 (Flatten) (None, 640) 0
_________________________________________________________________
dense_20 (Dense) (None, 2) 1282
=================================================================
Total params: 2,557
Trainable params: 2,557
Non-trainable params: 0
_________________________________________________________________
using GlobalAveragePooling1D layer
model = models.Sequential()
model.add(Dense(50, batch_input_shape=(None, 128, 2), kernel_initializer="he_normal" ,activation="relu"))
model.add(Dense(20, kernel_initializer="he_normal", activation="relu"))
model.add(GlobalAveragePooling1D())
model.add(Dense(5, kernel_initializer="he_normal", activation="relu"))
model.add(Dense(2))
model.summary()
​Model summary:
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense_21 (Dense) (None, 128, 50) 150
_________________________________________________________________
dense_22 (Dense) (None, 128, 20) 1020
_________________________________________________________________
global_average_pooling1d_2 ( (None, 20) 0
_________________________________________________________________
dense_23 (Dense) (None, 5) 105
_________________________________________________________________
dense_24 (Dense) (None, 2) 12
=================================================================
Total params: 1,287
Trainable params: 1,287
Non-trainable params: 0
_________________________________________________________________
Note that in both cases above you need to reshape the labels (i.e. targets) array to (n_samples, 2) (or you may want to use a Reshape layer at the end).

Categories