For the complete documentation index, see llms.txt. This page is also available as Markdown.

Sequential Model

Importing Keras Sequential models as MultiLayerNetwork

Importing Keras Sequential Models

Keras Sequential models are linear stacks of layers with a single input and a single output. They map directly to DL4J's MultiLayerNetwork.


Define a Sequential Model in Keras

from keras.models import Sequential
from keras.layers import Dense

model = Sequential()
model.add(Dense(units=64, activation='relu', input_dim=100))
model.add(Dense(units=10, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])

Saving the Model

Keras provides several serialization options, each corresponding to a different import method in DL4J:

# Option 1: Save full model — architecture, weights, and training config
model.save('full_model.h5')

# Option 2: Save architecture as JSON
model_json = model.to_json()
with open("model_config.json", "w") as f:
    f.write(model_json)

# Option 3: Save weights only
model.save_weights('model_weights.h5')

If you intend to continue training the model in DL4J after import, use model.save(...) so that the training configuration (optimizer settings, loss function) is preserved. The other options omit training configuration.


Loading the Model in Java

If the Keras model was not compiled (no training configuration in the HDF5 file), pass false for enforceTrainingConfig:

Load from Separate Config and Weights Files

Load Configuration Only


Running Inference

After import, inference follows standard DL4J conventions:


Training After Import

If the model was imported with training configuration, you can continue training directly:

For larger datasets, use a DataSetIterator:


KerasSequentialModel API Reference

The KerasSequentialModel class underlies KerasModelImport for Sequential models.


KerasSequentialModel

source

Builds a MultiLayerNetwork from a Keras Sequential model configuration.

getMultiLayerConfiguration

Returns the MultiLayerConfiguration from the parsed Keras Sequential model configuration.


getMultiLayerNetwork

Builds and returns a MultiLayerNetwork from this Keras Sequential model configuration, with weights loaded.


getMultiLayerNetwork (with weight control)

Builds and returns a MultiLayerNetwork. Pass importWeights=false to get a randomly-initialized network with the correct architecture.

Parameters:

  • importWeights — whether to import weights from the HDF5 source


Example: CNN for Image Classification

Python

Java


Example: LSTM for Sequence Classification

Python

Java


Troubleshooting

Model loads as ComputationGraph by mistake: ensure you call importKerasSequentialModelAndWeights (not importKerasModelAndWeights) for Sequential models.

Input shape mismatch: DL4J uses NCHW for images (channels first) while Keras defaults to NHWC (channels last). The importer handles this transpose automatically for Conv2D and pooling layers. However, if you build INDArray inputs manually, verify the expected shape from model.summary().

LSTM input ordering: DL4J RNN layers expect [batch, features, timesteps], which is the transpose of Keras's [batch, timesteps, features]. The importer adds the necessary RnnToFeedForwardPreProcessor and FeedForwardToRnnPreProcessor where needed, but verify the input array ordering when constructing inputs manually.

Last updated

Was this helpful?