Open In App

How to Determine Input Shape in Keras?

Last Updated : 16 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Answer: To determine the input shape in Keras, you can inspect the .shape attribute of the input data or print the shape of the input tensor using input_tensor.shape

In Keras, determining the input shape depends on the type of input data you’re working with. Here’s how you can determine the input shape for different scenarios:

1. For Sequential Models:

If you’re using a sequential model in Keras, you typically define the input shape when adding the first layer. For example:

Python3




from keras.models import Sequential
from keras.layers import Dense
 
model = Sequential()
# Example input shape (784,)
model.add(Dense(32, input_shape=(784,))) 


2. For Functional API Models:

If you’re using the functional API to build your model, you may have multiple input tensors. In this case, you can directly inspect the shape of the input tensor(s). For example:

Python3




from keras.models import Model
from keras.layers import Input, Dense
 
inputs = Input(shape=(784,))
x = Dense(32)(inputs)
model = Model(inputs=inputs, outputs=x)


3. For Pre-trained Models:

When using pre-trained models such as those available in keras.applications, you can usually find the expected input shape in the documentation or by inspecting the model summary. For example:

Python3




from keras.applications import ResNet50
 
model = ResNet50()
 # Example: (None, 224, 224, 3)
print(model.input_shape)


4. For Input Data:

If you’re working with input data (e.g., images, text sequences), you can inspect the shape of your input data directly. For example, if you’re loading an image dataset using ImageDataGenerator:

Python3




from keras.preprocessing.image import ImageDataGenerator
 
train_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
    'data/train',
    target_size=(150, 150),
    batch_size=32,
    class_mode='binary')
 
 # Example: (150, 150, 3)
print(train_generator.image_shape)


Conclusion:

Determining the input shape in Keras depends on the type of model you’re working with and the input data format. Whether you’re using sequential models, functional API models, pre-trained models, or input data generators, you can inspect the input shape through various methods provided by Keras. Understanding the input shape is crucial for correctly defining the architecture of your neural network models.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads