Machine Learning – JavaFX + Spring Boot + DL4J application template

Machine Learning – JavaFX + Spring Boot + DL4J application template

I want to share with you the application that will allow you to effectively start the journey through the world of artificial neural networks. The goal of the template will be to provide the Graphical User Interface and organize the application code in a way that allows you to focus only on issues related to machine learning. The GUI will be written using JavaFX and Spring Boot frameworks. We will use a Java distributed computing library, called DL4J as the main machine learning framework.

  1. What will you learn from this guide
  2. Project configuration
  3. How to use the application template
  4. The application template under the hood
  5. What’s next?

Application sources

  • Standalone template: zip
  • Repository: git clone

1. What will you learn from this guide

Machine learning is not a concept as new as it might seem. Its origins can be considered the fifties and sixties of the last century. In simplified terms, it consists in using statistical techniques in computer systems,so that they learn to solve problems without the need to explicitly coding of algorithms. In the case of neural networks, this effect is obtained by sensitizing it to stimuli, or input features and expecting a specific response from it. Therefore, it should not come as a surprise that this topic requires knowledge from many fields starting from statistics, through programming, to topics related to BigData.

To simplify the problem discussed a bit, I decided to write an application template that will remove the need to invent your own GUI and allow you to quickly perform various experiments with neural networks.

The application contains a button bar that allow you to properly load and save the current state of the neural network, perform training and test the network on a separate set of data. The rest of the form can be freely used, for example for the visualization of the network, which I will show in the next guide.

In addition, in the template I created a component that allows you to launch the Deeplearning4j UI server, witch allows you to track the network status and learning progress.

2. Project configuration

I based the application template on the project described in the previous article. If you have not read it yet, I recommend doing it because it will be much easier for you to understand how the template works under the hood.

Based on the mentioned project, I added the configuration for deeplearning4j to build.gradle file.

