Machine Learning in Kotlin: Modern Libraries and Tools
Kotlin is a statically typed programming language that runs on top of the JVM and is fully compatible with Java. Thanks to its concise syntax, null safety, and powerful ecosystem, Kotlin is increasingly used in Data Science and machine learning. In this article, we will review key libraries that allow solving ML tasks directly in Kotlin, without switching to Python.
1. KotlinDL — Deep Learning Library from JetBrains
KotlinDL is the official library from the creators of Kotlin (JetBrains), designed for building and training neural networks. It supports both a high-level API (Keras-like) and low-level tensor operations.
Key Features:
- Model building: Sequential, Functional API
- Layers: Dense, Conv2D, MaxPooling, Dropout, LSTM, etc.
- Optimizers: Adam, SGD, RMSprop
- Loss functions: CrossEntropy, MSE, MAE
- Loading pre-trained models (ONNX, TensorFlow SavedModel)
- Working with images, text, and tabular data
Example: Simple Neural Network for Classification
import org.jetbrains.kotlinx.dl.api.core.Sequentialimport org.jetbrains.kotlinx.dl.api.core.layer.core.Denseimport org.jetbrains.kotlinx.dl.api.core.layer.reshaping.Flattenimport org.jetbrains.kotlinx.dl.api.core.optimizer.Adamimport org.jetbrains.kotlinx.dl.dataset.mnist
fun main() { val model = Sequential.of( Flatten(inputShape = longArrayOf(28, 28)), Dense(128, activation = "relu"), Dense(10, activation = "softmax") )
model.use { it.compile(optimizer = Adam(), loss = "categoricalCrossEntropy") val (train, test) = mnist() it.fit(train, epochs = 5, batchSize = 32) val accuracy = it.evaluate(test) println("Accuracy: $accuracy") }}2. Smile — Universal Library for Statistics and ML
Smile (Statistical Machine Intelligence & Learning Engine) is a powerful Java/Kotlin library covering virtually all classical machine learning algorithms. It includes implementations of over 200 algorithms.
Key Modules:
- Classification: SVM, Random Forest, Decision Trees, Naive Bayes
- Regression: Linear, Ridge, LASSO, Gaussian Process
- Clustering: K-Means, DBSCAN, Hierarchical, GMM
- Dimensionality Reduction: PCA, t-SNE, MDS
- Natural Language Processing (NLP): tokenization, stemming, N-grams
- Visualization: charts, scatter plots, heatmaps
Example: Linear Regression with Smile
import smile.regression.OLSimport smile.data.DataFrameimport smile.data.type.DataTypesimport smile.data.vector.DoubleVector
fun main() { // Create a DataFrame with data val x = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0) val y = doubleArrayOf(2.1, 4.2, 6.0, 7.9, 10.1) val df = DataFrame.of(DoubleVector.of("x", x), DoubleVector.of("y", y))
// Train an OLS model (Ordinary Least Squares) val model = OLS.fit(df, "y", "x") println("Coefficients: ${model.coefficients()}") println("Prediction for x=6: ${model.predict(doubleArrayOf(6.0))}")}3. Koma — Matrix Computations and Scientific Calculations
Koma is a library for working with multidimensional arrays and matrices, inspired by NumPy from Python. It is ideal for numerical calculations, statistics, and data preprocessing before ML.
Features:
- Matrix creation: zeros, ones, eye, rand
- Operations: addition, multiplication, transposition, matrix inverse
- Linear algebra: SV
Also in library
Event Bus and Observer Pattern in JavaScript (Node.js) — Creating Flexible Event Systems
Machine Learning in TypeScript: Overview of ML Libraries in 2024
Sending Email in Java: A Complete Guide to JavaMail and Jakarta Mail
HTTP client for Rust: top libraries and tools
ORM for Rust: Comparison and Usage Examples of Diesel, SeaORM, and SQLx