I have been using the following functional API for an image classification task using CNN:
def create_model(X_train, X_test):
visible = Input(shape=(X_train.shape[0], X_train.shape[1], 1))
conv1 = Conv2D(32, kernel_size=4, activation='relu')(visible)
hidden1 = Dense(10, activation='relu')(pool2)
output = Dense(1, activation='sigmoid')(hidden1)
model = Model(inputs = visible, outputs = output)
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
return model
X_tr = np.reshape(X_train, (1,X_train.shape[0], X_train.shape[1], 1))
X_te = np.reshape(X_test, (1,X_test.shape[0], X_test.shape[1], 1))
model = create_model(X_train, X_test)
model.fit(X_tr, y_train, validation_split = 0.1, batch_size=10, epochs=10, verbose = 1, callbacks=[EarlyStopping(patience=5,verbose=1)])
where, X_train
is a 7942*6400 dimensional list and y_train
being a 1-D list with corresponding 7942 labels.
The error:
ValueError: Error when checking target: expected dense_2 to have 4 dimensions, but got array with shape (7942, 1)
What has possibly gone wrong here as I am a newbie to the functional API?
The message says that y_train
is not compatible with the model's output.
Your model is outputting (None, width, height, 1)
. You should add a Flatten()
layer after the convolution to make the data have only 2 dimensions from this point on.
Additional comments:
The input data must have a shape compatible with the model.
The shape of X_train
must be (7942,80,80,1)
The input_shape
of the model must be (80,80,1)
If you use a (1,6400, 1)
shape, your Conv2D
layer will be pretty useless, because it will not be able to intepret the data as a 2D image.