├── .github └── dependabot.yml ├── .gitignore ├── README.md ├── Cargo.toml ├── src ├── main.rs ├── quick_start.rs ├── model_selection.rs ├── unsupervised.rs ├── utils.rs └── supervised.rs └── LICENSE /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | open-pull-requests-limit: 10 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | 12 | # IDE 13 | .idea 14 | .project 15 | .vscode 16 | *.code-workspace 17 | 18 | # OS 19 | .DS_Store 20 | 21 | # Artifacts 22 | *.model 23 | *.svg 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DEPRECATION 2 | 3 | This examples are for legacy version 0.21, please see the **notebooks in [smartcore-jupyter](https://github.com/smartcorelib/smartcore-jupyter) for current examples**. 4 | 5 | 6 | # SmartCore Examples 7 | 8 | Examples of code using machine learning models from [SmartCore](https://smartcorelib.org/) library. 9 | All examples here are used in [SmartCore's User guide](https://smartcorelib.org/user_guide/) and grouped into same categories as pages from the manual. 10 | 11 | ## How to run examples? 12 | 13 | To list available examples: 14 | 15 | ``` 16 | cargo run list 17 | ``` 18 | 19 | To run an example: 20 | 21 | ``` 22 | cargo run quick-start:iris-knn 23 | ``` 24 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "smartcore-examples" 3 | description = "Examples of code using machine learning models from SmartCore library" 4 | homepage = "https://smartcorelib.org" 5 | version = "0.2.0" 6 | authors = ["SmartCore Dvelopers"] 7 | edition = "2018" 8 | license = "Apache-2.0" 9 | documentation = "https://docs.rs/smartcore" 10 | repository = "https://github.com/smartcorelib/smartcore-examples" 11 | readme = "README.md" 12 | keywords = ["machine-learning", "statistical", "ai", "optimization", "linear-algebra"] 13 | categories = ["science"] 14 | 15 | [dependencies] 16 | smartcore = { path = "../smartcore", default-features = false, features=["serde", "nalgebra-bindings", "ndarray-bindings", "datasets"]} 17 | structopt = "0.3.17" 18 | ndarray = "0.14" 19 | nalgebra = "0.31" 20 | plotters = "^0.3.0" 21 | serde = "1.0.115" 22 | bincode = "1.3.1" 23 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | pub mod model_selection; 2 | pub mod quick_start; 3 | pub mod supervised; 4 | pub mod unsupervised; 5 | pub mod utils; 6 | 7 | use std::collections::HashMap; 8 | use structopt::StructOpt; 9 | 10 | #[derive(StructOpt)] 11 | /// Run SmartCore example 12 | struct Cli { 13 | /// The example to run. Pass `list_examples` to list all available examples! 14 | example_name: String, 15 | } 16 | 17 | fn main() { 18 | let args = Cli::from_args(); 19 | 20 | let examples = args.example_name; 21 | 22 | let all_examples: HashMap<&str, &dyn Fn()> = vec![ 23 | ( 24 | "quick-start:iris-knn", 25 | &quick_start::iris_knn_example as &dyn Fn(), 26 | ), 27 | ( 28 | "quick-start:iris-lr", 29 | &quick_start::iris_lr_example as &dyn Fn(), 30 | ), 31 | ( 32 | "quick-start:iris-lr-ndarray", 33 | &quick_start::iris_lr_ndarray_example as &dyn Fn(), 34 | ), 35 | ( 36 | "quick-start:iris-lr-nalgebra", 37 | &quick_start::iris_lr_nalgebra_example as &dyn Fn(), 38 | ), 39 | ( 40 | "quick-start:iris-gaussiannb", 41 | &quick_start::iris_gaussiannb_example as &dyn Fn(), 42 | ), 43 | ( 44 | "supervised:breast-cancer", 45 | &supervised::breast_cancer as &dyn Fn(), 46 | ), 47 | ("supervised:diabetes", &supervised::diabetes as &dyn Fn()), 48 | ("supervised:boston", &supervised::boston as &dyn Fn()), 49 | ( 50 | "unsupervised:digits_clusters", 51 | &unsupervised::digits_clusters as &dyn Fn(), 52 | ), 53 | ( 54 | "unsupervised:digits_pca", 55 | &unsupervised::digits_pca as &dyn Fn(), 56 | ), 57 | ("unsupervised:circles", &unsupervised::circles as &dyn Fn()), 58 | ( 59 | "unsupervised:digits_svd1", 60 | &unsupervised::digits_svd1 as &dyn Fn(), 61 | ), 62 | ( 63 | "unsupervised:digits_svd2", 64 | &unsupervised::digits_svd2 as &dyn Fn(), 65 | ), 66 | ( 67 | "model_selection:save_restore_knn", 68 | &model_selection::save_restore_knn as &dyn Fn(), 69 | ), 70 | ( 71 | "model_selection:plot_cross_val_predict", 72 | &model_selection::plot_cross_val_predict as &dyn Fn(), 73 | ), 74 | ( 75 | "model_selection:lr_cross_validate", 76 | &model_selection::lr_cross_validate as &dyn Fn(), 77 | ), 78 | ("supervised:svm", &supervised::svm as &dyn Fn()), 79 | ] 80 | .into_iter() 81 | .collect(); 82 | 83 | match examples { 84 | example if all_examples.contains_key(&example.as_str()) => { 85 | println!("Running {} ...\n", example); 86 | for example_fn in all_examples.get(example.as_str()) { 87 | example_fn(); 88 | } 89 | println!("\nDone!"); 90 | } 91 | example if example == "list_examples" || example == "list" => { 92 | println!("You can run following examples:"); 93 | let mut keys: Vec<&&str> = all_examples.keys().collect(); 94 | keys.sort(); 95 | for c in keys { 96 | println!("\t{}", c); 97 | } 98 | } 99 | example => eprintln!( 100 | "Can't find this example: [{}]. Type `list` to list all available examples", 101 | example 102 | ), 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/quick_start.rs: -------------------------------------------------------------------------------- 1 | use smartcore::dataset::iris::load_dataset; 2 | // DenseMatrix wrapper around Vec 3 | use smartcore::linalg::naive::dense_matrix::DenseMatrix; 4 | // ndarray structs 5 | use ndarray::Array; 6 | // nalgebra structs 7 | use nalgebra::{DMatrix, RowDVector}; 8 | // Imports for KNN classifier 9 | use smartcore::neighbors::knn_classifier::*; 10 | // Imports for Logistic Regression 11 | use smartcore::linear::logistic_regression::LogisticRegression; 12 | // Imports Gaussian Naive Bayes classifier 13 | use smartcore::naive_bayes::gaussian::GaussianNB; 14 | // Model performance 15 | use smartcore::metrics::accuracy; 16 | 17 | pub fn iris_knn_example() { 18 | // Load Iris dataset 19 | let iris_data = load_dataset(); 20 | // Turn Iris dataset into NxM matrix 21 | let x = DenseMatrix::from_array( 22 | iris_data.num_samples, 23 | iris_data.num_features, 24 | &iris_data.data, 25 | ); 26 | // These are our target class labels 27 | let y = iris_data.target; 28 | 29 | // Fit KNN classifier to Iris dataset 30 | let knn = KNNClassifier::fit(&x, &y, Default::default()).unwrap(); 31 | 32 | let y_hat = knn.predict(&x).unwrap(); // Predict class labels 33 | 34 | // Calculate training error 35 | println!("accuracy: {}", accuracy(&y, &y_hat)); // Prints 0.96 36 | } 37 | 38 | pub fn iris_lr_example() { 39 | // Load Iris dataset 40 | let iris_data = load_dataset(); 41 | // Turn Iris dataset into NxM matrix 42 | let x = DenseMatrix::from_array( 43 | iris_data.num_samples, 44 | iris_data.num_features, 45 | &iris_data.data, 46 | ); 47 | // These are our target class labels 48 | let y = iris_data.target; 49 | 50 | // Fit Logistic Regression to Iris dataset 51 | let lr = LogisticRegression::fit(&x, &y, Default::default()).unwrap(); 52 | let y_hat = lr.predict(&x).unwrap(); // Predict class labels 53 | 54 | // Calculate training error 55 | println!("accuracy: {}", accuracy(&y, &y_hat)); // Prints 0.98 56 | } 57 | 58 | pub fn iris_lr_ndarray_example() { 59 | // Load Iris dataset 60 | let iris_data = load_dataset(); 61 | // Turn Iris dataset into NxM matrix 62 | let x = Array::from_shape_vec( 63 | (iris_data.num_samples, iris_data.num_features), 64 | iris_data.data, 65 | ) 66 | .unwrap(); 67 | 68 | // These are our target class labels 69 | let y = Array::from_shape_vec(iris_data.num_samples, iris_data.target).unwrap(); 70 | 71 | // Fit Logistic Regression to Iris dataset 72 | let lr = LogisticRegression::fit(&x, &y, Default::default()).unwrap(); 73 | let y_hat = lr.predict(&x).unwrap(); // Predict class labels 74 | 75 | // Calculate training error 76 | println!("accuracy: {}", accuracy(&y, &y_hat)); // Prints 0.98 77 | } 78 | 79 | pub fn iris_lr_nalgebra_example() { 80 | // Load Iris dataset 81 | let iris_data = load_dataset(); 82 | // Turn Iris dataset into NxM matrix 83 | let x = DMatrix::from_row_slice( 84 | iris_data.num_samples, 85 | iris_data.num_features, 86 | &iris_data.data, 87 | ); 88 | 89 | // These are our target class labels 90 | let y = RowDVector::from_iterator(iris_data.num_samples, iris_data.target.into_iter()); 91 | 92 | // Fit Logistic Regression to Iris dataset 93 | let lr = LogisticRegression::fit(&x, &y, Default::default()).unwrap(); 94 | let y_hat = lr.predict(&x).unwrap(); // Predict class labels 95 | 96 | // Calculate training error 97 | println!("accuracy: {}", accuracy(&y, &y_hat)); // Prints 0.98 98 | } 99 | 100 | pub fn iris_gaussiannb_example() { 101 | // Load Iris dataset 102 | let iris_data = load_dataset(); 103 | 104 | // Turn Iris dataset into NxM matrix 105 | let x = DenseMatrix::from_array( 106 | iris_data.num_samples, 107 | iris_data.num_features, 108 | &iris_data.data, 109 | ); 110 | 111 | // These are our target class labels 112 | let y = iris_data.target; 113 | 114 | // Fit Logistic Regression to Iris dataset 115 | let gnb = GaussianNB::fit(&x, &y, Default::default()).unwrap(); 116 | let y_hat = gnb.predict(&x).unwrap(); // Predict class labels 117 | 118 | // Calculate training error 119 | println!("accuracy: {}", accuracy(&y, &y_hat)); // Prints 0.96 120 | } 121 | -------------------------------------------------------------------------------- /src/model_selection.rs: -------------------------------------------------------------------------------- 1 | use smartcore::dataset::breast_cancer; 2 | use smartcore::dataset::diabetes; 3 | use smartcore::dataset::iris; 4 | use std::fs::File; 5 | use std::io::prelude::*; 6 | // DenseMatrix wrapper around Vec 7 | use smartcore::linalg::naive::dense_matrix::DenseMatrix; 8 | // Imports for KNN classifier 9 | use smartcore::math::distance::*; 10 | use smartcore::neighbors::knn_classifier::*; 11 | // Linear regression 12 | use smartcore::linear::linear_regression::LinearRegression; 13 | // Logistic regression 14 | use smartcore::linear::logistic_regression::LogisticRegression; 15 | // Model performance 16 | use smartcore::metrics::accuracy; 17 | // K-fold CV 18 | use smartcore::model_selection::{cross_val_predict, cross_validate, KFold}; 19 | 20 | use crate::utils; 21 | 22 | pub fn save_restore_knn() { 23 | // Load Iris dataset 24 | let iris_data = iris::load_dataset(); 25 | // Turn Iris dataset into NxM matrix 26 | let x = DenseMatrix::from_array( 27 | iris_data.num_samples, 28 | iris_data.num_features, 29 | &iris_data.data, 30 | ); 31 | // These are our target class labels 32 | let y = iris_data.target; 33 | 34 | // Fit KNN classifier to Iris dataset 35 | let knn = KNNClassifier::fit(&x, &y, Default::default()).unwrap(); 36 | // File name for the model 37 | let file_name = "iris_knn.model"; 38 | // Save the model 39 | { 40 | let knn_bytes = bincode::serialize(&knn).expect("Can not serialize the model"); 41 | File::create(file_name) 42 | .and_then(|mut f| f.write_all(&knn_bytes)) 43 | .expect("Can not persist model"); 44 | } 45 | // Load the model 46 | let knn: KNNClassifier = { 47 | let mut buf: Vec = Vec::new(); 48 | File::open(&file_name) 49 | .and_then(|mut f| f.read_to_end(&mut buf)) 50 | .expect("Can not load model"); 51 | bincode::deserialize(&buf).expect("Can not deserialize the model") 52 | }; 53 | //Predict class labels 54 | let y_hat = knn.predict(&x).unwrap(); // Predict class labels 55 | // Calculate training error 56 | println!("accuracy: {}", accuracy(&y, &y_hat)); // Prints 0.96 57 | } 58 | 59 | // This example is expired by 60 | // https://scikit-learn.org/stable/auto_examples/model_selection/plot_cv_predict.html 61 | pub fn lr_cross_validate() { 62 | // Load dataset 63 | let breast_cancer_data = breast_cancer::load_dataset(); 64 | let x = DenseMatrix::from_array( 65 | breast_cancer_data.num_samples, 66 | breast_cancer_data.num_features, 67 | &breast_cancer_data.data, 68 | ); 69 | // These are our target values 70 | let y = breast_cancer_data.target; 71 | // cross-validated estimator 72 | let results = cross_validate( 73 | LogisticRegression::fit, 74 | &x, 75 | &y, 76 | Default::default(), 77 | KFold::default().with_n_splits(3), 78 | accuracy, 79 | ) 80 | .unwrap(); 81 | println!( 82 | "Test score: {}, training score: {}", 83 | results.mean_test_score(), 84 | results.mean_train_score() 85 | ); 86 | } 87 | 88 | // This example is expired by 89 | // https://scikit-learn.org/stable/auto_examples/model_selection/plot_cv_predict.html 90 | pub fn plot_cross_val_predict() { 91 | // Load Diabetes dataset 92 | let diabetes_data = diabetes::load_dataset(); 93 | let x = DenseMatrix::from_array( 94 | diabetes_data.num_samples, 95 | diabetes_data.num_features, 96 | &diabetes_data.data, 97 | ); 98 | // These are our target values 99 | let y = diabetes_data.target; 100 | // Generate cross-validated estimates for each input data point 101 | let y_hat = cross_val_predict( 102 | LinearRegression::fit, 103 | &x, 104 | &y, 105 | Default::default(), 106 | KFold::default().with_n_splits(10), 107 | ) 108 | .unwrap(); 109 | // Assemble XY dataset for the scatter plot 110 | let xy = DenseMatrix::from_2d_vec( 111 | &y_hat 112 | .into_iter() 113 | .zip(y.into_iter()) 114 | .map(|(x1, x2)| vec![x1, x2]) 115 | .collect(), 116 | ); 117 | // Plot XY 118 | utils::scatterplot(&xy, None, "cross_val_predict").unwrap(); 119 | } 120 | -------------------------------------------------------------------------------- /src/unsupervised.rs: -------------------------------------------------------------------------------- 1 | use smartcore::dataset::*; 2 | // DenseMatrix wrapper around Vec 3 | use smartcore::linalg::naive::dense_matrix::DenseMatrix; 4 | // K-Means 5 | use smartcore::cluster::kmeans::{KMeans, KMeansParameters}; 6 | // DBSCAN 7 | use smartcore::cluster::dbscan::{DBSCANParameters, DBSCAN}; 8 | // PCA 9 | use smartcore::decomposition::pca::{PCAParameters, PCA}; 10 | use smartcore::metrics::*; 11 | // SVD 12 | use smartcore::decomposition::svd::{SVDParameters, SVD}; 13 | use smartcore::linalg::svd::SVDDecomposableMatrix; 14 | use smartcore::linalg::BaseMatrix; 15 | 16 | use crate::utils; 17 | 18 | pub fn digits_clusters() { 19 | // Load dataset 20 | let digits_data = digits::load_dataset(); 21 | // Transform dataset into a NxM matrix 22 | let x = DenseMatrix::from_array( 23 | digits_data.num_samples, 24 | digits_data.num_features, 25 | &digits_data.data, 26 | ); 27 | // These are our target class labels 28 | let true_labels = digits_data.target; 29 | // Fit & predict 30 | let labels = KMeans::fit(&x, KMeansParameters::default().with_k(10)) 31 | .and_then(|kmeans| kmeans.predict(&x)) 32 | .unwrap(); 33 | // Measure performance 34 | println!("Homogeneity: {}", homogeneity_score(&true_labels, &labels)); 35 | println!( 36 | "Completeness: {}", 37 | completeness_score(&true_labels, &labels) 38 | ); 39 | println!("V Measure: {}", v_measure_score(&true_labels, &labels)); 40 | } 41 | 42 | pub fn circles() { 43 | // Load dataset 44 | let circles = generator::make_circles(1000, 0.5, 0.05); 45 | // Transform dataset into a NxM matrix 46 | let x = DenseMatrix::from_array(circles.num_samples, circles.num_features, &circles.data); 47 | // These are our target class labels 48 | let true_labels = circles.target; 49 | // Fit & predict 50 | let labels = DBSCAN::fit( 51 | &x, 52 | DBSCANParameters::default() 53 | .with_eps(0.2) 54 | .with_min_samples(5), 55 | ) 56 | .and_then(|c| c.predict(&x)) 57 | .unwrap(); 58 | 59 | // Measure performance 60 | println!("Homogeneity: {}", homogeneity_score(&true_labels, &labels)); 61 | println!( 62 | "Completeness: {}", 63 | completeness_score(&true_labels, &labels) 64 | ); 65 | println!("V Measure: {}", v_measure_score(&true_labels, &labels)); 66 | utils::scatterplot( 67 | &x, 68 | Some(&labels.into_iter().map(|f| f as usize).collect()), 69 | "test", 70 | ) 71 | .unwrap(); 72 | } 73 | 74 | pub fn digits_pca() { 75 | // Load dataset 76 | let digits_data = digits::load_dataset(); 77 | // Transform dataset into a NxM matrix 78 | let x = DenseMatrix::from_array( 79 | digits_data.num_samples, 80 | digits_data.num_features, 81 | &digits_data.data, 82 | ); 83 | // These are our target class labels 84 | let labels = digits_data.target; 85 | // Fit PCA to digits dataset 86 | let pca = PCA::fit(&x, PCAParameters::default().with_n_components(2)).unwrap(); 87 | // Reduce dimensionality of X 88 | let x_transformed = pca.transform(&x).unwrap(); 89 | // Plot transformed X to 2 principal components 90 | utils::scatterplot( 91 | &x_transformed, 92 | Some(&labels.into_iter().map(|f| f as usize).collect()), 93 | "digits_pca", 94 | ) 95 | .unwrap(); 96 | } 97 | 98 | pub fn digits_svd1() { 99 | // Load dataset 100 | let digits_data = digits::load_dataset(); 101 | // Transform dataset into a NxM matrix 102 | let x = DenseMatrix::from_array( 103 | digits_data.num_samples, 104 | digits_data.num_features, 105 | &digits_data.data, 106 | ); 107 | // These are our target class labels 108 | let labels = digits_data.target; 109 | // Fit SVD to digits dataset 110 | let svd = SVD::fit(&x, SVDParameters::default().with_n_components(2)).unwrap(); 111 | // Reduce dimensionality of X 112 | let x_transformed = svd.transform(&x).unwrap(); 113 | // Plot transformed X to 2 principal components 114 | utils::scatterplot( 115 | &x_transformed, 116 | Some(&labels.into_iter().map(|f| f as usize).collect()), 117 | "digits_svd", 118 | ) 119 | .unwrap(); 120 | } 121 | 122 | pub fn digits_svd2() { 123 | // Load dataset 124 | let digits_data = digits::load_dataset(); 125 | // Transform dataset into a NxM matrix 126 | let x = DenseMatrix::from_array( 127 | digits_data.num_samples, 128 | digits_data.num_features, 129 | &digits_data.data, 130 | ); 131 | // Decompose matrix into U . Sigma . V^T 132 | let svd = x.svd().unwrap(); 133 | let u: &DenseMatrix = &svd.U; //U 134 | let v: &DenseMatrix = &svd.V; // V 135 | let s: &DenseMatrix = &svd.S(); // Sigma 136 | // Print dimensions of components 137 | println!("U is {}x{}", u.shape().0, u.shape().1); 138 | println!("V is {}x{}", v.shape().0, v.shape().1); 139 | println!("sigma is {}x{}", s.shape().0, s.shape().1); 140 | // Restore original matrix 141 | let x_hat = u.matmul(s).matmul(&v.transpose()); 142 | for (x_i, x_hat_i) in x.iter().zip(x_hat.iter()) { 143 | assert!((x_i - x_hat_i).abs() < 1e-3) 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/utils.rs: -------------------------------------------------------------------------------- 1 | // plotters 2 | use plotters::prelude::*; 3 | // DenseMatrix wrapper around Vec 4 | use smartcore::linalg::naive::dense_matrix::DenseMatrix; 5 | use smartcore::linalg::BaseMatrix; 6 | use smartcore::math::num::RealNumber; 7 | 8 | /// Get min value of `x` along axis `axis` 9 | pub fn min(x: &DenseMatrix, axis: usize) -> T { 10 | let n = x.shape().0; 11 | x.slice(0..n, axis..axis + 1) 12 | .iter() 13 | .min_by(|a, b| a.partial_cmp(b).unwrap()) 14 | .unwrap() 15 | } 16 | 17 | /// Get max value of `x` along axis `axis` 18 | pub fn max(x: &DenseMatrix, axis: usize) -> T { 19 | let n = x.shape().0; 20 | x.slice(0..n, axis..axis + 1) 21 | .iter() 22 | .max_by(|a, b| a.partial_cmp(b).unwrap()) 23 | .unwrap() 24 | } 25 | 26 | /// Draw a mesh grid defined by `mesh` with a scatterplot of `data` on top 27 | /// We use Plotters library to draw scatter plot. 28 | /// https://docs.rs/plotters/0.3.0/plotters/ 29 | pub fn scatterplot_with_mesh( 30 | mesh: &DenseMatrix, 31 | mesh_labels: &Vec, 32 | data: &DenseMatrix, 33 | labels: &Vec, 34 | title: &str, 35 | ) -> Result<(), Box> { 36 | let path = format!("{}.svg", title); 37 | let root = SVGBackend::new(&path, (800, 600)).into_drawing_area(); 38 | 39 | root.fill(&WHITE)?; 40 | let root = root.margin(15, 15, 15, 15); 41 | 42 | let x_min = (min(mesh, 0) - 1.0) as f64; 43 | let x_max = (max(mesh, 0) + 1.0) as f64; 44 | let y_min = (min(mesh, 1) - 1.0) as f64; 45 | let y_max = (max(mesh, 1) + 1.0) as f64; 46 | 47 | let mesh_labels: Vec = mesh_labels.into_iter().map(|&v| v as usize).collect(); 48 | let mesh: Vec = mesh.iter().map(|v| v as f64).collect(); 49 | 50 | let labels: Vec = labels.into_iter().map(|&v| v as usize).collect(); 51 | let data: Vec = data.iter().map(|v| v as f64).collect(); 52 | 53 | let mut scatter_ctx = ChartBuilder::on(&root) 54 | .x_label_area_size(20) 55 | .y_label_area_size(20) 56 | .build_cartesian_2d(x_min..x_max, y_min..y_max)?; 57 | scatter_ctx 58 | .configure_mesh() 59 | .disable_x_mesh() 60 | .disable_y_mesh() 61 | .draw()?; 62 | scatter_ctx.draw_series(mesh.chunks(2).zip(mesh_labels.iter()).map(|(xy, &l)| { 63 | EmptyElement::at((xy[0], xy[1])) 64 | + Circle::new((0, 0), 1, ShapeStyle::from(&Palette99::pick(l)).filled()) 65 | }))?; 66 | scatter_ctx.draw_series(data.chunks(2).zip(labels.iter()).map(|(xy, &l)| { 67 | EmptyElement::at((xy[0], xy[1])) 68 | + Circle::new( 69 | (0, 0), 70 | 3, 71 | ShapeStyle::from(&Palette99::pick(l + 3)).filled(), 72 | ) 73 | }))?; 74 | 75 | Ok(()) 76 | } 77 | 78 | /// Draw a scatterplot of `data` with labels `labels` 79 | /// We use Plotters library to draw scatter plot. 80 | /// https://docs.rs/plotters/0.3.0/plotters/ 81 | pub fn scatterplot( 82 | data: &DenseMatrix, 83 | labels: Option<&Vec>, 84 | title: &str, 85 | ) -> Result<(), Box> { 86 | let path = format!("{}.svg", title); 87 | let root = SVGBackend::new(&path, (800, 600)).into_drawing_area(); 88 | 89 | let x_min = (min(data, 0) - 1.0) as f64; 90 | let x_max = (max(data, 0) + 1.0) as f64; 91 | let y_min = (min(data, 1) - 1.0) as f64; 92 | let y_max = (max(data, 1) + 1.0) as f64; 93 | 94 | root.fill(&WHITE)?; 95 | let root = root.margin(15, 15, 15, 15); 96 | 97 | let data_values: Vec = data.iter().map(|v| v as f64).collect(); 98 | 99 | let mut scatter_ctx = ChartBuilder::on(&root) 100 | .x_label_area_size(20) 101 | .y_label_area_size(20) 102 | .build_cartesian_2d(x_min..x_max, y_min..y_max)?; 103 | scatter_ctx 104 | .configure_mesh() 105 | .disable_x_mesh() 106 | .disable_y_mesh() 107 | .draw()?; 108 | match labels { 109 | Some(labels) => { 110 | scatter_ctx.draw_series(data_values.chunks(2).zip(labels.iter()).map(|(xy, &l)| { 111 | EmptyElement::at((xy[0], xy[1])) 112 | + Circle::new((0, 0), 3, ShapeStyle::from(&Palette99::pick(l)).filled()) 113 | + Text::new(format!("{}", l), (6, 0), ("sans-serif", 15.0).into_font()) 114 | }))?; 115 | } 116 | None => { 117 | scatter_ctx.draw_series(data_values.chunks(2).map(|xy| { 118 | EmptyElement::at((xy[0], xy[1])) 119 | + Circle::new((0, 0), 3, ShapeStyle::from(&Palette99::pick(3)).filled()) 120 | }))?; 121 | } 122 | } 123 | 124 | Ok(()) 125 | } 126 | 127 | /// Generates 2x2 mesh grid from `x` 128 | pub fn make_meshgrid(x: &DenseMatrix) -> DenseMatrix { 129 | let n = x.shape().0; 130 | let x_min = min(x, 0) - 1.0; 131 | let x_max = max(x, 0) + 1.0; 132 | let y_min = min(x, 1) - 1.0; 133 | let y_max = max(x, 1) + 1.0; 134 | 135 | let x_step = (x_max - x_min) / n as f32; 136 | let x_axis: Vec = (0..n).map(|v| (v as f32 * x_step) + x_min).collect(); 137 | let y_step = (y_max - y_min) / n as f32; 138 | let y_axis: Vec = (0..n).map(|v| (v as f32 * y_step) + y_min).collect(); 139 | 140 | let x_new: Vec> = x_axis 141 | .clone() 142 | .into_iter() 143 | .flat_map(move |v1| y_axis.clone().into_iter().map(move |v2| vec![v1, v2])) 144 | .collect(); 145 | 146 | DenseMatrix::from_2d_vec(&x_new) 147 | } 148 | -------------------------------------------------------------------------------- /src/supervised.rs: -------------------------------------------------------------------------------- 1 | use smartcore::dataset::*; 2 | // DenseMatrix wrapper around Vec 3 | use smartcore::linalg::naive::dense_matrix::DenseMatrix; 4 | // KNN 5 | use smartcore::neighbors::knn_classifier::KNNClassifier; 6 | use smartcore::neighbors::knn_regressor::KNNRegressor; 7 | // Logistic/Linear Regression 8 | use smartcore::linear::elastic_net::{ElasticNet, ElasticNetParameters}; 9 | use smartcore::linear::lasso::{Lasso, LassoParameters}; 10 | use smartcore::linear::linear_regression::LinearRegression; 11 | use smartcore::linear::logistic_regression::LogisticRegression; 12 | use smartcore::linear::ridge_regression::{RidgeRegression, RidgeRegressionParameters}; 13 | // Tree 14 | use smartcore::tree::decision_tree_classifier::DecisionTreeClassifier; 15 | use smartcore::tree::decision_tree_regressor::DecisionTreeRegressor; 16 | // Random Forest 17 | use smartcore::ensemble::random_forest_classifier::RandomForestClassifier; 18 | use smartcore::ensemble::random_forest_regressor::RandomForestRegressor; 19 | // SVM 20 | use smartcore::svm::svc::{SVCParameters, SVC}; 21 | use smartcore::svm::svr::{SVRParameters, SVR}; 22 | use smartcore::svm::Kernels; 23 | // Model performance 24 | use smartcore::metrics::{mean_squared_error, roc_auc_score}; 25 | use smartcore::model_selection::train_test_split; 26 | 27 | use crate::utils; 28 | 29 | pub fn diabetes() { 30 | // Load dataset 31 | let diabetes_data = diabetes::load_dataset(); 32 | // Transform dataset into a NxM matrix 33 | let x = DenseMatrix::from_array( 34 | diabetes_data.num_samples, 35 | diabetes_data.num_features, 36 | &diabetes_data.data, 37 | ); 38 | // These are our target values 39 | let y = diabetes_data.target; 40 | 41 | // Split dataset into training/test (80%/20%) 42 | let (x_train, x_test, y_train, y_test) = train_test_split(&x, &y, 0.2, true); 43 | 44 | // SVM 45 | let y_hat_svm = SVR::fit( 46 | &x_train, 47 | &y_train, 48 | SVRParameters::default() 49 | .with_kernel(Kernels::rbf(0.5)) 50 | .with_c(2000.0) 51 | .with_eps(10.0), 52 | ) 53 | .and_then(|svm| svm.predict(&x_test)) 54 | .unwrap(); 55 | 56 | println!("{:?}", y_hat_svm); 57 | println!("{:?}", y_test); 58 | 59 | println!("MSE: {}", mean_squared_error(&y_test, &y_hat_svm)); 60 | } 61 | 62 | pub fn breast_cancer() { 63 | // Load dataset 64 | let cancer_data = breast_cancer::load_dataset(); 65 | // Transform dataset into a NxM matrix 66 | let x = DenseMatrix::from_array( 67 | cancer_data.num_samples, 68 | cancer_data.num_features, 69 | &cancer_data.data, 70 | ); 71 | // These are our target class labels 72 | let y = cancer_data.target; 73 | 74 | // Split dataset into training/test (80%/20%) 75 | let (x_train, x_test, y_train, y_test) = train_test_split(&x, &y, 0.2, true); 76 | 77 | // KNN classifier 78 | let y_hat_knn = KNNClassifier::fit(&x_train, &y_train, Default::default()) 79 | .and_then(|knn| knn.predict(&x_test)) 80 | .unwrap(); 81 | 82 | // Logistic Regression 83 | let y_hat_lr = LogisticRegression::fit(&x_train, &y_train, Default::default()) 84 | .and_then(|lr| lr.predict(&x_test)) 85 | .unwrap(); 86 | 87 | // Decision Tree 88 | let y_hat_tree = DecisionTreeClassifier::fit(&x_train, &y_train, Default::default()) 89 | .and_then(|tree| tree.predict(&x_test)) 90 | .unwrap(); 91 | 92 | // Random Forest 93 | let y_hat_rf = RandomForestClassifier::fit(&x_train, &y_train, Default::default()) 94 | .and_then(|rf| rf.predict(&x_test)) 95 | .unwrap(); 96 | 97 | // SVM 98 | let y_hat_svm = SVC::fit(&x_train, &y_train, SVCParameters::default().with_c(2.0)) 99 | .and_then(|svm| svm.predict(&x_test)) 100 | .unwrap(); 101 | 102 | // Calculate test error 103 | println!("AUC KNN: {}", roc_auc_score(&y_test, &y_hat_knn)); 104 | println!( 105 | "AUC Logistic Regression: {}", 106 | roc_auc_score(&y_test, &y_hat_lr) 107 | ); 108 | println!("AUC Decision Tree: {}", roc_auc_score(&y_test, &y_hat_tree)); 109 | println!("AUC Random Forest: {}", roc_auc_score(&y_test, &y_hat_rf)); 110 | println!("AUC SVM: {}", roc_auc_score(&y_test, &y_hat_svm)); 111 | } 112 | 113 | pub fn boston() { 114 | // Load dataset 115 | let boston_data = boston::load_dataset(); 116 | // Transform dataset into a NxM matrix 117 | let x = DenseMatrix::from_array( 118 | boston_data.num_samples, 119 | boston_data.num_features, 120 | &boston_data.data, 121 | ); 122 | // These are our target values 123 | let y = boston_data.target; 124 | 125 | let (x_train, x_test, y_train, y_test) = train_test_split(&x, &y, 0.2, true); 126 | 127 | // KNN regressor 128 | let y_hat_knn = KNNRegressor::fit(&x_train, &y_train, Default::default()) 129 | .and_then(|knn| knn.predict(&x_test)) 130 | .unwrap(); 131 | 132 | // Linear Regression 133 | let y_hat_lr = LinearRegression::fit(&x_train, &y_train, Default::default()) 134 | .and_then(|lr| lr.predict(&x_test)) 135 | .unwrap(); 136 | 137 | // Ridge Regression 138 | let y_hat_rr = RidgeRegression::fit( 139 | &x_train, 140 | &y_train, 141 | RidgeRegressionParameters::default().with_alpha(0.5), 142 | ) 143 | .and_then(|rr| rr.predict(&x_test)) 144 | .unwrap(); 145 | 146 | // LASSO 147 | let y_hat_lasso = Lasso::fit( 148 | &x_train, 149 | &y_train, 150 | LassoParameters::default().with_alpha(0.5), 151 | ) 152 | .and_then(|lr| lr.predict(&x_test)) 153 | .unwrap(); 154 | 155 | // Elastic Net 156 | let y_hat_en = ElasticNet::fit( 157 | &x_train, 158 | &y_train, 159 | ElasticNetParameters::default() 160 | .with_alpha(0.5) 161 | .with_l1_ratio(0.5), 162 | ) 163 | .and_then(|lr| lr.predict(&x_test)) 164 | .unwrap(); 165 | 166 | // Decision Tree 167 | let y_hat_tree = DecisionTreeRegressor::fit(&x_train, &y_train, Default::default()) 168 | .and_then(|tree| tree.predict(&x_test)) 169 | .unwrap(); 170 | 171 | // Random Forest 172 | let y_hat_rf = RandomForestRegressor::fit(&x_train, &y_train, Default::default()) 173 | .and_then(|rf| rf.predict(&x_test)) 174 | .unwrap(); 175 | 176 | // Calculate test error 177 | println!("MSE KNN: {}", mean_squared_error(&y_test, &y_hat_knn)); 178 | println!( 179 | "MSE Linear Regression: {}", 180 | mean_squared_error(&y_test, &y_hat_lr) 181 | ); 182 | println!( 183 | "MSE Ridge Regression: {}", 184 | mean_squared_error(&y_test, &y_hat_rr) 185 | ); 186 | println!("MSE LASSO: {}", mean_squared_error(&y_test, &y_hat_lasso)); 187 | println!( 188 | "MSE Elastic Net: {}", 189 | mean_squared_error(&y_test, &y_hat_en) 190 | ); 191 | println!( 192 | "MSE Decision Tree: {}", 193 | mean_squared_error(&y_test, &y_hat_tree) 194 | ); 195 | println!( 196 | "MSE Random Forest: {}", 197 | mean_squared_error(&y_test, &y_hat_rf) 198 | ); 199 | } 200 | 201 | /// Fits Support Vector Classifier (SVC) to generated dataset and plots the decision boundary for three SVC with different kernels.Default 202 | /// The idea for this example is taken from https://scikit-learn.org/stable/auto_examples/svm/plot_iris_svc.html 203 | pub fn svm() { 204 | let num_samples = 100; 205 | let num_features = 2; 206 | 207 | // Generate a dataset with 100 sample, 2 features in each sample, split into 2 groups 208 | let data = generator::make_blobs(num_samples, num_features, 2); 209 | let y: Vec = data.target; 210 | 211 | // Transform dataset into a NxM matrix 212 | let x = DenseMatrix::from_array(data.num_samples, data.num_features, &data.data); 213 | 214 | // We also need a 2x2 mesh grid that we will use to plot decision boundaries. 215 | let mesh = utils::make_meshgrid(&x); 216 | 217 | // SVC with linear kernel 218 | let linear_svc = SVC::fit(&x, &y, Default::default()).unwrap(); 219 | 220 | utils::scatterplot_with_mesh( 221 | &mesh, 222 | &linear_svc.predict(&mesh).unwrap(), 223 | &x, 224 | &y, 225 | "linear_svm", 226 | ) 227 | .unwrap(); 228 | 229 | // SVC with Gaussian kernel 230 | let rbf_svc = SVC::fit( 231 | &x, 232 | &y, 233 | SVCParameters::default().with_kernel(Kernels::rbf(0.7)), 234 | ) 235 | .unwrap(); 236 | 237 | utils::scatterplot_with_mesh(&mesh, &rbf_svc.predict(&mesh).unwrap(), &x, &y, "rbf_svm") 238 | .unwrap(); 239 | 240 | // SVC with 3rd degree polynomial kernel 241 | let poly_svc = SVC::fit( 242 | &x, 243 | &y, 244 | SVCParameters::default().with_kernel(Kernels::polynomial_with_degree(3.0, num_features)), 245 | ) 246 | .unwrap(); 247 | 248 | utils::scatterplot_with_mesh( 249 | &mesh, 250 | &poly_svc.predict(&mesh).unwrap(), 251 | &x, 252 | &y, 253 | "polynomial_svm", 254 | ) 255 | .unwrap(); 256 | } 257 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------