use scirs2_core::ndarray::Array1;
use scirs2_core::random::{rngs::StdRng, thread_rng, RngExt, SeedableRng};
use sklears_core::error::{Result, SklearsError};
use sklears_core::traits::{Estimator, Fit, Predict, Trained, Untrained};
use sklears_core::types::{Features, Float};
use std::marker::PhantomData;
#[derive(Debug, Clone, PartialEq, Copy)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Strategy {
Mean,
Constant(f64),
Median,
Uniform,
Normal { mean: Option<f64>, std: Option<f64> },
Quantile(f64),
Auto,
SeasonalNaive(usize),
}
#[derive(Debug, Clone)]
#[allow(dead_code)] pub struct DummyRegressor<State = Untrained> {
pub strategy: Strategy,
pub random_state: Option<u64>,
pub(crate) fitted_value_: Option<f64>,
pub(crate) fitted_std_: Option<f64>,
pub(crate) n_samples_: Option<usize>,
_state: PhantomData<State>,
}
pub type DummyRegressorTrained = DummyRegressor<Trained>;
#[derive(Debug, Clone)]
#[allow(dead_code)] pub struct DummyRegressorFitted {
strategy: Strategy,
fitted_value: f64,
fitted_std: Option<f64>,
n_samples: usize,
random_state: Option<u64>,
}
impl DummyRegressor<Untrained> {
pub fn new(strategy: Strategy) -> Self {
Self {
strategy,
random_state: None,
fitted_value_: None,
fitted_std_: None,
n_samples_: None,
_state: PhantomData,
}
}
pub fn with_random_state(mut self, random_state: u64) -> Self {
self.random_state = Some(random_state);
self
}
pub fn with_constant(mut self, constant: f64) -> Self {
self.strategy = Strategy::Constant(constant);
self
}
}
impl Estimator for DummyRegressor<Untrained> {
type Config = ();
type Error = SklearsError;
type Float = Float;
fn config(&self) -> &Self::Config {
&()
}
}
impl Fit<Features, Array1<Float>> for DummyRegressor<Untrained> {
type Fitted = DummyRegressor<Trained>;
fn fit(self, _x: &Features, y: &Array1<Float>) -> Result<DummyRegressor<Trained>> {
if y.is_empty() {
return Err(SklearsError::InvalidInput("Empty target array".to_string()));
}
let n_samples = y.len();
let fitted_value = match &self.strategy {
Strategy::Mean => y.iter().sum::<f64>() / n_samples as f64,
Strategy::Constant(value) => *value,
Strategy::Median => {
let mut sorted = y.to_vec();
sorted.sort_by(|a, b| a.partial_cmp(b).expect("operation should succeed"));
if sorted.len().is_multiple_of(2) {
(sorted[sorted.len() / 2 - 1] + sorted[sorted.len() / 2]) / 2.0
} else {
sorted[sorted.len() / 2]
}
}
Strategy::Uniform => {
let min_val = y.iter().fold(f64::INFINITY, |a, &b| a.min(b));
let max_val = y.iter().fold(f64::NEG_INFINITY, |a, &b| a.max(b));
(min_val + max_val) / 2.0 }
Strategy::Normal { mean, std: _ } => {
mean.unwrap_or_else(|| y.iter().sum::<f64>() / n_samples as f64)
}
Strategy::Quantile(q) => {
let mut sorted = y.to_vec();
sorted.sort_by(|a, b| a.partial_cmp(b).expect("operation should succeed"));
let index =
((*q * (sorted.len() - 1) as f64).round() as usize).min(sorted.len() - 1);
sorted[index]
}
Strategy::Auto => {
let mut sorted = y.to_vec();
sorted.sort_by(|a, b| a.partial_cmp(b).expect("operation should succeed"));
if sorted.len().is_multiple_of(2) {
(sorted[sorted.len() / 2 - 1] + sorted[sorted.len() / 2]) / 2.0
} else {
sorted[sorted.len() / 2]
}
}
Strategy::SeasonalNaive(_period) => {
y.iter().sum::<f64>() / n_samples as f64
}
};
let fitted_std = if n_samples > 1 {
let mean = fitted_value;
let variance =
y.iter().map(|&x| (x - mean).powi(2)).sum::<f64>() / (n_samples - 1) as f64;
Some(variance.sqrt())
} else {
None
};
Ok(DummyRegressor {
strategy: self.strategy,
random_state: self.random_state,
fitted_value_: Some(fitted_value),
fitted_std_: fitted_std,
n_samples_: Some(n_samples),
_state: PhantomData::<Trained>,
})
}
}
impl Predict<Features, Array1<Float>> for DummyRegressor<Trained> {
fn predict(&self, x: &Features) -> Result<Array1<Float>> {
let n_samples = x.nrows();
let fitted_value = self.fitted_value_.expect("operation should succeed");
let fitted_std = self.fitted_std_;
let predictions = match &self.strategy {
Strategy::Mean
| Strategy::Constant(_)
| Strategy::Median
| Strategy::Quantile(_)
| Strategy::Auto
| Strategy::SeasonalNaive(_) => Array1::from_elem(n_samples, fitted_value),
Strategy::Uniform => {
let predictions: Vec<f64> = if let Some(seed) = self.random_state {
let mut rng = StdRng::seed_from_u64(seed);
(0..n_samples)
.map(|_| {
fitted_value + rng.random_range(-1.0..1.0) * fitted_std.unwrap_or(1.0)
})
.collect()
} else {
let mut rng = thread_rng();
(0..n_samples)
.map(|_| {
fitted_value + rng.random_range(-1.0..1.0) * fitted_std.unwrap_or(1.0)
})
.collect()
};
Array1::from_vec(predictions)
}
Strategy::Normal { mean: _, std } => {
let std_val = std.unwrap_or_else(|| fitted_std.unwrap_or(1.0));
let predictions: Vec<f64> = if let Some(seed) = self.random_state {
let mut rng = StdRng::seed_from_u64(seed);
(0..n_samples)
.map(|_| fitted_value + rng.random_range(-2.0..2.0) * std_val) .collect()
} else {
let mut rng = thread_rng();
(0..n_samples)
.map(|_| fitted_value + rng.random_range(-2.0..2.0) * std_val) .collect()
};
Array1::from_vec(predictions)
}
};
Ok(predictions)
}
}
pub trait PredictConfidenceInterval<T> {
fn predict_interval(&self, x: &T, confidence: f64) -> Result<Vec<(f64, f64)>>;
}
pub trait ProbabilisticRegression<T> {
fn predict_distribution(&self, x: &T) -> Result<Vec<(f64, f64)>>;
}
impl PredictConfidenceInterval<Features> for DummyRegressorFitted {
fn predict_interval(&self, x: &Features, confidence: f64) -> Result<Vec<(f64, f64)>> {
if !(0.0..=1.0).contains(&confidence) {
return Err(SklearsError::InvalidInput(
"Confidence must be between 0 and 1".to_string(),
));
}
let n_samples = x.nrows();
let z_score = if confidence >= 0.99 {
2.576
} else if confidence >= 0.95 {
1.96
} else {
1.0
};
let margin = z_score * self.fitted_std.unwrap_or(1.0);
let lower = self.fitted_value - margin;
let upper = self.fitted_value + margin;
Ok(vec![(lower, upper); n_samples])
}
}
impl ProbabilisticRegression<Features> for DummyRegressorFitted {
fn predict_distribution(&self, x: &Features) -> Result<Vec<(f64, f64)>> {
let n_samples = x.nrows();
let mean = self.fitted_value;
let variance = self.fitted_std.unwrap_or(1.0).powi(2);
Ok(vec![(mean, variance); n_samples])
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum SeasonalAdjustmentMethod {
Additive,
Multiplicative,
}
#[derive(Debug, Clone, PartialEq)]
pub enum SeasonalType {
Additive,
Multiplicative,
}
#[derive(Debug, Clone, PartialEq)]
pub enum DecompositionMethod {
Classical,
STL,
X11,
}
#[derive(Debug, Clone, PartialEq)]
pub enum CyclicalMethod {
Fourier,
Wavelet,
Spectral,
}