Sklears Python Bindings
Python bindings for the sklears machine learning library, providing a high-performance, scikit-learn compatible interface through PyO3.
Latest release:
0.2.0(July 14, 2026). See the workspace release notes for highlights and upgrade guidance.
Features
- Drop-in replacement for scikit-learn's most common algorithms
- Pure Rust implementation with ongoing performance optimization
- Full NumPy array compatibility with zero-copy operations where possible
- Comprehensive error handling with Python exceptions
- Memory-safe operations with automatic reference counting
- Scikit-learn compatible API for easy migration
Status
- Partial: covers linear models, ensembles, MLP, naive Bayes, clustering (KMeans/DBSCAN), core preprocessing,
train_test_split/KFold, and the common classification/regression metrics — all genuinely wired to their underlyingsklears-*implementations (no stub bindings). - Covered by 55 passing crate tests for
0.2.0. - Tree-based models (
RandomForestClassifier,DecisionTreeClassifier) are implemented insrc/tree.rsbut still commented out of the Python module registration;StratifiedKFoldandcross_val_scoreare not implemented yet. SeeTODO.mdfor details.
Supported Algorithms
Linear Models
LinearRegression- Ordinary least squares linear regressionRidge- Ridge regression with L2 regularizationLasso- Lasso regression with L1 regularizationElasticNet- Elastic-net regularizationBayesianRidge- Bayesian ridge regressionARDRegression- Automatic Relevance Determination regressionLogisticRegression- Logistic regression for classification
Ensemble Methods
GradientBoostingClassifier- Gradient boosting for classificationGradientBoostingRegressor- Gradient boosting for regressionAdaBoostClassifier- Adaptive boosting classifierVotingClassifier- Voting ensemble classifierBaggingClassifier- Bagging ensemble classifier
Neural Networks
MLPClassifier- Multi-layer perceptron classifierMLPRegressor- Multi-layer perceptron regressor
Naive Bayes
GaussianNB- Gaussian Naive BayesMultinomialNB- Multinomial Naive BayesBernoulliNB- Bernoulli Naive BayesComplementNB- Complement Naive Bayes
Clustering
KMeans- K-Means clustering algorithm (K-means++ init; exposesfit/predict/fit_predictpluslabels_,cluster_centers_,inertia_,n_iter_)DBSCAN- Density-based spatial clustering (transductive like scikit-learn's implementation: exposesfit_predict()+labels_, nopredict()on new data since the underlying algorithm has none)
Preprocessing
StandardScaler- Standardize features by removing mean and scaling to unit varianceMinMaxScaler- Scale features to a given rangeLabelEncoder- Encode target labels with value between 0 and n_classes-1 (accepts a list of strings, e.g.le.fit(["a", "b", "c"]))
Tree Models (coming soon)
RandomForestClassifier- Random forest for classificationDecisionTreeClassifier- Decision tree for classification
Model Selection
train_test_split- Split arrays into random train and test subsets (test_size,random_state; always shuffles —train_size/stratifynot yet supported)KFold- K-Fold cross-validator (n_splits,shuffle,random_state)StratifiedKFold(coming soon) - Stratified K-Fold cross-validatorcross_val_score(coming soon) - Evaluate metric(s) by cross-validation
Metrics
accuracy_score- Classification accuracymean_squared_error- Mean squared error for regressionmean_absolute_error- Mean absolute error for regressionmean_squared_log_error- Mean squared logarithmic error for regressionmedian_absolute_error- Median absolute error for regressionr2_score- R² (coefficient of determination) scoreprecision_score- Precision for classificationrecall_score- Recall for classificationf1_score- F1 score for classificationconfusion_matrix- Confusion matrix for classificationclassification_report- Text report of classification metrics
Installation
Prerequisites
- Python 3.9 or later
- NumPy
- Rust 1.70 or later
- PyO3 and Maturin for building
Building from Source
-
Clone the repository:
-
Install Maturin:
-
Build and install the package:
-
Or build a wheel:
Quick Start
# Generate sample data
=
=
# Train a linear regression model
=
=
# Calculate R² score
=
Clustering, Preprocessing, and Model Selection
=
=
# train_test_split requires y as float64 (PyReadonlyArray1<f64>) -- cast
# integer label arrays with .astype(np.float64) first.
, , , =
# StandardScaler: fit/transform (or fit_transform) both genuinely compute
# per-feature mean/variance now.
=
=
=
# KMeans: fit()/predict()/fit_predict() are wired to the real
# sklears-clustering implementation (K-means++ initialization).
=
=
# DBSCAN has no predict() on new data (matches scikit-learn's transductive
# behavior) -- use fit_predict() and the labels_ attribute instead.
=
=
# KFold: n_splits/shuffle/random_state are all real now.
=
pass # train_idx / test_idx are lists of row indices
Performance Comparison
Here's a typical performance comparison with scikit-learn:
# Generate data
, =
, , , =
# Sklears
=
=
=
= -
# Scikit-learn
=
=
=
= -
API Compatibility
The sklears Python bindings are designed to be API-compatible with scikit-learn. Most existing scikit-learn code should work with minimal changes:
Before (scikit-learn):
After (sklears):
# Available classes and functions
=
, , , =
=
=
# mean_squared_error, r2_score, accuracy_score, etc. are all available too.
# Note: StratifiedKFold, cross_val_score - coming soon
Memory Management
The bindings are designed to be memory-efficient:
- Zero-copy operations where possible using NumPy's C API
- Automatic memory management through PyO3's reference counting
- Efficient data structures using ndarray and sprs for sparse matrices
- Streaming support for large datasets that don't fit in memory
Error Handling
All Rust errors are properly converted to Python exceptions:
# This will raise a ValueError if arrays have incompatible shapes
=
# Shape mismatch
System Information
Get information about your sklears installation:
# Version information (tracks the crate's Cargo.toml version automatically)
# Build information
=
# Hardware capability flags (avx2/fma/neon/...) plus the real CPU core
# count under "num_cpus" (previously miscoded as a bool).
=
# Basic timing benchmarks (matrix multiply, dot product, allocation), in ms.
=
Examples
See the examples/ directory for comprehensive usage examples:
python_demo.py- Complete demonstration of all features- Performance comparison scripts
- Real-world use cases
Contributing
Contributions are welcome! Please see the main sklears repository for contribution guidelines.
License
This project is licensed under the Apache-2.0 license.
Acknowledgments
- Built with PyO3 for Rust-Python interoperability
- Compatible with NumPy arrays
- API inspired by scikit-learn