How to Get Input Shape Keras

  • Post category:Keras / Python

To get the input shape of a Keras model, you can access it through the input_shape attribute of the first layer in the model. Here’s how to do it:

Assuming you have a Keras model named model, you can get the input shape like this:

input_shape = model.layers[0].input_shape
print("Input shape:", input_shape)

In this code:

  1. model.layers[0] retrieves the first layer in your Keras model.
  2. input_shape is the attribute that holds the input shape for that layer.

Working Example:

# Import necessary libraries
import keras
from keras.models import Sequential
from keras.layers import Dense

# Create a simple Keras model (for demonstration)
model = Sequential()
model.add(Dense(units=64, activation='relu', input_dim=100))
model.add(Dense(units=10, activation='softmax'))

# Print the model summary
model.summary()
input_shape = model.layers[0].input_shape
print("Input shape:", input_shape)

Output:

Input shape: (None, 100)

This will print the input shape of your model to the console. It’s essential to know the input shape, especially when building or using models, as it determines the shape of the data that can be fed into the model.