Getting started with the Keras Sequential model

The Sequential model is a linear stack of layers.

You can create a Sequential model by passing a list of layer instances to the constructor:

  1. from keras.models import Sequential
  2. from keras.layers import Dense, Activation
  3. model = Sequential([
  4. Dense(32, input_shape=(784,)),
  5. Activation('relu'),
  6. Dense(10),
  7. Activation('softmax'),
  8. ])

You can also simply add layers via the .add() method:

  1. model = Sequential()
  2. model.add(Dense(32, input_dim=784))
  3. model.add(Activation('relu'))

Specifying the input shape

The model needs to know what input shape it should expect. For this reason, the first layer in a Sequential model (and only the first, because following layers can do automatic shape inference) needs to receive information about its input shape. There are several possible ways to do this:

  • Pass an input_shape argument to the first layer. This is a shape tuple (a tuple of integers or None entries, where None indicates that any positive integer may be expected). In input_shape, the batch dimension is not included.
  • Some 2D layers, such as Dense, support the specification of their input shape via the argument input_dim, and some 3D temporal layers support the arguments input_dim and input_length.
  • If you ever need to specify a fixed batch size for your inputs (this is useful for stateful recurrent networks), you can pass a batch_size argument to a layer. If you pass both batch_size=32 and input_shape=(6, 8) to a layer, it will then expect every batch of inputs to have the batch shape (32, 6, 8).

As such, the following snippets are strictly equivalent:

  1. model = Sequential()
  2. model.add(Dense(32, input_shape=(784,)))
  1. model = Sequential()
  2. model.add(Dense(32, input_dim=784))

Compilation

Before training a model, you need to configure the learning process, which is done via the compile method. It receives three arguments:

  • An optimizer. This could be the string identifier of an existing optimizer (such as rmsprop or adagrad), or an instance of the Optimizer class. See: optimizers.
  • A loss function. This is the objective that the model will try to minimize. It can be the string identifier of an existing loss function (such as categorical_crossentropy or mse), or it can be an objective function. See: losses.
  • A list of metrics. For any classification problem you will want to set this to metrics=['accuracy']. A metric could be the string identifier of an existing metric or a custom metric function. See: metrics.
  1. # For a multi-class classification problem
  2. model.compile(optimizer='rmsprop',
  3. loss='categorical_crossentropy',
  4. metrics=['accuracy'])
  5. # For a binary classification problem
  6. model.compile(optimizer='rmsprop',
  7. loss='binary_crossentropy',
  8. metrics=['accuracy'])
  9. # For a mean squared error regression problem
  10. model.compile(optimizer='rmsprop',
  11. loss='mse')
  12. # For custom metrics
  13. import keras.backend as K
  14. def mean_pred(y_true, y_pred):
  15. return K.mean(y_pred)
  16. model.compile(optimizer='rmsprop',
  17. loss='binary_crossentropy',
  18. metrics=['accuracy', mean_pred])

Training

Keras models are trained on Numpy arrays of input data and labels. For training a model, you will typically use the fit function. Read its documentation here.

  1. # For a single-input model with 2 classes (binary classification):
  2. model = Sequential()
  3. model.add(Dense(32, activation='relu', input_dim=100))
  4. model.add(Dense(1, activation='sigmoid'))
  5. model.compile(optimizer='rmsprop',
  6. loss='binary_crossentropy',
  7. metrics=['accuracy'])
  8. # Generate dummy data
  9. import numpy as np
  10. data = np.random.random((1000, 100))
  11. labels = np.random.randint(2, size=(1000, 1))
  12. # Train the model, iterating on the data in batches of 32 samples
  13. model.fit(data, labels, epochs=10, batch_size=32)
  1. # For a single-input model with 10 classes (categorical classification):
  2. model = Sequential()
  3. model.add(Dense(32, activation='relu', input_dim=100))
  4. model.add(Dense(10, activation='softmax'))
  5. model.compile(optimizer='rmsprop',
  6. loss='categorical_crossentropy',
  7. metrics=['accuracy'])
  8. # Generate dummy data
  9. import numpy as np
  10. data = np.random.random((1000, 100))
  11. labels = np.random.randint(10, size=(1000, 1))
  12. # Convert labels to categorical one-hot encoding
  13. one_hot_labels = keras.utils.to_categorical(labels, num_classes=10)
  14. # Train the model, iterating on the data in batches of 32 samples
  15. model.fit(data, one_hot_labels, epochs=10, batch_size=32)

Examples

Here are a few examples to get you started!

