macro_rules! forest_classifier {
($name:ident, $params:ident, $kind:expr, $($doc:expr),+ $(,)?) => {
$(#[doc = $doc])+
#[derive(Clone, Debug, PartialEq)]
pub struct $name {
pub(crate) params: $params,
pub(crate) core: $crate::ensemble::forest::model::ClassifierCore,
}
impl $name {
#[inline]
pub fn n_features_in(&self) -> usize {
self.core.n_features_in
}
#[inline]
pub fn get_params(&self) -> &$params {
&self.params
}
#[inline]
pub fn classes(&self) -> &[u8] {
&self.core.classes
}
pub fn fit(
data: &$crate::data::MatrixView<'_>,
targets: &$crate::data::BinaryTargets,
params: $params,
) -> Result<Self, $crate::api::ModelError> {
Self::fit_binary(data, targets, None, params)
}
pub fn fit_weighted(
data: &$crate::data::MatrixView<'_>,
targets: &$crate::data::BinaryTargets,
sample_weights: &$crate::data::SampleWeights,
params: $params,
) -> Result<Self, $crate::api::ModelError> {
Self::fit_binary(data, targets, Some(sample_weights), params)
}
fn fit_binary(
data: &$crate::data::MatrixView<'_>,
targets: &$crate::data::BinaryTargets,
sample_weights: Option<&$crate::data::SampleWeights>,
params: $params,
) -> Result<Self, $crate::api::ModelError> {
use $crate::ensemble::forest::{model, training};
let config = training::ForestConfig::from(¶ms);
model::validate_common(data, targets.as_slice().len(), sample_weights, &config)?;
let saw_zero = targets.as_slice().contains(&0);
let saw_one = targets.as_slice().contains(&1);
let classes = match (saw_zero, saw_one) {
(true, true) => vec![0, 1],
(true, false) => vec![0],
(false, true) => vec![1],
(false, false) => unreachable!("non-empty validated binary targets"),
};
let trees = training::train_forest(
data,
targets.as_slice(),
sample_weights.map($crate::data::SampleWeights::as_slice),
&config,
$crate::tree::Classification,
)?;
Ok(Self {
params,
core: model::ClassifierCore {
n_features_in: data.columns(),
classes,
forest: model::Forest::Binary(trees),
},
})
}
pub fn fit_multiclass(
data: &$crate::data::MatrixView<'_>,
targets: &$crate::data::ClassTargets,
params: $params,
) -> Result<Self, $crate::api::ModelError> {
Self::fit_multiclass_internal(data, targets, None, params)
}
pub fn fit_multiclass_weighted(
data: &$crate::data::MatrixView<'_>,
targets: &$crate::data::ClassTargets,
sample_weights: &$crate::data::SampleWeights,
params: $params,
) -> Result<Self, $crate::api::ModelError> {
Self::fit_multiclass_internal(data, targets, Some(sample_weights), params)
}
fn fit_multiclass_internal(
data: &$crate::data::MatrixView<'_>,
targets: &$crate::data::ClassTargets,
sample_weights: Option<&$crate::data::SampleWeights>,
params: $params,
) -> Result<Self, $crate::api::ModelError> {
use $crate::ensemble::forest::{model, training};
let config = training::ForestConfig::from(¶ms);
model::validate_common(data, targets.len(), sample_weights, &config)?;
let classes = targets.classes().to_vec();
let class_of_row = targets
.as_slice()
.iter()
.map(|&label| {
targets
.class_index(label)
.expect("every target label is an observed class")
})
.collect::<Vec<_>>();
let trees = training::train_class_forest(
data,
&class_of_row,
classes.len(),
sample_weights.map($crate::data::SampleWeights::as_slice),
&config,
)?;
Ok(Self {
params,
core: model::ClassifierCore {
n_features_in: data.columns(),
classes,
forest: model::Forest::Multiclass(trees),
},
})
}
pub fn predict_one(&self, row: &[f32]) -> Result<u8, $crate::api::ModelError> {
self.core.predict_one(row)
}
pub fn predict(
&self,
data: &$crate::data::MatrixView<'_>,
) -> Result<Vec<u8>, $crate::api::ModelError> {
self.core.predict(data)
}
pub fn predict_into(
&self,
data: &$crate::data::MatrixView<'_>,
output: &mut [u8],
) -> Result<(), $crate::api::ModelError> {
self.core.predict_into(data, output)
}
pub fn predict_proba_one(
&self,
row: &[f32],
) -> Result<Vec<f32>, $crate::api::ModelError> {
self.core.predict_proba_one(row)
}
pub fn predict_proba_one_into(
&self,
row: &[f32],
output: &mut [f32],
) -> Result<(), $crate::api::ModelError> {
self.core.predict_proba_one_into(row, output)
}
pub fn predict_proba(
&self,
data: &$crate::data::MatrixView<'_>,
) -> Result<Vec<f32>, $crate::api::ModelError> {
<Self as $crate::api::ProbabilisticClassifier>::predict_proba(self, data)
}
pub fn predict_proba_into(
&self,
data: &$crate::data::MatrixView<'_>,
output: &mut [f32],
) -> Result<(), $crate::api::ModelError> {
self.core.predict_proba_into(data, output)
}
pub fn predict_class_proba_one(
&self,
row: &[f32],
class: u8,
) -> Result<f32, $crate::api::ModelError> {
self.core.predict_class_proba_one(row, class)
}
pub fn predict_class_proba(
&self,
data: &$crate::data::MatrixView<'_>,
class: u8,
) -> Result<Vec<f32>, $crate::api::ModelError> {
<Self as $crate::api::ProbabilisticClassifier>::predict_class_proba(
self, data, class,
)
}
pub fn predict_class_proba_into(
&self,
data: &$crate::data::MatrixView<'_>,
class: u8,
output: &mut [f32],
) -> Result<(), $crate::api::ModelError> {
self.core.predict_class_proba_into(data, class, output)
}
pub fn predict_positive_proba_one(
&self,
row: &[f32],
) -> Result<f32, $crate::api::ModelError> {
self.core.predict_positive_proba_one(row)
}
pub fn predict_positive_proba(
&self,
data: &$crate::data::MatrixView<'_>,
) -> Result<Vec<f32>, $crate::api::ModelError> {
self.core.predict_positive_proba(data)
}
pub fn predict_positive_proba_into(
&self,
data: &$crate::data::MatrixView<'_>,
output: &mut [f32],
) -> Result<(), $crate::api::ModelError> {
self.core.predict_positive_proba_into(data, output)
}
#[cfg(test)]
pub(crate) fn binary_trees(&self) -> &[$crate::tree::PackedTree] {
self.core.forest.binary_trees()
}
}
impl $crate::api::Estimator for $name {
fn n_features_in(&self) -> usize {
self.core.n_features_in
}
}
impl $crate::api::Classifier for $name {
fn classes(&self) -> &[u8] {
&self.core.classes
}
fn predict_into(
&self,
data: &$crate::data::MatrixView<'_>,
output: &mut [u8],
) -> Result<(), $crate::api::ModelError> {
self.core.predict_into(data, output)
}
}
impl $crate::api::ProbabilisticClassifier for $name {
fn predict_proba_into(
&self,
data: &$crate::data::MatrixView<'_>,
output: &mut [f32],
) -> Result<(), $crate::api::ModelError> {
self.core.predict_proba_into(data, output)
}
fn predict_class_proba_into(
&self,
data: &$crate::data::MatrixView<'_>,
class: u8,
output: &mut [f32],
) -> Result<(), $crate::api::ModelError> {
self.core.predict_class_proba_into(data, class, output)
}
}
impl $crate::api::HasParams for $name {
type Params = $params;
fn get_params(&self) -> &Self::Params {
&self.params
}
}
impl $crate::artifact::ModelArtifact for $name {
const ARTIFACT_KIND: u16 = $kind;
fn to_artifact(
&self,
schema: [u8; 32],
) -> Result<Vec<u8>, $crate::artifact::ArtifactError> {
$crate::ensemble::forest::codec::encode_classifier(
Self::ARTIFACT_KIND,
&self.params.artifact_fields(self.core.n_features_in),
&self.core.classes,
&self.core.forest,
schema,
)
}
fn from_artifact(
bytes: &[u8],
schema: [u8; 32],
) -> Result<Self, $crate::artifact::ArtifactError> {
let (fields, classes, forest) =
$crate::ensemble::forest::codec::decode_classifier(
Self::ARTIFACT_KIND,
bytes,
schema,
)?;
Ok(Self {
params: $params::from_artifact_fields(&fields),
core: $crate::ensemble::forest::model::ClassifierCore {
n_features_in: fields.n_features_in,
classes,
forest,
},
})
}
}
impl $crate::api::HasCapabilities for $name {
const CAPABILITIES: $crate::api::Capabilities = $crate::api::Capabilities::NONE
.with_sample_weights(true)
.with_artifact(true)
.with_multiclass(true)
.with_probability(true);
}
};
}
macro_rules! forest_regressor {
($name:ident, $params:ident, $kind:expr, $objective:expr, $($doc:expr),+ $(,)?) => {
$(#[doc = $doc])+
#[derive(Clone, Debug, PartialEq)]
pub struct $name {
pub(crate) params: $params,
pub(crate) core: $crate::ensemble::forest::model::RegressorCore,
}
impl $name {
#[inline]
pub fn n_features_in(&self) -> usize {
self.core.n_features_in
}
#[inline]
pub fn get_params(&self) -> &$params {
&self.params
}
pub fn fit(
data: &$crate::data::MatrixView<'_>,
targets: &$crate::data::RegressionTargets,
params: $params,
) -> Result<Self, $crate::api::ModelError> {
Self::fit_internal(data, targets, None, params)
}
pub fn fit_weighted(
data: &$crate::data::MatrixView<'_>,
targets: &$crate::data::RegressionTargets,
sample_weights: &$crate::data::SampleWeights,
params: $params,
) -> Result<Self, $crate::api::ModelError> {
Self::fit_internal(data, targets, Some(sample_weights), params)
}
fn fit_internal(
data: &$crate::data::MatrixView<'_>,
targets: &$crate::data::RegressionTargets,
sample_weights: Option<&$crate::data::SampleWeights>,
params: $params,
) -> Result<Self, $crate::api::ModelError> {
use $crate::ensemble::forest::{model, training};
let config = training::ForestConfig::from(¶ms);
model::validate_common(data, targets.as_slice().len(), sample_weights, &config)?;
let trees = training::train_forest(
data,
targets.as_slice(),
sample_weights.map($crate::data::SampleWeights::as_slice),
&config,
$objective,
)?;
Ok(Self {
params,
core: model::RegressorCore {
n_features_in: data.columns(),
trees,
},
})
}
pub fn predict_one(&self, row: &[f32]) -> Result<f32, $crate::api::ModelError> {
self.core.predict_one(row)
}
pub fn predict(
&self,
data: &$crate::data::MatrixView<'_>,
) -> Result<Vec<f32>, $crate::api::ModelError> {
<Self as $crate::api::Regressor>::predict(self, data)
}
pub fn predict_into(
&self,
data: &$crate::data::MatrixView<'_>,
output: &mut [f32],
) -> Result<(), $crate::api::ModelError> {
self.core.predict_into(data, output)
}
}
impl $crate::artifact::ModelArtifact for $name {
const ARTIFACT_KIND: u16 = $kind;
fn to_artifact(
&self,
schema: [u8; 32],
) -> Result<Vec<u8>, $crate::artifact::ArtifactError> {
$crate::ensemble::forest::codec::encode_regressor(
Self::ARTIFACT_KIND,
&self.params.artifact_fields(self.core.n_features_in),
&self.core.trees,
schema,
)
}
fn from_artifact(
bytes: &[u8],
schema: [u8; 32],
) -> Result<Self, $crate::artifact::ArtifactError> {
let (fields, trees) = $crate::ensemble::forest::codec::decode_regressor(
Self::ARTIFACT_KIND,
bytes,
schema,
)?;
Ok(Self {
params: $params::from_artifact_fields(&fields),
core: $crate::ensemble::forest::model::RegressorCore {
n_features_in: fields.n_features_in,
trees,
},
})
}
}
impl $crate::api::Estimator for $name {
fn n_features_in(&self) -> usize {
self.core.n_features_in
}
}
impl $crate::api::Regressor for $name {
fn predict_into(
&self,
data: &$crate::data::MatrixView<'_>,
output: &mut [f32],
) -> Result<(), $crate::api::ModelError> {
self.core.predict_into(data, output)
}
}
impl $crate::api::HasParams for $name {
type Params = $params;
fn get_params(&self) -> &Self::Params {
&self.params
}
}
impl $crate::api::HasCapabilities for $name {
const CAPABILITIES: $crate::api::Capabilities = $crate::api::Capabilities::NONE
.with_sample_weights(true)
.with_artifact(true);
}
};
}
pub(crate) use {forest_classifier, forest_regressor};