Search code examples
pythonkeras-layer

How to define inpute shapes in Sequential keras model


Please, help to define appropriate Dense input shapes in keras models. Maybe I have to reshape my data first. I have data set with dimensions shown below:

Data shapes are X_train: (2858, 2037) y_train: (2858, 1) X_test: (715, 2037) y_test: (715, 1) Number of features (input shape) is 2037

I want to define Sequential keras model like that

``

    batch_size = 128
    num_classes = 2
    epochs = 20

    model = Sequential()
    model.add(Dense(512, activation='relu', input_shape=(X_input_shape,)))
    model.add(Dropout(0.2))
    model.add(Dense(512, activation='relu'))

    model.summary()

    model.compile(loss='binary_crossentropy',
                optimizer=RMSprop(),
                from_logits=True,
                metrics=['accuracy'])

``

Model summary:

``

    Layer (type)                 Output Shape              Param #   
    =================================================================
    dense_20 (Dense)             (None, 512)               1043456   
    _________________________________________________________________
    dropout_12 (Dropout)         (None, 512)               0         
    _________________________________________________________________
    dense_21 (Dense)             (None, 512)               262656    
    =================================================================
    Total params: 1,306,112
    Trainable params: 1,306,112
    Non-trainable params: 0

``

And when I try to fit it...

``

    history = model.fit(X_train, y_train,
                        batch_size=batch_size,
                        epochs=epochs,
                        verbose=1,
                        validation_data=(X_test, y_test))

`` I got an error:

``

  ValueError: Error when checking target: expected dense_21 to have shape (512,) but got array with shape (1,)                    

``


Solution

  • Modify

    model.add(Dense(512, activation='relu'))
    

    to

    model.add(Dense(1, activation='relu'))
    

    The output shape to be of size 1, same as y_train.shape[1].