Expand description
A fast decision trees and random forest implementation.
§Classification
Rafor provides a decision tree (DT) classifier dt::Classifier and a random forest (RF) classifier
rf::Classifier. The class label is i64 value. Classifiers use Gini index for
evaluating the split impurity.
To get probabilities distribution, there is a method proba which returns a Vec<f32> of
length num_samples * num_classes where i-th chunk of length num_classes contains the
probabilities of classes for i-th sample. The classes are ordered by their values.
§Regression
Regression models are decision tree regressor dt::Regressor and random forest regressor
rf::Regressor. The targets are f32 values. By default regressors use MSE score for evaluating
the split impurity.
§Dataset
Multiple samples for inference or training are provided as a single f32 slice, where each chunk of
the size of feature space (num_features) is treated as a feature vector of a single sample.
During training, num_features is derived by dividing the length of the input f32 slice by
the number of provided targets.
§Model training
All models provide method trainer() which returns a Trainer object for particular model. The
Trainer incorporates builder interface (use rafor::prelude::*) for setting optional
train parameters and a method train for feeding dataset and targets.
Currently supported training parameters are given below. Please see default values in concrete models.
§Common parameters
The following parameters are common for decision trees and forests.
max_depth: usize defines the maximal tree depth.
max_features: MaxFeaturesPolicy, the maximal number of features that are considered when finding
best split value for decision tree node. Note that if no split value is found, additional
features will be considered until a split is found or all features are used.
seed: u64, defines the seed for random number generator. For trees the random numbers are
used for generating the feature sequence when finding a split if max_features is less than the
number of all features of the training dataset. In RF, datasets are generated using random
sampling (bootstrapping), and the seeds for individual trees are derived from the base seed.
min_samples_leaf: usize, guarantees that each leaf has at least min_samples_leaf samples.
Default: 1.
min_samples_split: usize, the minimal number of samples in a node to consider splitting it.
weights: Vec<f32> defines the weight for each sample. If empty, each sample is weighted
with 1.0
§Ensemble parameters
num_trees: usize defines the number of individual trees in ensemble.
num_threads: usize defines the number of CPU threads to use for training.
§Model serialization and deserialization
All models support serde, so any lib that supports serde
can be used for serialization and deserialization.
§Example
use rafor::prelude::*; // Required for the `.with_*` builder methods and `.num_classes()`.
use rafor::rf::Classifier;
// Dataset for 5 samples (number of samples is defined by the number of targets).
let dataset = [
0.7, 0.0,
0.8, 1.0,
0.3, 0.0,
1.0, 1.3,
0.4, 2.1
];
// Target classes.
let targets = [1, 5, 1, -15, 5];
let predictor: Classifier = Classifier::trainer()
.with_max_depth(15)
.with_trees(40)
.with_threads(num_cpus::get())
.with_seed(42)
.train(&dataset, &targets);
// Get predictions for same dataset.
let predictions = predictor.predict_batch(&dataset, num_cpus::get());
println!("Predictions: {:?}", predictions);
// Now let's get probability distributions for each class. Use all CPU cores.
let proba = predictor.proba(&dataset, num_cpus::get());
println!("Probability distributions:");
for p in proba.chunks(predictor.num_classes()) {
println!("{:?}", p);
}§Space / performance considerations
Rafor utilizes a compact tree representation under the following restrictions:
- split threshold is
f32; - feature index is
u16, up to 2^16 = 65,536 features allowed; - in regression tasks, the target type is
f32; - in classification tasks, the class is represented by
u32(the inputi64labels are mapped intou32internally, and restored during prediction); - child node index is
u32, up to 2^32 = 4,294,967,296 nodes allowed.
§Tree types
Rafor provides a flexible mechanism to use custom decision trees. A compatible tree structure
must support trait Predictor. Currently there are two decision tree types available out of
the box: BlockTree and CompactTree.
§BlockTree
This is an exceptionally fast predictor, but it requires more RAM than CompactTree (about
4.5 times more in the worst case). The tree is stored as an array of 64-byte blocks; each
block holds a balanced subtree of depth 2, i.e. 3 decision levels (splits) packed into a single
cache line. A memory jump means a distinct cache-line access, so resolving a path needs ~3
splits per jump instead of 1 - which yields up to 3x fewer memory jumps per prediction than
CompactTree. BlockTree is the default predictor.
§CompactTree
This is a fast predictor focusing on memory efficiency. Memory scales as 8 bytes per tree node
on average: only internal (parent) nodes are stored, and each node reserves a u32 per child -
either a child index or, for a leaf child, the encoded leaf value (f32 for regression trees,
u32 index into the class-probability table for classification trees). Because leaves occupy
no dedicated storage, roughly half of all vertices cost nothing. Classification trees
additionally store a per-leaf class-probability table. CompactTree also provides a compact,
bit-packed serialization format.
Modules§
- dt
- Decision Tree implementation.
- ensemble_
classifier - ensemble_
regressor - prelude
- rf
- Random Forest implementation.
- trainer_
builders - tree_
classifier - tree_
regressor
Structs§
Enums§
- MaxFeatures
Policy - Defines the limiting strategy for a number of features that are selected at each split.