Search code examples
pythonpython-3.xtensorflowkeraskeras-layer

How to adjust the output dimensions of a Keras model?


I'm trying to build an artificial neural network using Keras. The model's input has dimensions of (5, 5, 2), while the output has dimensions of (5,5). While running the keras.fit() function, I encounter the following error:

ValueError: Error when checking target: expected dense_3 to have 4 dimensions, but got array with shape (5, 5)

Here's the code I'm executing

from keras.models import Sequential
from keras.layers import Dense, Flatten
import matplotlib.pyplot as plt
from keras.callbacks import EarlyStopping, ModelCheckpoint

model = Sequential()

model.add(Dense(1000, input_shape=(5, 5, 2), activation="relu"))
model.add(Dense(1000, activation="relu"))
model.add(Dense(2), output_shape=(5,5))

model.summary()

model.compile(optimizer="adam",loss="mse", metrics = ["mse"])

monitor_val_acc = EarlyStopping(monitor="loss", patience = 10)


history = model.fit(trainX, trainYbliss, epochs=1000, validation_data=(testX, testY), callbacks = [monitor_val_acc], verbose = 1)

clinical = model.predict(np.arange(0, len(testY)))

Here's the architecture of the network:

Layer (type)                 Output Shape              Param #   
=================================================================
dense_1 (Dense)              (None, 5, 5, 1000)        3000      
_________________________________________________________________
dense_2 (Dense)              (None, 5, 5, 1000)        1001000   
_________________________________________________________________
dense_3 (Dense)              (None, 5, 5, 1)           1001      
=================================================================
Total params: 1,005,001
Trainable params: 1,005,001
Non-trainable params: 0
_________________________________________________________________

The model should output a (5,5) array based on a (5,5,2) array, but fails at the lowest hidden layer. How do I resolve this?


Solution

  • use below code as reference change the values according to your input values:

    train_data = train_data.reshape(train_data.shape[0], 10, 30, 30, 1)

    for both your input train data,