Shape error when predicting with a trained model in tensorflow.keras


I’m creating a 1D CNN using tensorflow.keras, following this tutorial, with some of the concepts from this tutorial. So far modeling and training seem to be working, but I can’t seem to generate a prediction. Here’s an example of what I’m dealing with:


import numpy as np
from keras.utils import to_categorical

trainy = to_categorical(np.random.randint(2, size=NUM_SAMPLES))

In this example, I’m creating a dataset which represents what I’m working with. I have 1000 windows of time series data, each of which has 6 distinct traces (accelerometer x,y,z and gyro x,y,z). The lengths of these windows are 512 data points long.


from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten
from tensorflow.keras.layers import Conv1D, MaxPooling1D

verbose, epochs, batch_size = 1, 3, 32
model = Sequential()
model.add(Conv1D(filters=64, kernel_size=3, activation='relu', input_shape = trainX[0].shape))
model.add(Conv1D(filters=64, kernel_size=3, activation='relu'))
model.add(Dense(100, activation='relu'))
model.add(Dense(2, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']), trainy, epochs=epochs, batch_size=batch_size, verbose=verbose)

Creating a simple CNN, this trains perfectly with the following output:

Train on 1000 samples
Epoch 1/3
1000/1000 [==============================] - 1s 1ms/sample - loss: 0.8802 - accuracy: 0.4930
Epoch 2/3
1000/1000 [==============================] - 1s 724us/sample - loss: 0.6726 - accuracy: 0.5920
Epoch 3/3
1000/1000 [==============================] - 1s 740us/sample - loss: 0.6291 - accuracy: 0.6760

Prediction (where the error comes up)

for testing purposes, I’m predicting a portion of training data. Running model.predict(trainX[0]) results in the following error:

ValueError: Error when checking input: expected conv1d_4_input to have 3 dimensions, but got array with shape (512, 6)

this seems peculiar, as I would expect compatibility of the training dataset; after all, trainX[0] is what defined the input_shape in the first place.


please runing the code: model.predict([trainX[0]]), and the model outputs the predicted results

Answered By – feifei Xiao

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published