A lightweight, educational scikit-learn-like machine learning library
Project description
simpleml
A lightweight, educational implementation of a scikit-learn-like machine learning library in pure Python and NumPy.
Features
- Classification Models: Logistic Regression, Decision Trees, Random Forests, Naive Bayes, Support Vector Classifiers
- Regression Models: Linear Regression, Decision Tree Regression, Random Forest Regression, Support Vector Regression
- Clustering Algorithms: K-Means, DBSCAN
- Preprocessing: StandardScaler, MinMaxScaler, OneHotEncoder
- Model Selection: K-Fold Cross-Validation, Grid Search, Cross-Validation
- Metrics: Accuracy, Precision, Recall, F1-Score, Confusion Matrix, MSE, MAE, R² Score
- Consistent API: Inspired by scikit-learn's fit-predict interface
Installation
git clone https://github.com/sergeauronss01/simpleml.git
cd simpleml
pip install -r requirements.txt
Quick Start
Basic Classification
from simpleml.linear_model import LogisticRegression
from simpleml.preprocessing import StandardScaler
from simpleml.model_selection import train_test_split
from simpleml.metrics import accuracy_score
import numpy as np
# Generate sample data
X = np.random.randn(100, 5)
y = np.random.randint(0, 2, 100)
# Split data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Preprocess
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# Train model
clf = LogisticRegression(n_iterations=1000)
clf.fit(X_train, y_train)
# Evaluate
y_pred = clf.predict(X_test)
print(f"Accuracy: {accuracy_score(y_test, y_pred)}")
Decision Tree Classifier
from simpleml.tree import DecisionTreeClassifier
X = np.array([[0, 0], [1, 1], [0, 1], [1, 0]])
y = np.array([0, 1, 1, 0])
clf = DecisionTreeClassifier(max_depth=3)
clf.fit(X, y)
predictions = clf.predict(X)
Random Forest
from simpleml.ensemble import RandomForestClassifier
clf = RandomForestClassifier(n_estimators=10, random_state=42)
clf.fit(X_train, y_train)
predictions = clf.predict(X_test)
K-Means Clustering
from simpleml.cluster import KMeans
kmeans = KMeans(n_clusters=3, random_state=42)
kmeans.fit(X)
labels = kmeans.predict(X_new)
Cross-Validation
from simpleml.model_selection import cross_validate
scores = cross_validate(clf, X, y, cv=5)
print(f"Mean test score: {scores['mean_test_score']}")
Grid Search
from simpleml.model_selection import GridSearchCV
param_grid = {
'learning_rate': [0.01, 0.1],
'n_iterations': [100, 500],
}
gs = GridSearchCV(clf, param_grid, cv=5)
gs.fit(X_train, y_train)
print(f"Best parameters: {gs.best_params_}")
Module Structure
simpleml/
├── __init__.py # Package initialization
├── base.py # Base classes (BaseEstimator, ClassifierMixin, etc.)
├── linear_model.py # Linear regression and classification
├── tree.py # Decision tree models
├── ensemble.py # Ensemble methods
├── cluster.py # Clustering algorithms
├── naive_bayes.py # Naive Bayes classifiers
├── svm.py # Support Vector Machines
├── preprocessing.py # Data preprocessing
├── model_selection.py # Model selection and evaluation
├── metrics.py # Evaluation metrics
└── utils.py # Utility functions
Available Models
Supervised Learning
Classification
LogisticRegression: Binary logistic regression with gradient descentDecisionTreeClassifier: Decision tree with Gini/Entropy splitsRandomForestClassifier: Ensemble of decision treesGaussianNaiveBayes: Gaussian Naive Bayes classifierMultinomialNaiveBayes: Multinomial Naive Bayes for discrete featuresLinearSVC: Linear Support Vector Classifier
Regression
LinearRegression: Ordinary least squares regressionDecisionTreeRegressor: Decision tree regressionRandomForestRegressor: Ensemble regressionSVR: Support Vector Regression
Unsupervised Learning
Clustering
KMeans: K-Means clustering algorithmDBSCAN: Density-based clustering
Preprocessing
StandardScaler: Standardization (zero mean, unit variance)MinMaxScaler: Min-Max scaling to a fixed rangeOneHotEncoder: One-hot encoding for categorical features
Model Selection
KFold: K-Fold cross-validatorcross_validate(): Cross-validation scoringGridSearchCV: Exhaustive grid search
Metrics
All metrics are available in simpleml.metrics:
accuracy_score: Classification accuracyprecision_score: Precision for binary classificationrecall_score: Recall for binary classificationf1_score: F1-Score for binary classificationconfusion_matrix: Confusion matrixmean_squared_error: Mean squared errormean_absolute_error: Mean absolute errorr2_score: R² coefficient of determination
Testing
Run the test suite:
pytest tests/ -v
Run tests with coverage:
pytest tests/ --cov=simpleml
Documentation
Each module is thoroughly documented with docstrings following NumPy style. Use help() in Python:
from simpleml.linear_model import LogisticRegression
help(LogisticRegression)
Design Philosophy
This library is designed to:
- Educate: Clear, understandable implementations without external ML dependencies
- Mirror scikit-learn: Familiar API for users of scikit-learn
- Be extensible: Easy to add new models and algorithms
- Be tested: Comprehensive test coverage
Limitations
- No support for neural networks or deep learning
- No GPU acceleration
- Limited to basic algorithms (no advanced techniques like stacking, boosting beyond basic implementation)
- Not optimized for large-scale datasets
Performance
This library is for educational purposes. For production use and performance-critical applications, use scikit-learn or similar production libraries.
Contributing
To contribute:
- Fork the repository
- Create a feature branch
- Write tests for new functionality
- Ensure all tests pass
- Submit a pull request
License
MIT License
Author
Serge Auronss Gbaguidi
References
- Scikit-learn documentation: https://scikit-learn.org
- NumPy documentation: https://numpy.org
- Machine Learning fundamentals
Note: This is an educational project created to understand machine learning algorithms and best practices for library design. For production machine learning work, please use scikit-learn.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file simpleml_auronss-0.1.0.tar.gz.
File metadata
- Download URL: simpleml_auronss-0.1.0.tar.gz
- Upload date:
- Size: 22.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f81023d56fd06fd3a2234d19ce44fc2128d8fcedc91da34c950eefe0699445db
|
|
| MD5 |
59f5305c9185689de3e8d023074f5029
|
|
| BLAKE2b-256 |
a24857097fceede8565e352618cf6ecacb2f612985701a724d2d578f0cc0d09b
|
File details
Details for the file simpleml_auronss-0.1.0-py3-none-any.whl.
File metadata
- Download URL: simpleml_auronss-0.1.0-py3-none-any.whl
- Upload date:
- Size: 27.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d47fd3e9bf31d7825d28cc9abc918ad3c66a34cb9975b6d05045db2587993fdd
|
|
| MD5 |
596557e743b28ec984c2575991dd6ad1
|
|
| BLAKE2b-256 |
e1de1db5c7a63b3eb2e6a691c3ceec06447dc40cbcec7286ba728bffe6c57d91
|