Table Of Contents


Built with 🛠 MkDocs - Theme 🖤 Github.

Saving and Loading a Model

Save the trained network so it can make predictions without retraining every time the application starts.

Attach preprocessing

If training used a fitted standardizer or scaler, attach it before saving:

neuralNet.setNormalizer(standardizer);

For Min-Max scaling, attach the scaler instead:

neuralNet.setNormalizer(scaler);

This keeps the model and its input transformation together as one prediction pipeline.

Save the model

Create the destination directory and save the network:

import java.nio.file.Files;
import java.nio.file.Path;

private static final String MODEL_PATH = "models/model.dnet";

Files.createDirectories(Path.of("models"));
neuralNet.save(MODEL_PATH);

Load the model

Load the saved network with the expected model class:

import deepnetts.net.FeedForwardNetwork;
import deepnetts.util.FileIO;

FeedForwardNetwork neuralNet = FileIO.createFromFile(
        MODEL_PATH,
        FeedForwardNetwork.class
);

createFromFile(...) can throw IOException and ClassNotFoundException; handle or declare them according to the surrounding application.

Load a saved CNN with its own model class:

import deepnetts.net.ConvolutionalNetwork;

ConvolutionalNetwork network = FileIO.createFromFile(
        "models/image-classifier.dnet",
        ConvolutionalNetwork.class
);

Saving the network does not remove the image input contract. Keep the expected width, height, channel order, value scaling, and class-label order alongside the model artifact.

Verify the saved artifact

It preserves the trained network state and can also carry the fitted preprocessing attached before saving.

A loaded model must transform new inputs exactly as training inputs were transformed.

Was this helpful?