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
| Group | Items |
|---|---|
| Estimator traits | Fit, Predict, Transform, FitTransform |
| Shared enums | DistanceCalculationMetric, RegularizationType, KernelType |
| Regression | LinearRegression, LeastSquaresSolver |
| Linear classification | LogisticRegression, generate_polynomial_features |
| Neighbors | KNN, WeightingStrategy |
| Trees | DecisionTree, DecisionTreeParams, Algorithm |
| SVM | SVC, LinearSVC |
| Discriminant analysis | LDA, DiscriminantSolver, Shrinkage |
| Clustering | KMeans, DBSCAN, MeanShift, estimate_bandwidth |
| Decomposition | PCA, KernelPCA, EigenSolver, SVDSolver |
| Manifold | TSNE, TSNEMethod, Init |
| Anomaly detection | IsolationForest, Contamination |
Neural network
| Group | Items |
|---|---|
| Tensor | Tensor (alias for ArrayD<f32>) |
| Shape | Shape (what SequentialBuilder::build takes) |
| Model | SequentialBuilder (collects the layers), Sequential (what build gives back) |
| Training history | History (1 loss per epoch, what fit returns) |
| Context | Ctx (the per-pass cache, gradient store, and training flag that a layer’s forward and backward share) |
| Graph model | GraphBuilder (collects nodes and layers for a non-chain topology), Graph (what build gives back), NodeId (a handle to 1 node of the graph) |
| Core layers | Dense, Embedding, Flatten, Identity, Reshape, Reverse, Permute, RepeatVector, Rescaling, Activation |
| Merge layers | Add, Average, Concatenate, Maximum, Minimum, Multiply, Subtract |
| Activation layers | Linear, ReLU, LeakyReLU, ELU, SELU, Sigmoid, HardSigmoid, Tanh, Softplus, Softsign, Exponential, Softmax, PReLU |
| Convolution | Conv1D, Conv2D, Conv3D, Conv1DTranspose, Conv2DTranspose, Conv3DTranspose, DepthwiseConv1D, DepthwiseConv2D, SeparableConv1D, SeparableConv2D, PaddingType, ConvPadding |
| Border | ZeroPadding1D/2D/3D, Cropping1D/2D/3D, Border1D/2D/3D |
| Pooling | MaxPooling1D/2D/3D, AveragePooling1D/2D/3D, GlobalMaxPooling1D/2D/3D, GlobalAveragePooling1D/2D/3D |
| Upsampling | UpSampling1D/2D/3D, Interpolation, Factor2D, Factor3D |
| Recurrent | SimpleRNN, LSTM, GRU |
| Regularization | Dropout, SpatialDropout1D/2D/3D, GaussianDropout, GaussianNoise |
| Normalization | BatchNormalization, LayerNormalization, LayerNormalizationAxis, GroupNormalization, InstanceNormalization, UnitNormalization, UnitNormalizationAxis |
| Losses | MeanSquaredError, MeanAbsoluteError, BinaryCrossEntropy, CategoricalCrossEntropy, SparseCategoricalCrossEntropy |
| Optimizers | SGD, 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
| Group | Items |
|---|---|
| Types | ConfusionMatrix, MulticlassConfusionMatrix, Average |
| Regression | mean_squared_error, root_mean_squared_error, mean_absolute_error, median_absolute_error, mean_absolute_percentage_error, r2_score, explained_variance_score |
| Classification | accuracy, roc_auc, roc_curve, precision_recall_curve, average_precision, log_loss, cohen_kappa, top_k_accuracy |
| Clustering | adjusted_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
| Group | Items |
|---|---|
| Scaling | standardize, StandardizationAxis, normalize, NormalizationAxis, NormalizationOrder, StandardScaler, MinMaxScaler, MaxAbsScaler, RobustScaler, Normalizer |
| Label encoding | to_categorical, to_categorical_with_mapping, to_sparse_categorical |
| Splitting | train_test_split, train_test_split_stratified |
| Traits | Fit, 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 feature | What rustyml::prelude::* contains |
|---|---|
machine_learning | the classical estimators, traits, and shared enums |
neural_network | SequentialBuilder, Sequential, History, Tensor, Shape, layers, losses, optimizers |
metrics | the metric functions and the confusion-matrix types |
utils | standardize, normalize, the whole scaler family, encoders, split functions, the estimator traits |
default (all 5 modules) | every module |
full | every 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 / function | Fully-qualified path |
|---|---|
LinearRegression, LogisticRegression | rustyml::machine_learning:: |
KNN, DecisionTree, SVC, LinearSVC, LDA | rustyml::machine_learning:: |
KMeans, DBSCAN, MeanShift | rustyml::machine_learning:: |
PCA, KernelPCA, TSNE, IsolationForest, Contamination | rustyml::machine_learning:: |
Fit, Predict, Transform, FitTransform | rustyml::traits:: (also re-exported under rustyml::machine_learning:: and rustyml::utils::) |
DistanceCalculationMetric | rustyml::machine_learning:: or rustyml::math:: |
Sequential, SequentialBuilder, History | rustyml::neural_network::sequential:: (all 3 are in the prelude as well) |
Graph, GraphBuilder, NodeId | rustyml::neural_network::graph:: (all 3 are in the prelude as well) |
Tensor, Shape, Ctx | rustyml::neural_network:: |
Dense, Embedding, Flatten, Identity, Reshape, Reverse, Permute, RepeatVector, Activation | rustyml::neural_network::layers:: |
Add, Average (the merge layer), Concatenate, Maximum, Minimum, Multiply, Subtract | rustyml::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/3D | rustyml::neural_network::layers::border:: (also re-exported under rustyml::neural_network::layers::) |
UpSampling1D/2D/3D, Interpolation, Factor2D, Factor3D | rustyml::neural_network::layers::upsampling:: (also re-exported under rustyml::neural_network::layers::) |
Rescaling, and ConvPadding for causal Conv1D padding | rustyml::neural_network::layers:: (both are in the prelude as well) |
Adam, SGD, AdamW, RMSprop, AdaGrad | rustyml::neural_network::optimizers:: |
MeanSquaredError, CategoricalCrossEntropy, and the rest | rustyml::neural_network::losses:: |
accuracy, mean_squared_error, r2_score, and the rest | rustyml::metrics:: |
ConfusionMatrix, MulticlassConfusionMatrix, Average (the averaging mode) | rustyml::metrics:: |
standardize, StandardizationAxis | rustyml::utils::standardize:: |
StandardScaler, MinMaxScaler, MaxAbsScaler, RobustScaler, Normalizer | rustyml::utils:: (defined in rustyml::utils::scaler::) |
normalize, NormalizationAxis, NormalizationOrder | rustyml::utils::normalize:: |
train_test_split, train_test_split_stratified | rustyml::utils::train_test_split:: |
to_categorical, to_sparse_categorical, and the rest | rustyml::utils::label_encoding:: |
Error, RustymlResult | rustyml::error:: |
set_global_seed, clear_global_seed | rustyml:: (or rustyml::random::) |