In the examples folder, you will also find example models for real datasets:

  • CIFAR10 small images classification: Convolutional Neural Network (CNN) with realtime data augmentation
  • IMDB movie review sentiment classification: LSTM over sequences of words
  • Reuters newswires topic classification: Multilayer Perceptron (MLP)
  • MNIST handwritten digits classification: MLP & CNN
  • Character-level text generation with LSTM

…and more.

Multilayer Perceptron (MLP) for multi-class softmax classification:

  1. import keras
  2. from keras.models import Sequential
  3. from keras.layers import Dense, Dropout, Activation
  4. from keras.optimizers import SGD
  5. # Generate dummy data
  6. import numpy as np
  7. x_train = np.random.random((1000, 20))
  8. y_train = keras.utils.to_categorical(np.random.randint(10, size=(1000, 1)), num_classes=10)
  9. x_test = np.random.random((100, 20))
  10. y_test = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10)
  11. model = Sequential()
  12. # Dense(64) is a fully-connected layer with 64 hidden units.
  13. # in the first layer, you must specify the expected input data shape:
  14. # here, 20-dimensional vectors.
  15. model.add(Dense(64, activation='relu', input_dim=20))
  16. model.add(Dropout(0.5))
  17. model.add(Dense(64, activation='relu'))
  18. model.add(Dropout(0.5))
  19. model.add(Dense(10, activation='softmax'))
  20. sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
  21. model.compile(loss='categorical_crossentropy',
  22. optimizer=sgd,
  23. metrics=['accuracy'])
  24. model.fit(x_train, y_train,
  25. epochs=20,
  26. batch_size=128)
  27. score = model.evaluate(x_test, y_test, batch_size=128)

MLP for binary classification:

  1. import numpy as np
  2. from keras.models import Sequential
  3. from keras.layers import Dense, Dropout
  4. # Generate dummy data
  5. x_train = np.random.random((1000, 20))
  6. y_train = np.random.randint(2, size=(1000, 1))
  7. x_test = np.random.random((100, 20))
  8. y_test = np.random.randint(2, size=(100, 1))
  9. model = Sequential()
  10. model.add(Dense(64, input_dim=20, activation='relu'))
  11. model.add(Dropout(0.5))
  12. model.add(Dense(64, activation='relu'))
  13. model.add(Dropout(0.5))
  14. model.add(Dense(1, activation='sigmoid'))
  15. model.compile(loss='binary_crossentropy',
  16. optimizer='rmsprop',
  17. metrics=['accuracy'])
  18. model.fit(x_train, y_train,
  19. epochs=20,
  20. batch_size=128)
  21. score = model.evaluate(x_test, y_test, batch_size=128)

VGG-like convnet:

  1. import numpy as np
  2. import keras
  3. from keras.models import Sequential
  4. from keras.layers import Dense, Dropout, Flatten
  5. from keras.layers import Conv2D, MaxPooling2D
  6. from keras.optimizers import SGD
  7. # Generate dummy data
  8. x_train = np.random.random((100, 100, 100, 3))
  9. y_train = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10)
  10. x_test = np.random.random((20, 100, 100, 3))
  11. y_test = keras.utils.to_categorical(np.random.randint(10, size=(20, 1)), num_classes=10)
  12. model = Sequential()
  13. # input: 100x100 images with 3 channels -> (100, 100, 3) tensors.
  14. # this applies 32 convolution filters of size 3x3 each.
  15. model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(100, 100, 3)))
  16. model.add(Conv2D(32, (3, 3), activation='relu'))
  17. model.add(MaxPooling2D(pool_size=(2, 2)))
  18. model.add(Dropout(0.25))
  19. model.add(Conv2D(64, (3, 3), activation='relu'))
  20. model.add(Conv2D(64, (3, 3), activation='relu'))
  21. model.add(MaxPooling2D(pool_size=(2, 2)))
  22. model.add(Dropout(0.25))
  23. model.add(Flatten())
  24. model.add(Dense(256, activation='relu'))
  25. model.add(Dropout(0.5))
  26. model.add(Dense(10, activation='softmax'))
  27. sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
  28. model.compile(loss='categorical_crossentropy', optimizer=sgd)
  29. model.fit(x_train, y_train, batch_size=32, epochs=10)
  30. score = model.evaluate(x_test, y_test, batch_size=32)

Sequence classification with LSTM:

  1. from keras.models import Sequential
  2. from keras.layers import Dense, Dropout
  3. from keras.layers import Embedding
  4. from keras.layers import LSTM
  5. max_features = 1024
  6. model = Sequential()
  7. model.add(Embedding(max_features, output_dim=256))
  8. model.add(LSTM(128))
  9. model.add(Dropout(0.5))
  10. model.add(Dense(1, activation='sigmoid'))
  11. model.compile(loss='binary_crossentropy',
  12. optimizer='rmsprop',
  13. metrics=['accuracy'])
  14. model.fit(x_train, y_train, batch_size=16, epochs=10)
  15. score = model.evaluate(x_test, y_test, batch_size=16)

