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. 3 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 4 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::*;   // SequentialBuilder, Sequential, History, Tensor, Shape, 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>)
ShapeShape (what SequentialBuilder::build takes)
ModelSequentialBuilder (collects the layers), Sequential (what build gives back)
Training historyHistory (1 loss per epoch, what fit returns)
ContextCtx (the per-pass cache, gradient store, and training flag that a layer’s forward and backward share)
Graph modelGraphBuilder (collects nodes and layers for a non-chain topology), Graph (what build gives back), NodeId (a handle to 1 node of the graph)
Core layersDense, Embedding, Flatten, Identity, Reshape, Reverse, Permute, RepeatVector, Rescaling, Activation
Merge layersAdd, Average, Concatenate, Maximum, Minimum, Multiply, Subtract
Activation layersLinear, ReLU, LeakyReLU, ELU, SELU, Sigmoid, HardSigmoid, Tanh, Softplus, Softsign, Exponential, Softmax, PReLU
ConvolutionConv1D, Conv2D, Conv3D, Conv1DTranspose, Conv2DTranspose, Conv3DTranspose, DepthwiseConv1D, DepthwiseConv2D, SeparableConv1D, SeparableConv2D, PaddingType, ConvPadding
BorderZeroPadding1D/2D/3D, Cropping1D/2D/3D, Border1D/2D/3D
PoolingMaxPooling1D/2D/3D, AveragePooling1D/2D/3D, GlobalMaxPooling1D/2D/3D, GlobalAveragePooling1D/2D/3D
UpsamplingUpSampling1D/2D/3D, Interpolation, Factor2D, Factor3D
RecurrentSimpleRNN, LSTM, GRU
RegularizationDropout, SpatialDropout1D/2D/3D, GaussianDropout, GaussianNoise
NormalizationBatchNormalization, LayerNormalization, LayerNormalizationAxis, GroupNormalization, InstanceNormalization, UnitNormalization, UnitNormalizationAxis
LossesMeanSquaredError, MeanAbsoluteError, BinaryCrossEntropy, CategoricalCrossEntropy, SparseCategoricalCrossEntropy
OptimizersSGD, Adam, AdamW, RMSprop, AdaGrad

Average names 2 different items in this crate. This table lists it as a merge layer that averages its inputs. The metrics table below lists it as an averaging mode for a classification score. use rustyml::prelude::* globs both categories, so an explicit re-export at the prelude root breaks the tie: plain Average is always the averaging mode. Reach the merge layer by its full path, rustyml::neural_network::layers::Average.

Note the exact casing on RMSprop (lowercase p). Activations come in 2 forms. One is the standalone layers in the table above. The other is a variant of the Activation enum, such as Activation::ReLU or Activation::LeakyReLU { negative_slope }. Any layer that accepts an Activation also accepts a standalone activation layer, because each one implements Layer and Into<Activation>.

The table has no gap. A whole model, from the first add to predict, needs the 1 glob and nothing else.

PReLU is the exception: it holds trainable slopes, so it is a layer and nothing else. 3.2. Dense Layers and Activations lists the full set with the formula for each one.

For example, 1 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(8, Activation::ReLU) and Dense::new(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 for the metrics module in depth. 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_networkSequentialBuilder, Sequential, History, Tensor, Shape, 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 5 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, SequentialBuilder, Historyrustyml::neural_network::sequential:: (all 3 are in the prelude as well)
Graph, GraphBuilder, NodeIdrustyml::neural_network::graph:: (all 3 are in the prelude as well)
Tensor, Shape, Ctxrustyml::neural_network::
Dense, Embedding, Flatten, Identity, Reshape, Reverse, Permute, RepeatVector, Activationrustyml::neural_network::layers::
Add, Average (the merge layer), Concatenate, Maximum, Minimum, Multiply, Subtractrustyml::neural_network::layers:: (also in the prelude, but write the full path for Average once rustyml::prelude::* is in scope)
ZeroPadding1D/2D/3D, Cropping1D/2D/3D, Border1D/2D/3Drustyml::neural_network::layers::border:: (also re-exported under rustyml::neural_network::layers::)
UpSampling1D/2D/3D, Interpolation, Factor2D, Factor3Drustyml::neural_network::layers::upsampling:: (also re-exported under rustyml::neural_network::layers::)
Rescaling, and ConvPadding for causal Conv1D paddingrustyml::neural_network::layers:: (both are in the prelude as well)
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, Average (the averaging mode)rustyml::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::)