Exploring Java Machine Learning Libraries
Machine learning is no longer limited to applications built with Python. Java developers can also build applications that learn from data, identify patterns, classify information, and make predictions using machine learning models. With the growing number of machine learning libraries available for the Java ecosystem, it is possible to incorporate these capabilities into existing enterprise applications without necessarily introducing a separate Python service.
However, choosing a machine learning library involves more than comparing the algorithms it supports. One of the first decisions is whether an application needs to train a model or perform inference using an existing model. Although these operations are closely related, they have different requirements and often benefit from different tools.
Training involves providing an algorithm with data so that it can learn the parameters needed to make predictions. This process may involve preparing datasets, selecting features, choosing an algorithm, configuring hyperparameters, and evaluating the resulting model. Inference, on the other hand, uses an already-trained model to process new input and produce a prediction. It is usually performed repeatedly as part of an application’s normal operation, making prediction speed, memory consumption, deployment requirements, and model compatibility important considerations.
Java provides several libraries that address these requirements. Smile and Tribuo provide APIs for developing and training traditional machine learning models directly in Java. Deep Java Library (DJL) provides a higher-level interface for working with deep learning frameworks, while ONNX Runtime allows Java applications to execute models exported from other machine learning ecosystems. Weka provides an interactive environment for exploring datasets and experimenting with algorithms, whereas Apache Spark MLlib is designed for machine learning workloads that operate across distributed data processing environments.
In this article, we examine these libraries, compare their capabilities, and look at how they fit into Java applications.
1. Understanding Model Training and Inference
Before looking at the available libraries, it is worth understanding the difference between training and inference. These two operations are the foundation of most machine learning applications, but they are not interchangeable.
1.1 Model Training
Training is the process of teaching a machine learning algorithm to recognise patterns in a dataset. The dataset contains examples, usually represented by input features and their corresponding expected outputs or labels. For example, consider an application that predicts whether a customer is likely to purchase a product. The training dataset might contain information such as the customer’s age, monthly income, previous purchases, and whether the customer eventually purchased the product.
The machine learning algorithm examines these examples and learns relationships between the input features and their corresponding labels. Depending on the selected algorithm, training may involve adjusting weights, building decision trees, identifying clusters, or calculating statistical relationships. The resulting model contains the learned parameters that can subsequently be used to make predictions.
1.2 Model Inference
Inference is the process of using a trained model to make predictions about new data. Unlike training, inference does not involve learning new parameters. Instead, the model receives input features and produces an output based on what it learned during training. For example, after training a customer purchasing prediction model, a Java application can provide information about a new customer and ask the model to predict whether that customer is likely to purchase a product.
The model might return a classification such as LIKELY_TO_PURCHASE or UNLIKELY_TO_PURCHASE, together with a probability or confidence score if the model supports it. The distinction is important because training and inference have different operational requirements.
| Requirement | Training | Inference |
|---|---|---|
| Main purpose | Learn patterns from data | Make predictions |
| Input | Training dataset and labels | New input features |
| Output | Trained model | Prediction |
| Resource requirements | Can require substantial CPU, memory, and GPU resources | Usually optimised for prediction speed and memory |
| Frequency | Often performed periodically | Usually performed repeatedly |
| Deployment | Training environment or pipeline | Application or inference service |
A Java application does not necessarily need to perform both operations. An organisation might train its models using Python libraries such as scikit-learn or PyTorch and then export the resulting models for use in a Java application. Alternatively, a development team might implement the entire machine learning workflow in Java.
2. Overview of Java Machine Learning Libraries
There are several machine learning libraries available to Java developers. Although some libraries overlap in functionality, they have different strengths and are designed for different types of workloads. The following libraries are worth considering.
2.1 Smile
Smile (Statistical Machine Intelligence and Learning Engine) is a machine learning library written in Java. It provides implementations of traditional machine learning algorithms and tools for statistical computing, data processing, and model development.
Smile supports several machine learning tasks, including classification, regression, clustering, dimensionality reduction, and anomaly detection. Its classification algorithms include logistic regression, decision trees, random forests, support vector machines, and gradient boosting.
One of Smile’s advantages is that it provides a relatively direct API for working with numerical data and training models. Developers can provide feature arrays and corresponding labels without having to build an extensive data processing infrastructure. For example, training a logistic regression classifier can be accomplished with just a few lines of Java:
double[][] x = {
{20.0, 30.0},
{25.0, 35.0},
{30.0, 40.0},
{35.0, 45.0},
{40.0, 50.0},
{45.0, 55.0}
};
int[] y = {0, 0, 0, 1, 1, 1};
LogisticRegression model = LogisticRegression.fit(x, y);
The x array contains the training features, while y contains the corresponding class labels. Smile learns a logistic regression model from these examples. Once training is complete, the model can be used to classify new observations:
double[] customer = {32.0, 42.0};
int prediction = model.predict(customer);
System.out.println("Prediction: " + prediction);
The predict() method returns the predicted class. In this example, the result is represented by either 0 or 1. Smile is a good option when the objective is to build traditional machine learning models directly in Java without introducing a separate machine learning service.
When to consider Smile:
- Training traditional machine learning models in Java.
- Working with numerical datasets.
- Building classification and regression applications.
- Performing clustering and statistical analysis.
- Developing machine learning functionality within existing Java applications.
2.2 Tribuo
Tribuo is an open-source machine learning library developed by Oracle Labs. It provides a Java API for building, training, evaluating, and deploying machine learning models. Tribuo supports classification, regression, clustering, anomaly detection, and multi-label classification. It also provides integrations with external machine learning libraries, including XGBoost, TensorFlow, and ONNX Runtime.
One of the main differences between Tribuo and Smile is how they represent training data and models. Tribuo uses concepts such as Dataset, Example, Feature, Output, and Trainer. These abstractions provide a consistent structure for preparing data, configuring algorithms, training models, and making predictions.
For example, a classification problem uses Label to represent the expected output of an example. The training examples are collected in a Dataset, which is then passed to a trainer. A logistic regression model can be trained using the following code:
LabelFactory factory = new LabelFactory();
MutableDataset<Label> dataset = new MutableDataset<>(
new SimpleDataSourceProvenance("Training examples", factory),
factory
);
dataset.add(new ArrayExample<>(
new Label("NO"),
new String[]{"age", "income"},
new double[]{20.0, 30.0}
));
dataset.add(new ArrayExample<>(
new Label("NO"),
new String[]{"age", "income"},
new double[]{25.0, 35.0}
));
dataset.add(new ArrayExample<>(
new Label("YES"),
new String[]{"age", "income"},
new double[]{40.0, 50.0}
));
Model<Label> model =
new LogisticRegressionTrainer().train(dataset);
Here, MutableDataset holds the training examples, and each ArrayExample contains an output label, feature names, and feature values. The LogisticRegressionTrainer is responsible for learning the model from the dataset.
Tribuo places considerable emphasis on model provenance. A trained model can retain information about the training dataset, transformations, and configuration used during its creation. This helps development teams understand how a model was produced and reproduce the training process when necessary. The library provides model serialization and ONNX export for supported models, allowing trained models to be transferred and used across different environments.
When to consider Tribuo:
- Building traditional machine learning applications in Java.
- Working with structured datasets and labelled examples.
- Tracking model training configurations and provenance.
- Evaluating models using a consistent API.
- Integrating Java applications with other machine learning ecosystems.
2.3 Deep Java Library (DJL)
Deep Java Library (DJL) is an open-source deep learning framework designed to make deep learning accessible to Java developers. Unlike Smile and Tribuo, which provide implementations of traditional machine learning algorithms, DJL focuses on deep learning and provides an abstraction over different deep learning engines.
DJL supports engines such as PyTorch and TensorFlow, allowing developers to work with different deep learning implementations through a consistent Java API. The library provides functionality for:
- Training neural networks.
- Loading pretrained models.
- Performing image classification and object detection.
- Working with tensors and datasets.
- Running inference using supported deep learning engines.
One of DJL’s advantages is its engine-independent API. Developers can write much of their application code against DJL interfaces and select an appropriate engine through the dependencies included in the application. For example, a Java application might use DJL to load a pretrained image classification model and perform predictions on uploaded images without implementing the neural network architecture or training process itself.
When to consider DJL:
- Building deep learning applications in Java.
- Working with pretrained neural networks.
- Performing image classification and object detection.
- Training neural networks through supported engines.
- Using PyTorch or TensorFlow models from Java.
2.4 TensorFlow Java
TensorFlow Java provides Java developers with access to the TensorFlow machine learning framework directly from the JVM. It allows applications written in Java and other JVM languages to build, train, and execute machine learning models without requiring a separate Python application.
The Java implementation provides access to TensorFlow’s core functionality, including tensor operations, computational graphs, automatic differentiation, and neural network development. It supports both eager execution and graph-based execution, making it possible to develop different types of machine learning workloads.
TensorFlow Java is organised into several components:
- TensorFlow Core: Provides the fundamental Java bindings for interacting with the TensorFlow runtime.
- TensorFlow Framework: Provides higher-level utilities and APIs for building and training neural networks.
- TensorFlow NDArray: Provides functionality for creating and manipulating multidimensional arrays.
One advantage of TensorFlow Java is that developers can work with the TensorFlow ecosystem without leaving Java. For example, a development team can implement a neural network, prepare training tensors, configure an optimisation process, and execute model predictions within a Java application.
When to consider TensorFlow Java:
- Building and training neural networks directly in Java.
- Integrating TensorFlow functionality into enterprise Java applications.
- Working with tensors and computational graphs.
- Running existing TensorFlow models within a JVM environment.
- Using CPU or supported GPU execution environments.
2.5 ONNX Runtime
ONNX Runtime is an inference engine that allows applications to execute machine learning models saved in the Open Neural Network Exchange (ONNX) format. ONNX provides a common model representation that allows machine learning models to move between different frameworks and execution environments.
For example, a data science team might train a model using Python and scikit-learn, export it to ONNX, and then provide the resulting file to a Java application. The Java application can load the model using ONNX Runtime and perform predictions without needing the original Python training environment.
ONNX Runtime provides Java bindings that expose functionality for loading models, creating input tensors, executing inference sessions, and retrieving prediction results. A simplified Java inference workflow looks like this:
OrtEnvironment environment =
OrtEnvironment.getEnvironment();
try (OrtSession session =
environment.createSession("model.onnx")) {
// Create input tensors and execute inference.
}
The OrtEnvironment provides access to the runtime environment, while OrtSession represents a loaded model and its inference session. The application supplies input tensors that match the model’s expected input names, dimensions, and data types. ONNX Runtime executes the model and returns its outputs.
ONNX Runtime also provides different execution providers, including CPU and GPU-based execution options. This allows applications to select an appropriate execution environment depending on their deployment requirements. It is worth noting that ONNX Runtime is primarily an inference solution. It does not replace the machine learning framework used to train the original model.
When to consider ONNX Runtime:
- Serving models trained using Python frameworks.
- Integrating machine learning predictions into Java applications.
- Running models without deploying the original training framework.
- Deploying models across different platforms.
- Using CPU or GPU execution providers.
2.6 Weka
Weka is a collection of machine learning algorithms and data processing tools developed at the University of Waikato. Weka is different from many Java machine learning libraries because it provides both a Java API and a graphical environment for working with datasets and experimenting with algorithms.
Its graphical interface allows developers and data analysts to load datasets, inspect attributes, apply preprocessing operations, train models, and evaluate results without writing Java code for every operation. Weka supports classification, regression, clustering, association rule mining, and feature selection. Its algorithms include decision trees, random forests, support vector machines, and several other traditional machine learning techniques.
Weka is also available as a Java library, which means developers can incorporate its algorithms into their own applications. For example, a Java application can use Weka’s Instances class to represent a dataset, configure a classifier, train it, and use the resulting model to classify new instances. Weka is useful when exploring a dataset or comparing different algorithms before deciding which approach to use in an application.
When to consider Weka:
- Experimenting with machine learning algorithms.
- Exploring and analysing datasets through a graphical interface.
- Teaching machine learning concepts.
- Building applications using Weka’s Java API.
- Comparing classification and clustering algorithms.
2.7 Apache Spark MLlib
Apache Spark MLlib is the machine learning component of Apache Spark. It is designed for machine learning workloads that need to operate on large datasets within distributed data processing environments. Unlike Smile and Tribuo, which can train models directly within an ordinary Java application, MLlib is designed to work with Spark’s distributed computing infrastructure.
MLlib provides algorithms and tools for classification, regression, clustering, collaborative filtering, and feature engineering. It also provides machine learning pipelines that combine data transformations, feature extraction, model training, and evaluation. A simplified example of training a logistic regression model using the Spark Java API looks like this:
SparkSession spark = SparkSession.builder()
.appName("MachineLearningExample")
.master("local[*]")
.getOrCreate();
LogisticRegression lr = new LogisticRegression()
.setMaxIter(10)
.setRegParam(0.01);
LogisticRegressionModel model = lr.fit(trainingData);
Dataset<Row> predictions =
model.transform(testData);
The example creates a Spark session, configures a logistic regression algorithm, trains it using a Spark dataset, and then applies the resulting model to another dataset. Unlike the earlier examples, the training data here is represented by a Spark Dataset containing the expected feature and label columns. The features are normally assembled into a vector using Spark’s feature transformation APIs before training.
When to consider Spark MLlib:
- Training models using large datasets.
- Building distributed machine learning pipelines.
- Integrating machine learning with Spark SQL and structured data processing.
- Processing data across multiple machines.
- Working with existing Spark infrastructure.
3. Comparing Java Machine Learning Libraries
The libraries discussed above have different objectives. Some provide algorithms for training traditional machine learning models, while others focus on deep learning or executing models produced by external frameworks. The following table summarises some of their characteristics.
| Library | Main algorithms and capabilities | Primary use | License | Java requirement |
|---|---|---|---|---|
| Smile | Logistic regression, random forests, SVM, decision trees, clustering | Training and inference | GPL-3.0 for 4.4.2 | Java 21 |
| Tribuo | Logistic regression, SVM, random forests, clustering, regression | Training and inference | Apache 2.0 | Java 8+ core |
| DJL | Neural networks, deep learning, image classification, object detection | Training and inference | Apache 2.0 | Java 11+ |
| TensorFlow Java | Neural networks, tensor operations, computational graphs, deep learning | Training and inference | Apache 2.0 | Java 11+ |
| ONNX Runtime | Executes ONNX models from different frameworks | Inference | MIT | Java 8+ |
| Weka | Decision trees, random forests, SVM, clustering, regression | Training, inference and experimentation | GPL-3.0 | Java 8+ |
| Spark MLlib | Classification, regression, clustering, collaborative filtering, pipelines | Distributed training and inference | Apache 2.0 | Java 17, 21 or 25 |
Smile and Tribuo are good starting points for developers who want to train traditional machine learning models using Java. Both provide classification and regression algorithms, although their programming models and data representations differ.
DJL is more appropriate when working with neural networks and deep learning models. Its engine abstraction also makes it possible to work with different deep learning implementations.
ONNX Runtime is a good choice when a model has already been trained in another ecosystem and needs to be executed by a Java application. It avoids introducing the original training framework into the Java deployment environment.
Weka is well suited to experimentation and learning. Its graphical interface makes it easier to inspect data and compare algorithms before implementing a solution.
Spark MLlib is relevant when the machine learning workload is part of a distributed data processing pipeline. Its infrastructure introduces additional complexity, so it is not necessary for every application.
4. Building a Classification Model with Smile
This article builds a small classification application using Smile. The objective is to demonstrate how to prepare training data, train a logistic regression classifier, and use the resulting model to make predictions. We will use a simple customer purchasing example. The model will predict whether a customer is likely to purchase a product based on two input features:
- Age: The customer’s age.
- Monthly income: The customer’s monthly income, represented by a simplified numerical value.
For this demonstration, the output will have two possible classes:
0: The customer is unlikely to purchase.1: The customer is likely to purchase.
The dataset is deliberately small so that we can concentrate on the library APIs rather than data preparation. It is not intended to represent a production-quality purchasing prediction model.
4.1 Create the Project
Create a standard Maven Java project and add Smile as a dependency. Add the following dependency to the pom.xml file:
<dependency>
<groupId>com.github.haifengl</groupId>
<artifactId>smile-core</artifactId>
<version>7.3.0</version>
</dependency>
The smile-core dependency provides the core machine learning functionality, including the classification algorithms we need for this example.
4.2 Preparing the Training Dataset
The first step is to prepare the dataset. Smile allows us to represent numerical training data using a two-dimensional array. Each row represents one training example, while each column represents a feature. Create a class named SmileClassificationExample:
public class SmileClassificationExample {
public static void main(String[] args) {
// Training features: age and monthly income
double[][] x = {
{20.0, 30.0},
{22.0, 32.0},
{25.0, 35.0},
{28.0, 38.0},
{35.0, 45.0},
{38.0, 48.0},
{40.0, 50.0},
{45.0, 55.0},
{48.0, 58.0},
{50.0, 60.0}
};
// Expected class labels
int[] y = {
0, 0, 0, 0, 1,
1, 1, 1, 1, 1
};
}
}
The x array contains ten training examples, each with two features. The corresponding y array contains the expected class for each example. The relationship between the two arrays is positional. For example, x[0] represents the first customer, and y[0] contains the expected classification for that customer. Smile uses these arrays directly when training the classifier.
4.3 Training a Logistic Regression Model
With the dataset prepared, we can train a logistic regression classifier. We can then train the model using:
LogisticRegression model = LogisticRegression.fit(x, y);
The fit() method receives the training features and their corresponding labels. Smile uses this information to calculate the model parameters required for classification. Logistic regression is a supervised learning algorithm commonly used for classification problems. It is frequently used to predict the probability that an observation belongs to a particular class.
For binary classification, the model estimates the probability of an observation belonging to one of the two classes. A decision threshold is then used to determine the predicted class. This article’s example uses Smile’s default logistic regression configuration. For more advanced applications, the algorithm can be configured with different regularisation parameters and optimisation settings.
4.4 Performing Inference
Once the model has been trained, we can provide new customer information and request a prediction. Add the following code:
// New customer: age and monthly income
double[] newCustomer = {32.0, 42.0};
// Perform inference
int prediction = model.predict(newCustomer);
IO.println("Predicted class: " + prediction);
The predict() method receives the features of a new customer and returns the predicted class. Because the model has already been trained, there is no need to execute the training process again when making this prediction.
We can also provide multiple customers and perform predictions individually:
double[][] customers = {
{24.0, 34.0},
{33.0, 43.0},
{42.0, 52.0}
};
for (double[] customer : customers) {
int prediction = model.predict(customer);
IO.println("Predicted class: " + prediction);
}
This demonstrates how a trained model can be incorporated into an application that needs to classify incoming customer records.
4.5 Complete Smile Example
The following is the complete implementation:
public class SmileClassificationExample {
public static void main(String[] args) {
// Training features: age and monthly income
double[][] x = {
{20.0, 30.0},
{22.0, 32.0},
{25.0, 35.0},
{28.0, 38.0},
{35.0, 45.0},
{38.0, 48.0},
{40.0, 50.0},
{45.0, 55.0},
{48.0, 58.0},
{50.0, 60.0}
};
// Expected class labels
int[] y = {
0, 0, 0, 0, 1,
1, 1, 1, 1, 1
};
// Train logistic regression model
LogisticRegression model = LogisticRegression.fit(x, y);
IO.println("Model training completed.");
// New customer
double[] newCustomer = {32.0, 42.0};
// Perform inference
int prediction = model.predict(newCustomer);
IO.println("Predicted class: " + prediction);
// Predict for multiple customers
double[][] customers = {
{24.0, 34.0},
{33.0, 43.0},
{42.0, 52.0}
};
for (double[] customer : customers) {
IO.println("Customer prediction: " + model.predict(customer));
}
}
}
The example illustrates how little code is needed to train and use a traditional machine learning classifier with Smile. The application provides the training data, calls fit() to create the model, and uses predict() whenever it needs a classification.
For a real application, we would normally separate training from prediction, use a larger dataset, reserve test data for evaluation, and persist the trained model rather than retraining it whenever the application starts.
5. Building the Same Classification Model with Tribuo
We will now implement the same customer purchasing classification problem using Tribuo. The objective is to demonstrate how Tribuo represents training data and how its trainer abstraction differs from Smile’s direct array-based API.
Unlike Smile, Tribuo uses examples and datasets to represent training information. Each example contains named features and an expected output. This gives the library a more structured way of managing training data.
5.1 Create the Project
Create another Maven project and add the Tribuo dependency:
<dependency>
<groupId>org.tribuo</groupId>
<artifactId>tribuo-all</artifactId>
<version>4.3.2</version>
<type>pom</type>
</dependency>
We will use Tribuo 4.3.2, which supports Java 8 and later for its core functionality.
5.2 Defining the Training Dataset
Tribuo uses Label to represent classification outputs. We will use the same two classes as in the Smile example:
NO: The customer is unlikely to purchase.YES: The customer is likely to purchase.
We first create a LabelFactory, which is responsible for constructing classification labels.
public class TribuoClassificationExample {
public static void main(String[] args) {
LabelFactory factory = new LabelFactory();
MutableDataset<Label> dataset =
new MutableDataset<>(
new SimpleDataSourceProvenance(
"Customer purchasing training data",
factory
),
factory
);
}
}
The MutableDataset class provides a dataset that can be populated with training examples. We supply it with a provenance description and the output factory.
The provenance information describes where the training data originated. We use SimpleDataSourceProvenance here because the examples are created directly in the application. In a production application, a more descriptive data source and provenance implementation would be preferable.
5.3 Adding Training Examples
Each training example needs an output label, feature names, and feature values. Tribuo provides ArrayExample for constructing examples using arrays. We can populate the dataset as follows:
String[] featureNames = {"age", "income"};
double[][] x = {
{20.0, 30.0},
{22.0, 32.0},
{25.0, 35.0},
{28.0, 38.0},
{35.0, 45.0},
{38.0, 48.0},
{40.0, 50.0},
{45.0, 55.0},
{48.0, 58.0},
{50.0, 60.0}
};
String[] labels = {
"NO", "NO", "NO", "NO", "YES",
"YES", "YES", "YES", "YES", "YES"
};
for (int i = 0; i < x.length; i++) {
dataset.add(
new ArrayExample<>(
new Label(labels[i]),
featureNames,
x[i]
)
);
}
Here, the featureNames array identifies the meaning of each numerical value. This is different from the Smile example, where the feature names were implicit in the positions of the array elements. The ArrayExample constructor receives the output label, feature names, and feature values. Each example is then added to the dataset using dataset.add().
This gives Tribuo the information it needs to build its feature and output representations before training begins.
5.4 Training the Logistic Regression Model
Tribuo provides a LogisticRegressionTrainer class for training logistic regression classifiers. We can now train the model:
LogisticRegressionTrainer trainer = new LogisticRegressionTrainer(); Model<Label> model = trainer.train(dataset);
The trainer receives the dataset and produces a trained model. The Model abstraction represents the resulting prediction model. It can be used to make predictions on new examples without repeating the training process. One difference worth noting is that Tribuo separates the algorithm configuration from the model itself. The trainer is responsible for learning the model, while the resulting Model instance is responsible for prediction.
5.5 Performing Inference
To perform inference, we create a new example containing the features of a customer whose purchasing behaviour we want to predict. Since this customer does not have a known label, we use the unknown output provided by the LabelFactory.
ArrayExample<Label> newCustomer =
new ArrayExample<>(
factory.getUnknownOutput(),
featureNames,
new double[]{32.0, 42.0}
);
Prediction<Label> prediction = model.predict(newCustomer);
IO.println("Predicted class: " + prediction.getOutput());
The model.predict() method returns a Prediction object rather than returning the predicted label directly. The Prediction object contains the predicted output and can also contain scores or probabilities for the available classes, depending on the model. We can retrieve the predicted classification using getOutput().
5.6 Complete Tribuo Example
The complete implementation brings the dataset creation, training, and inference operations together:
public class TribuoClassificationExample {
public static void main(String[] args) {
// Create output factory
LabelFactory factory = new LabelFactory();
// Create dataset
MutableDataset<Label> dataset = new MutableDataset<>(
new SimpleDataSourceProvenance(
"Customer purchasing training data",
factory
),
factory
);
// Feature names
String[] featureNames = {"age", "income"};
// Training features
double[][] x = {
{20.0, 30.0},
{22.0, 32.0},
{25.0, 35.0},
{28.0, 38.0},
{35.0, 45.0},
{38.0, 48.0},
{40.0, 50.0},
{45.0, 55.0},
{48.0, 58.0},
{50.0, 60.0}
};
// Expected labels
String[] labels = {
"NO", "NO", "NO", "NO", "YES",
"YES", "YES", "YES", "YES", "YES"
};
// Add examples to the dataset
for (int i = 0; i < x.length; i++) {
dataset.add(
new ArrayExample<>(
new Label(labels[i]),
featureNames,
x[i]
)
);
}
IO.println("Training examples: " + dataset.size());
// Train logistic regression model
LogisticRegressionTrainer trainer = new LogisticRegressionTrainer();
Model<Label> model = trainer.train(dataset);
IO.println("Model training completed.");
// Create a new customer example
ArrayExample<Label> newCustomer = new ArrayExample<>(
factory.getUnknownOutput(),
featureNames,
new double[]{32.0, 42.0}
);
// Perform inference
Prediction<Label> prediction = model.predict(newCustomer);
IO.println("Predicted class: " + prediction.getOutput());
}
}
6. Training in Java vs. Training Outside Java
Although the examples demonstrate how to train models directly in Java, this is not the only way to incorporate machine learning into a Java application. In some organisations, model development and application development are separate activities. Data scientists may use Python frameworks to experiment with algorithms, prepare datasets, train models, and evaluate their performance. Once a suitable model has been produced, it can be exported and made available to Java applications.
There are two common approaches.
6.1 Training and Inference in the Same Java Application
In this approach, the Java application is responsible for preparing the data, training the model, and performing predictions. Libraries such as Smile and Tribuo make this possible without requiring a separate machine learning service.
This approach can work well when:
- The dataset is relatively small or manageable.
- The application uses traditional machine learning algorithms.
- The development team wants to maintain the entire workflow in Java.
- Training can be performed periodically within the application or a dedicated Java process.
However, training does not necessarily need to happen whenever the application starts. A better approach is often to train the model as a separate scheduled operation and make the resulting model available to the application.
6.2 Training Outside Java and Performing Inference in Java
Another approach is to train the model using a different ecosystem and deploy it to a Java application for inference. For example, a data science team might use Python and scikit-learn to train a classification model. After evaluating the model, the team exports it into ONNX format.
The Java application can then load the exported model using ONNX Runtime and perform predictions. This separation provides several advantages:
- Data scientists can use the tools and frameworks they already understand.
- Java applications do not need to include the original training framework.
- Training and application deployment can be managed independently.
- Models can be updated without necessarily changing the Java application itself.
DJL provides another option when working with deep learning models and supported engines.
The choice between these approaches depends on the development team’s requirements, the algorithms involved, and the intended deployment environment.
7. Saving and Reusing Trained Models
An important consideration when building machine learning applications is what happens after training. In the examples, the trained model exists only in memory. If the application terminates, the model is lost, and the training process must be repeated when the application starts again.
This is acceptable for a demonstration, but it is not a good approach for most production applications. A better approach is to train the model once, evaluate it, save it, and load it whenever predictions are required.
The exact process depends on the library. Tribuo provides model serialization facilities, including methods for saving and loading models. Smile also provides serialization support for its models, although the supported persistence mechanisms should be checked for the specific model type. ONNX Runtime takes a different approach. It loads a model that has already been exported into ONNX format.
A typical model lifecycle involves the following activities:
- Prepare the training dataset.
- Train the selected machine learning algorithm.
- Evaluate the resulting model using separate test data.
- Save the model to a file or model repository.
- Load the model in the application that performs inference.
- Monitor prediction quality and retrain when necessary.
Keeping training separate from inference makes it easier to manage model versions and deploy updates without unnecessarily interrupting the application. It is also worth storing information about the training dataset, algorithm configuration, feature definitions, and model version. This information becomes important when investigating unexpected predictions or reproducing a previous training run.
8. Conclusion
Java provides several libraries for incorporating machine learning into applications, ranging from traditional classification and regression algorithms to deep learning and distributed model training. The main design consideration is whether the application needs to learn from data or simply execute an existing model. Smile and Tribuo provide convenient ways to train traditional models in Java, while DJL and ONNX Runtime make it possible to work with models from deep learning and external machine learning ecosystems. Weka and Spark MLlib address more specialised requirements involving experimentation and distributed data processing.
A key takeaway is to choose a library based on the machine learning task rather than assuming that training and inference require the same tools. A Java application can perform both operations, or it can consume a model trained and maintained by an entirely separate workflow.
9. Download the Source Code
You can download the full source code of this example here: java machine learning libraries




