iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🦀

Getting Started with smartcore: A Machine Learning Library for Rust

に公開

Introduction

I write Rust once in a while. I'm interested in machine learning, and I'll try anything that catches my interest.

What is smartcore?

https://twitter.com/vaaaaanquish/status/1411682015569539074

When I asked someone knowledgeable about machine learning in Rust about the current "de-facto" libraries, they kindly pointed me to either linfa or smartcore. I tried linfa first, but it didn't go well. I personally prefer using the gnu(mingw) toolchain for Rust, but linfa requires linking to Intel MKL, and Intel MKL only provides libraries in MSVC format. I tried generating .a files from the DLLs and linking them, but in the end, I couldn't get it to link properly and gave up. I assume it works without any issues with the MSVC toolchain or on other operating systems like Linux.

Having no other choice, I decided to try the remaining option, smartcore.

https://smartcorelib.org/

smartcore is a machine learning library written in Pure Rust. There are no linking failures. After trying it out for a bit, I noticed it has a strong scikit-learn (sklearn) flavor; if you've used sklearn before, you'll find that "that thing from sklearn" is mostly available in smartcore as well.

Sample

It comes with datasets ready to use, so you can start right away. I've written a sample code to try it out.

use smartcore::dataset::iris;
use smartcore::linalg::naive::dense_matrix::DenseMatrix;
use smartcore::linear::logistic_regression::LogisticRegression;
use smartcore::model_selection::train_test_split;
use smartcore::metrics::mean_absolute_error;

fn main() {
    let iris_data = iris::load_dataset();
    let x = DenseMatrix::from_array(
        iris_data.num_samples,
        iris_data.num_features,
        &iris_data.data,
    );
    let y = iris_data.target;

    let (x_train, x_test, y_train, y_test) = train_test_split(&x, &y, 0.2, true);

    let reg = LogisticRegression::fit(
        &x_train,
        &y_train,
        Default::default(),
    ).unwrap();

    let result = reg.predict(&x_test).unwrap();
    assert!(mean_absolute_error(&y_test, &result) < 0.2);
}

I hadn't touched Rust in a while, so it took some time to get back into the swing of things, but I managed to get it working for now.

Conclusion

I tried out smartcore, a machine learning library written in Pure Rust. It provides a full range of features including not only linear regression like LogisticRegression, but also similarity search such as KNN and K-Means, support vector machines, and more. One thing is that GPU acceleration is not implemented, but I thought it was convenient enough for small-scale machine learning. I've shared the code so you can easily try it out.

https://github.com/mattn/smartcore-example/

Discussion