Sequence classification with 1D convolutions:

  1. from keras.models import Sequential
  2. from keras.layers import Dense, Dropout
  3. from keras.layers import Embedding
  4. from keras.layers import Conv1D, GlobalAveragePooling1D, MaxPooling1D
  5. seq_length = 64
  6. model = Sequential()
  7. model.add(Conv1D(64, 3, activation='relu', input_shape=(seq_length, 100)))
  8. model.add(Conv1D(64, 3, activation='relu'))
  9. model.add(MaxPooling1D(3))
  10. model.add(Conv1D(128, 3, activation='relu'))
  11. model.add(Conv1D(128, 3, activation='relu'))
  12. model.add(GlobalAveragePooling1D())
  13. model.add(Dropout(0.5))
  14. model.add(Dense(1, activation='sigmoid'))
  15. model.compile(loss='binary_crossentropy',
  16. optimizer='rmsprop',
  17. metrics=['accuracy'])
  18. model.fit(x_train, y_train, batch_size=16, epochs=10)
  19. score = model.evaluate(x_test, y_test, batch_size=16)

Stacked LSTM for sequence classification

In this model, we stack 3 LSTM layers on top of each other,making the model capable of learning higher-level temporal representations.

The first two LSTMs return their full output sequences, but the last one only returnsthe last step in its output sequence, thus dropping the temporal dimension(i.e. converting the input sequence into a single vector).

stacked LSTM

  1. from keras.models import Sequential
  2. from keras.layers import LSTM, Dense
  3. import numpy as np
  4. data_dim = 16
  5. timesteps = 8
  6. num_classes = 10
  7. # expected input data shape: (batch_size, timesteps, data_dim)
  8. model = Sequential()
  9. model.add(LSTM(32, return_sequences=True,
  10. input_shape=(timesteps, data_dim))) # returns a sequence of vectors of dimension 32
  11. model.add(LSTM(32, return_sequences=True)) # returns a sequence of vectors of dimension 32
  12. model.add(LSTM(32)) # return a single vector of dimension 32
  13. model.add(Dense(10, activation='softmax'))
  14. model.compile(loss='categorical_crossentropy',
  15. optimizer='rmsprop',
  16. metrics=['accuracy'])
  17. # Generate dummy training data
  18. x_train = np.random.random((1000, timesteps, data_dim))
  19. y_train = np.random.random((1000, num_classes))
  20. # Generate dummy validation data
  21. x_val = np.random.random((100, timesteps, data_dim))
  22. y_val = np.random.random((100, num_classes))
  23. model.fit(x_train, y_train,
  24. batch_size=64, epochs=5,
  25. validation_data=(x_val, y_val))

Same stacked LSTM model, rendered "stateful"

A stateful recurrent model is one for which the internal states (memories) obtained after processing a batchof samples are reused as initial states for the samples of the next batch. This allows to process longer sequenceswhile keeping computational complexity manageable.

You can read more about stateful RNNs in the FAQ.

  1. from keras.models import Sequential
  2. from keras.layers import LSTM, Dense
  3. import numpy as np
  4. data_dim = 16
  5. timesteps = 8
  6. num_classes = 10
  7. batch_size = 32
  8. # Expected input batch shape: (batch_size, timesteps, data_dim)
  9. # Note that we have to provide the full batch_input_shape since the network is stateful.
  10. # the sample of index i in batch k is the follow-up for the sample i in batch k-1.
  11. model = Sequential()
  12. model.add(LSTM(32, return_sequences=True, stateful=True,
  13. batch_input_shape=(batch_size, timesteps, data_dim)))
  14. model.add(LSTM(32, return_sequences=True, stateful=True))
  15. model.add(LSTM(32, stateful=True))
  16. model.add(Dense(10, activation='softmax'))
  17. model.compile(loss='categorical_crossentropy',
  18. optimizer='rmsprop',
  19. metrics=['accuracy'])
  20. # Generate dummy training data
  21. x_train = np.random.random((batch_size * 10, timesteps, data_dim))
  22. y_train = np.random.random((batch_size * 10, num_classes))
  23. # Generate dummy validation data
  24. x_val = np.random.random((batch_size * 3, timesteps, data_dim))
  25. y_val = np.random.random((batch_size * 3, num_classes))
  26. model.fit(x_train, y_train,
  27. batch_size=batch_size, epochs=5, shuffle=False,
  28. validation_data=(x_val, y_val))