Quickstart
End-to-end quickstart guide — from Maven setup to training an MNIST classifier in Deeplearning4j
This guide takes you from zero to a trained MNIST digit classifier in a single self-contained Java project. By the end you will have:
A working Maven project with the correct M2.1 dependencies
A complete
MultiLayerNetworkthat classifies MNIST handwritten digitsA training loop with evaluation and score logging
A saved model you can reload later
No prior DL4J experience is assumed. You do need Java 11+ and Apache Maven installed.
Prerequisites
Java 11 or later (64-bit)
java -versionYou need a 64-bit JVM. If you see no jnind4j in java.library.path at runtime you are almost certainly running a 32-bit JVM.
Apache Maven 3.6+
mvn --versionIf you are on macOS with Homebrew:
brew install mavenAn IDE (recommended)
IntelliJ IDEA Community Edition works best because it has first-class Maven support. Eclipse and VS Code work too.
Step 1 — Create a Maven Project
Create a new Maven project, then replace the generated pom.xml with the one below (or add the relevant sections to your existing one).
pom.xml
Dependency notes
deeplearning4j-core
MultiLayerNetwork, ComputationGraph, all layer types
deeplearning4j-datasets
Built-in dataset downloaders including MNIST
deeplearning4j-ui
Web-based training visualization UI (port 9000)
nd4j-native-platform
CPU math backend with pre-built natives for Linux, macOS, Windows
logback-classic
Logging backend required by DL4J's SLF4J calls
GPU alternative: Replace nd4j-native-platform with nd4j-cuda-11.8-platform (or your CUDA version) and add deeplearning4j-cuda-11.8. The rest of the code stays identical.
Install dependencies:
Step 2 — Write the MNIST Classifier
Create the file src/main/java/com/example/MnistClassifier.java with the content below.
Step 3 — Build and Run
On first run, DL4J downloads the MNIST binary files (~12 MB) and caches them. Subsequent runs use the cache.
Expected training output (times vary by machine):
A well-configured MLP on MNIST reaches 97-98% accuracy within five epochs on the CPU. If you are seeing much lower accuracy, check the troubleshooting section below.
Understanding the Configuration
M2.1 API Differences from Older Versions
If you are migrating from DL4J 1.0.0-beta4 or earlier, the key API changes are:
Updaters: The enum-based updater API is removed. Use updater class instances:
DataType: Set it explicitly on the builder:
pretrain / backprop flags: These were removed. Standard supervised training always uses backpropagation. Remove any .pretrain(false).backprop(true) calls — they will cause a compilation error or warning.
Layer index: In M2.1 you can omit the integer index when adding layers with .layer(LayerBuilder) and they are added in order. The old .layer(0, new DenseLayer...) style still compiles but the index is redundant for MultiLayerNetwork.
Network Architecture Explained
The example uses a simple multilayer perceptron (MLP):
Input: MNIST images are 28x28 = 784 pixels, flattened to a 1D vector
Hidden layers:
DenseLayerwith ReLU activation learns non-linear representationsOutput:
OutputLayerwith softmax produces a probability distribution over 10 classes; negative log-likelihood (cross-entropy) is the loss functionXavier initialization: Keeps activation variance stable at initialization, important for deep networks
Adam optimizer: Adaptive learning rate per parameter; usually converges faster than plain SGD
L2 regularization: Penalizes large weights to reduce overfitting
Step 4 — Load and Use the Saved Model
ModelSerializer stores both the network configuration and the trained weights in a single .zip file. The normalizer (if you used one) can also be saved alongside:
Adding a Convolutional Network (Optional)
For images, a convolutional network significantly outperforms an MLP. Here is the configuration change — everything else (training loop, saving) stays the same:
This CNN typically reaches 99%+ accuracy on MNIST within five epochs.
Troubleshooting
NoAvailableBackendException at startup
The ND4J backend JAR is missing from the classpath. Confirm nd4j-native-platform is in your pom.xml and that mvn dependency:resolve completed without errors. If you are running from an IDE, reimport the Maven project.
no jnind4j in java.library.path
You are running a 32-bit JVM. Install a 64-bit JDK. Check with java -d64 -version.
Very low accuracy (below 80% after epoch 1)
Common causes:
Data not normalized — MNIST loaded via
MnistDataSetIteratoris normalized to [0, 1] automatically, but if you load your own images you need aDataNormalizationpreprocessorLearning rate too high or too low — try values between
1e-4and1e-2Batch size too small — try 32 to 256
OutOfMemoryError (heap)
Increase JVM heap: java -Xmx4g -cp ...
DL4J allocates tensor data off-heap (in native memory). If you see off-heap OOM errors, set Nd4j.getMemoryManager().setAutoGcWindow(5000) to trigger GC more frequently, or tune the off-heap limit with -Dorg.bytedeco.javacpp.maxbytes=2G.
Windows: UnsatisfiedLinkError
Conflicting native DLLs on PATH. Add -Djava.library.path="" to VM options in your IDE run configuration.
Next Steps
Core Concepts: Read Core Concepts to understand
MultiLayerNetworkvsComputationGraph, the training pipeline, and the ND4J relationshipMore examples: Clone the DL4J examples repository for CNNs, RNNs, transfer learning, and more
Custom layers: See the custom layers guide
Training on Spark: See the distributed training guide
Keras import: Trained a model in Keras? Import it with the Keras model import guide
Hyperparameter tuning: Use Arbiter for automated hyperparameter search
API reference: Browse the Deeplearning4j Javadoc
Last updated
Was this helpful?