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

Functional Model

Importing Keras Functional API models as ComputationGraph

Importing Keras Functional API Models

Keras Functional API models (keras.models.Model) are directed acyclic graphs with arbitrary topology: multiple inputs, multiple outputs, shared layers, and residual or skip connections are all supported. In DL4J, these map to ComputationGraph.


Define a Functional Model in Keras

from keras.models import Model
from keras.layers import Dense, Input

inputs = Input(shape=(100,))
x = Dense(64, activation='relu')(inputs)
predictions = Dense(10, activation='softmax')(x)

model = Model(inputs=inputs, outputs=predictions)
model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])

Saving the Model

Keras provides several serialization options. Each is supported for import:

# Option 1: Save everything in a single HDF5 file (recommended)
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 want to continue training in DL4J after import, use model.save(...) (Option 1). It preserves the training configuration (optimizer, loss, metrics). The other options do not include training configuration.


Loading the Model in Java

Load Full Model

This is the recommended path when the model was saved with model.save():

If the Keras model was not compiled before saving, skip training configuration enforcement:

Load from Separate Config and Weights

When architecture and weights were saved separately:

Load Configuration Only

To load just the graph topology without weights:


Running Inference

After import, inference on a ComputationGraph follows DL4J conventions. output() accepts one or more INDArray inputs and returns an array of outputs (one per output node):

For models with multiple inputs:


KerasModel API Reference

The KerasModel class underlies KerasModelImport when importing Functional API models. Use it directly when you need more control:


KerasModel

source

Builds a ComputationGraph from a Keras Functional API model configuration.

Constructor

Recommended builder-pattern constructor. Use KerasModelBuilder to configure the import (model file, training config enforcement, etc.) before building.

Parameters:

  • modelBuilder — a configured KerasModelBuilder instance

Throws:

  • IOException — IO exception

  • InvalidKerasConfigurationException — invalid Keras configuration

  • UnsupportedKerasConfigurationException — unsupported Keras configuration


getComputationGraphConfiguration

Returns the ComputationGraphConfiguration from the parsed Keras model configuration. Training-related settings that are not supported (e.g., unknown regularizers) are ignored or throw exceptions depending on the enforceTrainingConfig flag.


getComputationGraph

Builds and returns a ComputationGraph from this model configuration, with weights loaded.


getComputationGraph (with weight control)

Builds and returns a ComputationGraph. Pass importWeights=false to obtain a randomly-initialized graph with the correct architecture.

Parameters:

  • importWeights — whether to load weights from the HDF5 source


Example: ResNet-style Skip Connections

The Functional API allows residual connections that cannot be expressed in a Sequential model. DL4J's ComputationGraph handles these natively.

Python

Java


Example: Multi-Input Model

Java


Troubleshooting

Wrong number of inputs at inference time: ensure that the order of INDArray arguments to model.output(...) matches the order of inputs in the Keras model's inputs list.

ComputationGraph vs MultiLayerNetwork: functional models always load as ComputationGraph. Passing a Functional API model path to importKerasSequentialModelAndWeights will fail. Use importKerasModelAndWeights instead.

Merge layer axis: the Dot merge layer is not supported. All other standard Keras merge layers (Add, Multiply, Subtract, Average, Maximum, Concatenate) are supported.

Last updated

Was this helpful?