Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

1.5. The Prelude and Imports

1.5.1. Three ways to bring names into scope

Glob the whole prelude

use rustyml::prelude::*;

This pulls everything into the current scope. It suits getting code written quickly, without having to look up where each item lives.

Glob a single prelude category

The prelude is split into four submodules, so you can import just what you need:

use rustyml::prelude::machine_learning::*; // classical estimators, traits, and shared enums
use rustyml::prelude::neural_network::*;   // Sequential, History, Tensor, layers, losses, optimizers
use rustyml::prelude::metrics::*;          // the evaluation-metric functions and types
use rustyml::prelude::utils::*;            // standardize, normalize, scalers, encoders, split

Use this when the file you are writing clearly belongs to a single domain.

Import by exact path

use rustyml::machine_learning::LinearRegression;
use rustyml::traits::{Fit, Predict};
use rustyml::metrics::r2_score;

Library code that has to be maintained long-term should prefer this style.

1.5.2. What the prelude re-exports

The prelude is a hand-picked list: it re-exports only the items you reach for often. The tables below show exactly what each prelude submodule re-exports.

Machine learning

GroupItems
Estimator traitsFit, Predict, Transform, FitTransform
Shared enumsDistanceCalculationMetric, RegularizationType, KernelType
RegressionLinearRegression, LeastSquaresSolver
Linear classificationLogisticRegression, generate_polynomial_features
NeighborsKNN, WeightingStrategy
TreesDecisionTree, DecisionTreeParams, Algorithm
SVMSVC, LinearSVC
Discriminant analysisLDA, DiscriminantSolver, Shrinkage
ClusteringKMeans, DBSCAN, MeanShift, estimate_bandwidth
DecompositionPCA, KernelPCA, EigenSolver, SVDSolver
ManifoldTSNE, TSNEMethod, Init
Anomaly detectionIsolationForest, Contamination

Neural network

GroupItems
TensorTensor (alias for ArrayD<f32>)
ModelSequential
Training historyHistory (one loss per epoch, what fit returns)
Core layersDense, Flatten, Activation
Activation layersLinear, ReLU, Sigmoid, Softmax, Tanh
ConvolutionConv1D, Conv2D, Conv3D, DepthwiseConv2D, SeparableConv2D, PaddingType
PoolingMaxPooling1D/2D/3D, AveragePooling1D/2D/3D, GlobalMaxPooling1D/2D/3D, GlobalAveragePooling1D/2D/3D
RecurrentSimpleRNN, LSTM, GRU
RegularizationDropout, SpatialDropout1D/2D/3D, GaussianDropout, GaussianNoise
NormalizationBatchNormalization, LayerNormalization, LayerNormalizationAxis, GroupNormalization, InstanceNormalization
LossesMeanSquaredError, MeanAbsoluteError, BinaryCrossEntropy, CategoricalCrossEntropy, SparseCategoricalCrossEntropy
OptimizersSGD, Adam, AdamW, RMSprop, AdaGrad

Note the exact casing on RMSprop (lowercase p). Activations come in two forms: one is the standalone layers ReLU/Softmax/Linear/Sigmoid/Tanh. The other is, in any layer that accepts an Activation enum, either picking a variant (Activation::ReLU, Activation::Softmax, Activation::Linear, Activation::Sigmoid, Activation::Tanh) or passing one of those standalone activation layers instead (they impl Layer and convert Into<Activation>).

For example, one of Dense::new’s parameters is activation: impl Into<Activation>, so you can pass either an Activation enum variant or a standalone activation layer: Dense::new(3, 8, Activation::ReLU) and Dense::new(3, 8, ReLU::new()) are equivalent.

Metrics

GroupItems
TypesConfusionMatrix, MulticlassConfusionMatrix, Average
Regressionmean_squared_error, root_mean_squared_error, mean_absolute_error, median_absolute_error, mean_absolute_percentage_error, r2_score, explained_variance_score
Classificationaccuracy, roc_auc, roc_curve, precision_recall_curve, average_precision, log_loss, cohen_kappa, top_k_accuracy
Clusteringadjusted_rand_index, adjusted_mutual_info, normalized_mutual_info, homogeneity_score, completeness_score, v_measure_score, fowlkes_mallows_score, silhouette_score, davies_bouldin_score, calinski_harabasz_score

Unlike the error-propagation design in the rest of the crate, the metric functions panic outright on an error, which keeps the module lightweight; see 5. Model Evaluation. Their argument order is (y_true, y_pred), matching scikit-learn.

Utilities

GroupItems
Scalingstandardize, StandardizationAxis, normalize, NormalizationAxis, NormalizationOrder, StandardScaler, MinMaxScaler, MaxAbsScaler, RobustScaler, Normalizer
Label encodingto_categorical, to_categorical_with_mapping, to_sparse_categorical
Splittingtrain_test_split, train_test_split_stratified
TraitsFit, Predict, Transform, FitTransform

1.5.3. Feature gates decide what the prelude contains

The rustyml::prelude module is always compiled, but each submodule only appears once the matching module feature is enabled. So use rustyml::prelude::* does not mean everything RustyML can do — it means everything the features you enabled can do. For what each feature contains, see 1.2 Installation and Feature Flags.

Enabled featureWhat rustyml::prelude::* contains
machine_learningthe classical estimators, traits, and shared enums
neural_networkSequential, History, Tensor, layers, losses, optimizers
metricsthe metric functions and the confusion-matrix types
utilsstandardize, normalize, the whole scaler family, encoders, split functions, the estimator traits
default (all five modules)every module
fullevery module

1.5.4. Using fully-qualified paths

To find where an item lives, docs.rs/rustyml is the place to look. Here is a lookup table for the main types:

Type / functionFully-qualified path
LinearRegression, LogisticRegressionrustyml::machine_learning::
KNN, DecisionTree, SVC, LinearSVC, LDArustyml::machine_learning::
KMeans, DBSCAN, MeanShiftrustyml::machine_learning::
PCA, KernelPCA, TSNE, IsolationForest, Contaminationrustyml::machine_learning::
Fit, Predict, Transform, FitTransformrustyml::traits:: (also re-exported under rustyml::machine_learning:: and rustyml::utils::)
DistanceCalculationMetricrustyml::machine_learning:: or rustyml::math::
Sequential, Historyrustyml::neural_network::sequential::
Tensorrustyml::neural_network::
Dense, Flatten, Activationrustyml::neural_network::layers::
Adam, SGD, AdamW, RMSprop, AdaGradrustyml::neural_network::optimizers::
MeanSquaredError, CategoricalCrossEntropy, and the restrustyml::neural_network::losses::
accuracy, mean_squared_error, r2_score, and the restrustyml::metrics::
ConfusionMatrix, MulticlassConfusionMatrix, Averagerustyml::metrics::
standardize, StandardizationAxisrustyml::utils::standardize::
StandardScaler, MinMaxScaler, MaxAbsScaler, RobustScaler, Normalizerrustyml::utils:: (defined in rustyml::utils::scaler::)
normalize, NormalizationAxis, NormalizationOrderrustyml::utils::normalize::
train_test_split, train_test_split_stratifiedrustyml::utils::train_test_split::
to_categorical, to_sparse_categorical, and the restrustyml::utils::label_encoding::
Error, RustymlResultrustyml::error::
set_global_seed, clear_global_seedrustyml:: (or rustyml::random::)