buildscript {
    ext {
        dl4j_use_cuda = false
        dl4j_version = "1.0.+"

    repositories {
    dependencies {
        classpath "org.springframework.boot:spring-boot-gradle-plugin:2.+"

apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group 'com.bettercoding.dl4j'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {

dependencies {

    compile group: 'javax.el', name: 'javax.el-api', version: '3.0.0'

    compile "org.deeplearning4j:deeplearning4j-core:${dl4j_version}"
    if (dl4j_use_cuda) {
        compile "org.nd4j:nd4j-cuda-8.0-platform:${dl4j_version}"
    } else {
        compile "org.nd4j:nd4j-native-platform:${dl4j_version}"
    compile "org.deeplearning4j:arbiter-ui_2.11:${dl4j_version}"
    compile group: 'org.datavec', name: 'datavec-data-codec', version: "${dl4j_version}"

    testCompile group: 'junit', name: 'junit', version: '4.12'

I also added a switch dl4j_use_cuda, because sooner or later we will go on to perform calculations on the CUDA platform. We will talk about CUDA i one of n the further parts of the machine learning cycle.

3. How to use the application template

I have prepared two points that allow the template to be adapted to future projects. The first is custom-learning-gui.fxml form, used to implement a project-specific GUI part. The second element is the

CustomLearningGuiControllerImpl bean, which is as the controller for the mentioned form, as well as providing the missing implementation of methods. We will define future networks, implement data processing and network learning algorithms in it.

There are properties defined in file, that you can change behaviour of the template.

use-ui=true                   #Turn on/off UI sevrer
nn-file=saved-network.dat     #The path of the file where save/load neural network
gui-refresh-interval-ms=5000  #The interval of custom UI refresh method invocation

The UI server is started by default on the port 9000. If you set flag use-ui=true and and enter the address http://localhost:9000, you will see the UI server console. In the next article, I will describe in detail how to build an application based on the template discussed here.

4. The application template under the hood

The template consists of the main form called learning-gui.fxml containing the previously mentioned buttons (Load, Save, Train and Test), which has included the custom-learning-gui.fxml form. It is intended for the implementation of the future part of the GUI – not yet known and different for each application.

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import javafx.scene.layout.BorderPane?>
<BorderPane xmlns:fx="" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity"

        <ButtonBar prefHeight="40.0" prefWidth="200.0" BorderPane.alignment="CENTER">
                <Label fx:id="counterText" text="Train loop: 0" prefWidth="120"/>
                <Button mnemonicParsing="false" text="Load" onAction="#loadAction" fx:id="btnLoad"/>
                <Button mnemonicParsing="false" text="Save" onAction="#saveAction" fx:id="btnSave"/>
                <ToggleButton mnemonicParsing="false" text="Train" onAction="#trainAction" fx:id="btnTrain"/>
                <Button mnemonicParsing="false" text="Test" onAction="#testAction" fx:id="btnTest"/>
        <fx:include source="custom-learning-gui.fxml"/>

The form is supported by the LearningGuiController controller, which I will discuss in more detail, because you can find some useful information in its code. This code can be found in the repository.

The controller class contains fields associated with mentioned buttons. We achieve this effect by using an annotation @FXML and naming fields as the fx:id attribute values defined in learning-gui.fxm file.

The counterProperty field is used as traint loop counter and is bind with the counterText label.

Class UIServerComponent is a component that manages the state of the UI server. The interface CustomLearningGuiController and its purpose I discussed earlier.

The method named initialize marked by @FXML annotation is executed just after binding the controls marked by @FXML annotation. You can think of it as a constructor in the JavaFX world. I used it to prepare the initial state of the form.

In the first step, I prepare Timeline, which will allow you to execute a GUI refresh code. I am talking about a costly process that is called periodically. An example of this is the visualization of learning results of a neural network every few seconds. Then the customLearningGuiController.onInitialize() method is called. It’s allows you to handle the initlialize event. The last step is to start the UI server and run the GUI refresh timeline.

package com.bettercoding.dl4j.controller;

public class LearningGuiController {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final IntegerProperty counterProperty = new SimpleIntegerProperty();

    private Button btnLoad;
    private Button btnSave;
    private ToggleButton btnTrain;
    private Button btnTest;

    private Label counterText;

    private Timeline guiRefreshTimeline;

    private String nnFile;

    private double guiRefreshIntervalMs;

    private UIServerComponent uiServerComponent;

    private CustomLearningGuiController customLearningGuiController;

    private void initialize() {
        guiRefreshTimeline = new Timeline(new KeyFrame(Duration.millis(guiRefreshIntervalMs), event -> {

        counterText.textProperty().bindBidirectional(counterProperty, new NumberStringConverter("Train loop: ######"));





The next pair of actions worth paying attention to is loading and writing the neural network to a file. I use ModelSerializer class for this purpose.

    protected void onLoadAction() {
        try {
            showAlert(Alert.AlertType.INFORMATION, "Success", "Neural network successfully loaded from " + nnFile);
        } catch (IOException e) {
            logger.error("Loading neural network error", e);
            showAlert(Alert.AlertType.ERROR, "Loading neural network error", e.getMessage());

    protected void onSaveAction() {
        try {
            ModelSerializer.writeModel(customLearningGuiController.onGetNeuralNetwork(), nnFile, true);
            showAlert(Alert.AlertType.INFORMATION, "Success", "Neural network successfully saved to " + nnFile);
        } catch (IOException e) {
            logger.error("Saving neural network error", e);
            showAlert(Alert.AlertType.ERROR, "Saving neural network error", e.getMessage());

Neural network learning process is carried out using the following methods. The first one is responsible for blocking or unblocking the corresponding buttons and initiating the learning process by calling Platform.runLater(this::trainLoop) , which will run the trainLoop method in the next JavaFX cycle.

The trainLoop method contains the logic associated with counting the number of learning loops and for executing externally supplied code responsible for network learning. If the training button is pressed, the method will schedule its execution for the next JavaFX cycle.

    public void trainAction(ActionEvent actionEvent) {
        boolean trainingMode = btnTrain.isSelected();
        if (btnTrain.isSelected()) {

    private void trainLoop() {
        if (btnTrain.isSelected()) {
            counterProperty.setValue(counterProperty.get() + 1);
            long loopNo = counterProperty.get();
            logger.debug("Train Loop: {}", loopNo);

It is also worth looking into the file, where you will find utility methods for data range conversion, as well as methods that create images based on the result of the network neural.

package com.bettercoding.dl4j.utils;

public final class ImageUtils {
    public static final Random RANDOM = new Random();

    public static Color randomColor();

    public static WritableImage emptyImage(Color color, int width, int height) ;

    public static WritableImage drawImage(INDArray data, int width, int height);

    private static double trimToRange0to1(double value) ;

    private static double trimToRange(double value, double min, double max);

    public static DataSet convertToDataSet(Image inputImage, Image expectedImage) ;

    private static double scaleColor(double value) ;

    private static double scale(int value, int rangeSize);

    private static double scale(int value, int rangeSize, double targetRange) ;

5. What’s next?

If you think this post is valuable, please leave me +1 or just share it. This action will allow me to reach a wider audience.
Thank You in advance.
0 0 vote
Article Rating
Notify of
newest most voted
Inline Feedbacks
View all comments
2 years ago

[…] Machine Learning – JavaFX + Spring Boot + DL4J application template […]

1 year ago

thank you

1 year ago

Firsly, thanks your work. Do you have any nn-file?