python-kerasHow do I use Keras Sequential to create a model in Python?
Keras Sequential is a way of creating a linear stack of layers in a deep learning model. To use Keras Sequential, you must first create a Sequential object and then add layers to it. The layers can be added one by one or all at once.
Example code
from keras.models import Sequential
from keras.layers import Dense
# Create the Sequential model
model = Sequential()
# 1st Layer - Add a flatten layer
model.add(Flatten(input_shape=(32, 32, 3)))
# 2nd Layer - Add a fully connected layer
model.add(Dense(100, activation='relu'))
# 3rd Layer - Add a fully connected layer
model.add(Dense(60, activation='relu'))
# Output Layer - Add a fully connected layer
model.add(Dense(10, activation='softmax'))
# Compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
Code explanation
from keras.models import Sequential
- imports the Sequential model from the Keras library.model = Sequential()
- creates the Sequential model object.model.add(Flatten(input_shape=(32, 32, 3)))
- adds a flatten layer to the model. The input shape is the size of the image (32x32 pixels with 3 color channels).model.add(Dense(100, activation='relu'))
- adds a fully connected layer with 100 nodes and ReLU activation.model.add(Dense(60, activation='relu'))
- adds another fully connected layer with 60 nodes and ReLU activation.model.add(Dense(10, activation='softmax'))
- adds the output layer with 10 nodes and Softmax activation.model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
- compiles the model with the Adam optimizer, categorical cross-entropy loss function, and accuracy metrics.
Helpful links
More of Python Keras
- How to load a model in Python Keras?
- How do I set the input shape when using Keras with Python?
- How can I use Python and Keras to forecast time series data?
- How do I use validation_data when creating a Keras model in Python?
- How do I use Python Keras to zip a file?
- How do I check which version of Keras I am using in Python?
- How can I use Python Keras to develop a reinforcement learning model?
- How do I use Python's tf.keras.utils.get_file to retrieve a file?
- How can I split my data into train and test sets using Python and Keras?
- How can I use XGBoost, Python and Keras together to build a machine learning model?
See more codes...