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

Neural Networks

The MultiLayerNetwork API — building, configuring, training, evaluating, and using sequential neural networks

Overview

MultiLayerNetwork is the primary API for building sequential (stack-of-layers) neural networks in Eclipse Deeplearning4j. It covers the vast majority of practical use cases: feedforward classifiers and regressors, CNNs for image recognition, and RNNs for sequence data.

Use MultiLayerNetwork when:

  • Your network has a single input and a single output.

  • Layers connect in a straight chain: input -> layer 0 -> layer 1 -> ... -> output.

Use ComputationGraph instead when you need skip/residual connections, multiple inputs, or multiple outputs.


Building a Network

NeuralNetConfiguration.Builder (M2.1 API)

All network configuration starts with NeuralNetConfiguration.Builder. In M2.1 the global updater, weight initializer, regularization, and data type are set here and apply to every layer unless overridden at the layer level.

import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.layers.DenseLayer;
import org.deeplearning4j.nn.conf.layers.OutputLayer;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.nd4j.linalg.activations.Activation;
import org.nd4j.linalg.api.buffer.DataType;
import org.nd4j.linalg.learning.config.Adam;
import org.nd4j.linalg.lossfunctions.LossFunctions;

MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
    .seed(42)
    .dataType(DataType.FLOAT)                          // use 32-bit floats
    .weightInit(WeightInit.XAVIER)
    .updater(new Adam(1e-3))                           // M2.1: pass lr to constructor
    .l2(1e-4)                                          // L2 regularization
    .list()
    .layer(new DenseLayer.Builder()
        .nIn(784).nOut(256)
        .activation(Activation.RELU)
        .build())
    .layer(new DenseLayer.Builder()
        .nIn(256).nOut(128)
        .activation(Activation.RELU)
        .build())
    .layer(new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
        .nIn(128).nOut(10)
        .activation(Activation.SOFTMAX)
        .build())
    .build();

Key M2.1 differences from older API:

  • dataType(DataType.FLOAT) replaces the old global float/double flags.

  • new Adam(lr) — the updater is constructed directly with the learning rate. No separate .learningRate() call.

  • .pretrain(false).backprop(true) is removed — standard backprop is always used.

  • Layer indices are optional: use .layer(layerConf) without an index for automatic ordering.

Global Builder Options

Method
Description

.seed(long)

Random seed for reproducibility

.dataType(DataType)

Numeric precision: DataType.FLOAT or DataType.DOUBLE

.weightInit(WeightInit)

Default weight initializer for all layers

.updater(IUpdater)

Optimizer: new Adam(lr), new Sgd(lr), new Nesterovs(lr, momentum), etc.

.l1(double)

Global L1 regularization coefficient

.l2(double)

Global L2 regularization coefficient

.dropout(double)

Global dropout retain probability (applied after each layer)

.activation(Activation)

Default activation for layers that do not specify their own

.gradientNormalization(GradientNormalization)

Clip gradients by value or norm

.gradientNormalizationThreshold(double)

Threshold for gradient clipping


Initializing and Inspecting the Network

init() allocates parameter arrays, runs weight initialization, and wires up the internal computation graph. It must be called before any training or inference.

Printing a Summary

Output includes each layer's name, type, output shape, number of parameters, and connected layers. Extremely useful for catching misconfigured nIn/nOut values.


Training

Fitting with a DataSetIterator

The standard training loop passes a DataSetIterator directly to fit():

Fitting a Single DataSet

For small datasets held in memory:

Fitting with Raw Arrays

Attaching a ScoreIterationListener

Other useful listeners: PerformanceListener, EvaluativeListener, CheckpointListener.


Inference

output()

Runs a full forward pass and returns the activations of the last layer:

feedForward()

Returns activations of every layer as a List<INDArray>:

Useful for extracting intermediate representations for transfer learning or visualization.

predict()

Returns predicted class index for each example (classification only):


Evaluation

Classification

Regression

Using evaluateDataSet Convenience Method


Parameter Access

Viewing All Parameters

Getting and Setting Layer Parameters

Standard parameter keys: "W" for weights, "b" for bias. Convolutional layers use "W" for the filter tensor.


Gradient Access

Gradients are available after a backward pass (which happens automatically during training):


Saving and Loading

Pass false as the third argument to writeModel if you only need inference (smaller file, no updater state).

JSON / YAML Configuration


Common Patterns

Simple MLP Classifier (M2.1)

LeNet-Style CNN

setInputType() automatically inserts the necessary FeedForwardToCnnPreProcessor and calculates nIn for the first dense layer. You do not need to specify nIn on layers that follow convolutional blocks when using this feature.

Regression with MSE Loss

LSTM for Sequence Classification


Step-by-Step Inference (RNNs)

For RNNs where you want to feed one time step at a time and preserve state between calls:


Key API Reference

Method
Description

init()

Allocate and initialize parameters

fit(DataSetIterator)

Train for one epoch over the iterator

fit(DataSet)

Train on a single batch

output(INDArray)

Forward pass, returns last layer activations

feedForward(INDArray, boolean)

Forward pass, returns all layer activations

predict(INDArray)

Returns predicted class indices

evaluate(DataSetIterator)

Returns Evaluation object

evaluateRegression(DataSetIterator)

Returns RegressionEvaluation object

params()

Returns flat INDArray of all parameters

paramTable()

Returns Map<String, INDArray> of named parameters

getLayer(int)

Returns a specific layer by index

numLayers()

Total number of layers

summary()

Human-readable architecture summary

rnnTimeStep(INDArray)

One-step RNN inference with state maintenance

rnnClearPreviousState()

Reset RNN hidden state

setListeners(TrainingListener...)

Attach training listeners

score()

Returns the most recent training loss

computeGradientAndScore()

Manually trigger forward + backward pass

gradient()

Returns Gradient object after backward pass

Last updated

Was this helpful?