Neural networks and Deep learning tips and samples using Java

View on GitHub

Neural Networks and Deep Learning using Java

Cleuton Sampaio - LinkedIn

Convolutional Neural Network

Original source code here

It is a double Neural Network model composed by some convolutional layers (not all neurons are connected), dedicated to extract image features, and some dense connected layers, which classify the image by its features.

Here you have my post explining how a CNN works.

Java implementation

We can create any neural network model with Java, including CNN. A CNN requires images pre-processing in order to raise the accuracy.

In this demo we’ll use:

Image database

The Labeled Faces in the Wild is a public image database that can be used to train a CNN.

We need to pre-process the imagens, extracting and aligning the faces, and also converting them to grayscale. For example:emplo:

Original image:

Prepared image:

Image preprocessing

Class has method getFaces(), which uses OpenIMAJ to detect, extract and align faces, creating new images.

public class PrepareFaces {
	public static List<BufferedImage> getFaces(String imagePath) throws IOException {
		List<BufferedImage> facesList = new ArrayList<BufferedImage>();
		File arq = new File(imagePath);
		BufferedImage imagem =;
		FImage fimage = ImageUtilities.createFImage(imagem);
		FKEFaceDetector detector = new FKEFaceDetector(1);
		List<KEDetectedFace> faces = detector.detectFaces(fimage);	
		RotateScaleAligner aligner = new RotateScaleAligner();
		for (KEDetectedFace face : faces) {
			FImage aligned = aligner.align(face);
			BufferedImage bfi = ImageUtilities.createBufferedImage(aligned);
		return facesList;
	public static Set<String> prepareImages(String sourcePath, String targetPath) throws IOException {
		Set<String> names = new HashSet<String>();
		File[] files = new File(sourcePath).listFiles();
	    for (File file : files) {
	    	String name = getNameFromFile(file);
	    	List<BufferedImage> faces = getFaces(file.getAbsolutePath());
	    	int faceCount = 0;
	    	for (BufferedImage img : faces) {
	    		int pos = file.getName().indexOf('.');
	    		String fileName = file.getName().substring(0,pos) + faceCount + ".jpg";
	    		File outputfile = new File(targetPath + "/" +  fileName);
	    		ImageIO.write(img, "jpg", outputfile);
	        System.out.println("Name: " + name);
	    return names;

Model creation

I created the model using Deeplearning4J in class TrainModel:

	private static final Logger log = Logger.getLogger(TrainModel.class.getName());
	public static void train(String imagePath, String modelPath, int numLabels, String testImage) throws IOException {
		// Random
		int seed = 42;
		Random random = new Random(seed);
		// Hiperparameters
		int height = 80;
		int width = 80;
		int channels = 1;
		int batchSize = 10;
		double trainTestRatio = 0.7;
		int iterations = 1;
		int epochs = 50;
		double learningRate = 0.01;
		// Prepare dataset:
        LabelGen labelMaker = new LabelGen();
        File mainPath = new File(imagePath);
        FileSplit fileSplit = new FileSplit(mainPath, NativeImageLoader.ALLOWED_FORMATS, random);
        int numExamples = Math.toIntExact(fileSplit.length());
        // Network configuration:
        MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
                .updater(new Adam(1e-3))
                .layer(new ConvolutionLayer.Builder(5, 5)
                .layer(new SubsamplingLayer.Builder(PoolingType.MAX)
                .layer(new ConvolutionLayer.Builder(5, 5)
                .layer(new SubsamplingLayer.Builder(PoolingType.MAX)
                .layer(new DenseLayer.Builder().activation(Activation.RELU)
                .layer(new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
        MultiLayerNetwork network = new MultiLayerNetwork(conf);


To get the classes from the file name, I had to create class LabelGen, implementing interface PathLabelGenerator.

GPU usage

This code uses the GPU to train the Neural Network. To use the GPU I had to include this in the pom.xml:


How to run the code

When you run a mvn clean package it will create an uber jar. Just run it with the arguments:

  1. raw images path
  2. processed images path
  3. model save path
  4. test image path