Machine Learning in Rust: Modern Libraries and Tools
The Rust language, known for its performance and memory safety, is actively entering the field of machine learning (ML). Although the ML ecosystem in Rust is younger than in Python, it already offers mature solutions for building, training, and deploying models. In this article, we will review the key libraries that allow you to solve machine learning tasks in Rust and provide practical examples.
Why Rust for Machine Learning?
Rust provides unique advantages:
- Performance: Compiled Rust code is comparable in speed to C/C++, which is critical for training large models.
- Safety: The ownership and borrowing system eliminates entire classes of errors (data races, null pointers).
- Cross-platform: Easily compiles to WebAssembly, mobile devices, and embedded systems.
- Integration with Python: You can write high-performance modules in Rust and call them from Python via PyO3.
Key Libraries for ML in Rust
1. Linfa — Swiss Army Knife of ML
Linfa is the scikit-learn equivalent for Rust. It provides a unified interface for standard algorithms. It supports:
- Linear and logistic regression
- Support Vector Machines (SVM)
- Clustering (K-Means, DBSCAN)
- Dimensionality reduction methods (PCA)
- Decision trees and random forest
Example of linear regression with Linfa:
use linfa::prelude::*;use linfa_linear::LinearRegression;use ndarray::Array2;
fn main() -> Result<(), Box<dyn std::error::Error>> { // Create synthetic data: 100 points, 3 features let x = Array2::random((100, 3), rand::distributions::Uniform::new(-1.0, 1.0)); let true_weights = arr2(&[[2.0], [-1.0], [0.5]]); let y = x.dot(&true_weights) + 0.1; // add noise
let dataset = Dataset::new(x, y); // Train the model let model = LinearRegression::default().fit(&dataset)?; // Model coefficients println!("Weights: {:?}", model.params()); // Prediction let predicted = model.predict(&dataset); println!("MSE: {:?}", predicted.mean_squared_error(&dataset)?); Ok(())}2. Burn — Modern Deep Learning Framework
Burn is a flexible neural network framework written entirely in Rust. Its features:
- GPU support (CUDA, Vulkan, Metal, WebGPU)
- Automatic differentiation (autograd)
- Flexible backend system (torch, ndarray, wgpu)
- Dynamic computation graphs
- Export to ONNX
Example of a simple neural network in Burn:
use burn::tensor::{Tensor, backend::Backend};use burn::nn::{Linear, Relu, Sequential};
// Define the network architecturestruct MyModel<B: Backend> { linear1: Linear<B>, linear2: Linear<B>, activation: Relu,}
impl<B: Backend> MyModel<B> { fn new(device: &B::Device) -> Self { Self { linear1: Linear::new(784, 256, device), linear2: Linear::new(256, 10, device), activation: Relu::new(), } } fn forward(&self, input: Tensor<B, 2>) -> Tensor<B, 2> { let x = self.linear1.forward(input); let x = self.activation.forward(x); self.linear2.forward(x) }}
fn main() { // Use CPU backend (ndarray) type MyBackend = burn::backend::NdArray; let device = Default::default(); let model = MyModel::<MyBackend>::new(&device); let input = Tensor::<MyBackend, 2>::ra Also in library
ASP.NET Core for C# (.NET): Complete Guide with Examples
Sending SMS in TypeScript: API Libraries and Integration
JWT tokens in C# (.NET): working with System.IdentityModel.Tokens.Jwt
Jetpack Compose for Kotlin: Complete Guide with Examples