#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MaxFeatures {
All,
Sqrt,
Count(usize),
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NJobs {
#[default]
Serial,
All,
Count(usize),
}
impl NJobs {
pub(crate) fn resolved(self) -> usize {
match self {
Self::Serial => 1,
Self::All => std::thread::available_parallelism()
.map(usize::from)
.unwrap_or(1),
Self::Count(count) => count,
}
}
}
macro_rules! forest_params {
($name:ident, $default_features:expr) => {
#[doc = concat!("Parameters for [`", stringify!($name), "`].")]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct $name {
n_estimators: usize,
max_depth: Option<usize>,
min_samples_split: usize,
min_samples_leaf: usize,
max_features: MaxFeatures,
bootstrap: bool,
random_state: u64,
n_jobs: NJobs,
}
impl Default for $name {
fn default() -> Self {
Self {
n_estimators: 100,
max_depth: None,
min_samples_split: 2,
min_samples_leaf: 1,
max_features: $default_features,
bootstrap: true,
random_state: 0,
n_jobs: NJobs::Serial,
}
}
}
impl $name {
#[must_use]
pub fn with_n_estimators(mut self, n_estimators: usize) -> Self {
self.n_estimators = n_estimators;
self
}
#[must_use]
pub fn with_max_depth(mut self, max_depth: Option<usize>) -> Self {
self.max_depth = max_depth;
self
}
#[must_use]
pub fn with_min_samples_split(mut self, min_samples_split: usize) -> Self {
self.min_samples_split = min_samples_split;
self
}
#[must_use]
pub fn with_min_samples_leaf(mut self, min_samples_leaf: usize) -> Self {
self.min_samples_leaf = min_samples_leaf;
self
}
#[must_use]
pub fn with_max_features(mut self, max_features: MaxFeatures) -> Self {
self.max_features = max_features;
self
}
#[must_use]
pub fn with_bootstrap(mut self, bootstrap: bool) -> Self {
self.bootstrap = bootstrap;
self
}
#[must_use]
pub fn with_random_state(mut self, random_state: u64) -> Self {
self.random_state = random_state;
self
}
#[must_use]
pub fn with_n_jobs(mut self, n_jobs: NJobs) -> Self {
self.n_jobs = n_jobs;
self
}
pub const fn n_estimators(&self) -> usize {
self.n_estimators
}
pub const fn max_depth(&self) -> Option<usize> {
self.max_depth
}
pub const fn min_samples_split(&self) -> usize {
self.min_samples_split
}
pub const fn min_samples_leaf(&self) -> usize {
self.min_samples_leaf
}
pub const fn max_features(&self) -> MaxFeatures {
self.max_features
}
pub const fn bootstrap(&self) -> bool {
self.bootstrap
}
pub const fn random_state(&self) -> u64 {
self.random_state
}
pub const fn n_jobs(&self) -> NJobs {
self.n_jobs
}
}
};
}
forest_params!(RandomForestClassifierParams, MaxFeatures::Sqrt);
forest_params!(RandomForestRegressorParams, MaxFeatures::All);