use scirs2_core::ndarray::{Array1, Array2, ArrayView1, ArrayView2};
use sklears_core::error::SklearsError;
use std::collections::HashMap;
pub trait BaselineStrategy: Send + Sync + std::fmt::Debug {
type Config: Clone + std::fmt::Debug;
type FittedData: Clone + std::fmt::Debug;
type Prediction: Clone + std::fmt::Debug;
fn name(&self) -> &'static str;
fn fit(
&self,
config: &Self::Config,
x: &ArrayView2<f64>,
y: &ArrayView1<f64>,
) -> Result<Self::FittedData, SklearsError>;
fn predict(
&self,
fitted_data: &Self::FittedData,
x: &ArrayView2<f64>,
) -> Result<Vec<Self::Prediction>, SklearsError>;
fn validate_config(&self, config: &Self::Config) -> Result<(), SklearsError>;
}
pub trait ClassificationStrategy: BaselineStrategy<Prediction = i32> {
fn predict_proba(
&self,
fitted_data: &Self::FittedData,
x: &ArrayView2<f64>,
) -> Result<Vec<HashMap<i32, f64>>, SklearsError> {
let predictions = self.predict(fitted_data, x)?;
let uniform_proba = predictions
.iter()
.map(|&pred| [(pred, 1.0)].iter().cloned().collect())
.collect();
Ok(uniform_proba)
}
fn decision_function(
&self,
_fitted_data: &Self::FittedData,
x: &ArrayView2<f64>,
) -> Result<Vec<f64>, SklearsError> {
Ok(vec![0.0; x.nrows()])
}
}
pub trait RegressionStrategy: BaselineStrategy<Prediction = f64> {
fn predict_interval(
&self,
fitted_data: &Self::FittedData,
x: &ArrayView2<f64>,
_confidence: f64,
) -> Result<Vec<(f64, f64)>, SklearsError> {
let predictions = self.predict(fitted_data, x)?;
let intervals = predictions.iter().map(|&pred| (pred, pred)).collect();
Ok(intervals)
}
}
#[derive(Debug, Clone)]
pub struct MostFrequentConfig {
pub random_state: Option<u64>,
}
#[derive(Debug, Clone)]
pub struct MostFrequentFittedData {
pub most_frequent_class: i32,
pub class_counts: HashMap<i32, usize>,
pub class_priors: HashMap<i32, f64>,
}
#[derive(Debug, Clone)]
pub struct MostFrequentStrategy;
impl BaselineStrategy for MostFrequentStrategy {
type Config = MostFrequentConfig;
type FittedData = MostFrequentFittedData;
type Prediction = i32;
fn name(&self) -> &'static str {
"most_frequent"
}
fn fit(
&self,
config: &Self::Config,
_x: &ArrayView2<f64>,
y: &ArrayView1<f64>,
) -> Result<Self::FittedData, SklearsError> {
self.validate_config(config)?;
let mut class_counts = HashMap::new();
let n_samples = y.len();
for &value in y.iter() {
let class = value as i32;
*class_counts.entry(class).or_insert(0) += 1;
}
if class_counts.is_empty() {
return Err(SklearsError::InvalidInput("No classes found".to_string()));
}
let most_frequent_class = class_counts
.iter()
.max_by_key(|(_, &count)| count)
.map(|(&class, _)| class)
.expect("operation should succeed");
let class_priors = class_counts
.iter()
.map(|(&class, &count)| (class, count as f64 / n_samples as f64))
.collect();
Ok(MostFrequentFittedData {
most_frequent_class,
class_counts,
class_priors,
})
}
fn predict(
&self,
fitted_data: &Self::FittedData,
x: &ArrayView2<f64>,
) -> Result<Vec<Self::Prediction>, SklearsError> {
Ok(vec![fitted_data.most_frequent_class; x.nrows()])
}
fn validate_config(&self, _config: &Self::Config) -> Result<(), SklearsError> {
Ok(())
}
}
impl ClassificationStrategy for MostFrequentStrategy {
fn predict_proba(
&self,
fitted_data: &Self::FittedData,
x: &ArrayView2<f64>,
) -> Result<Vec<HashMap<i32, f64>>, SklearsError> {
let probabilities = vec![fitted_data.class_priors.clone(); x.nrows()];
Ok(probabilities)
}
}
#[derive(Debug, Clone)]
pub struct MeanConfig {
pub random_state: Option<u64>,
}
#[derive(Debug, Clone)]
pub struct MeanFittedData {
pub target_mean: f64,
pub target_std: f64,
pub n_samples: usize,
}
#[derive(Debug, Clone)]
pub struct MeanStrategy;
impl BaselineStrategy for MeanStrategy {
type Config = MeanConfig;
type FittedData = MeanFittedData;
type Prediction = f64;
fn name(&self) -> &'static str {
"mean"
}
fn fit(
&self,
config: &Self::Config,
_x: &ArrayView2<f64>,
y: &ArrayView1<f64>,
) -> Result<Self::FittedData, SklearsError> {
self.validate_config(config)?;
if y.is_empty() {
return Err(SklearsError::InvalidInput("Empty target array".to_string()));
}
let n_samples = y.len();
let target_mean = y.iter().sum::<f64>() / n_samples as f64;
let target_std = if n_samples > 1 {
let variance = y
.iter()
.map(|&value| (value - target_mean).powi(2))
.sum::<f64>()
/ (n_samples - 1) as f64;
variance.sqrt()
} else {
0.0
};
Ok(MeanFittedData {
target_mean,
target_std,
n_samples,
})
}
fn predict(
&self,
fitted_data: &Self::FittedData,
x: &ArrayView2<f64>,
) -> Result<Vec<Self::Prediction>, SklearsError> {
Ok(vec![fitted_data.target_mean; x.nrows()])
}
fn validate_config(&self, _config: &Self::Config) -> Result<(), SklearsError> {
Ok(())
}
}
impl RegressionStrategy for MeanStrategy {
fn predict_interval(
&self,
fitted_data: &Self::FittedData,
x: &ArrayView2<f64>,
confidence: f64,
) -> Result<Vec<(f64, f64)>, SklearsError> {
if !(0.0..=1.0).contains(&confidence) {
return Err(SklearsError::InvalidInput(
"Confidence must be between 0 and 1".to_string(),
));
}
let z_score = if confidence >= 0.99 {
2.576
} else if confidence >= 0.95 {
1.96
} else {
1.0
};
let margin = z_score * fitted_data.target_std;
let lower = fitted_data.target_mean - margin;
let upper = fitted_data.target_mean + margin;
Ok(vec![(lower, upper); x.nrows()])
}
}
pub struct StrategyRegistry {
classification_strategies: Vec<String>,
regression_strategies: Vec<String>,
}
impl Default for StrategyRegistry {
fn default() -> Self {
Self::new()
}
}
impl StrategyRegistry {
pub fn new() -> Self {
Self {
classification_strategies: vec!["most_frequent".to_string()],
regression_strategies: vec!["mean".to_string()],
}
}
pub fn list_classification_strategies(&self) -> Vec<String> {
self.classification_strategies.clone()
}
pub fn list_regression_strategies(&self) -> Vec<String> {
self.regression_strategies.clone()
}
}
pub struct PredictionPipeline<S: BaselineStrategy + Clone> {
strategy: S,
preprocessors: Vec<Box<dyn Preprocessor>>,
postprocessors: Vec<Box<dyn Postprocessor<S::Prediction>>>,
}
impl<S: BaselineStrategy + Clone> PredictionPipeline<S> {
pub fn new(strategy: S) -> Self {
Self {
strategy,
preprocessors: Vec::new(),
postprocessors: Vec::new(),
}
}
pub fn with_preprocessor(mut self, preprocessor: Box<dyn Preprocessor>) -> Self {
self.preprocessors.push(preprocessor);
self
}
pub fn with_postprocessor(
mut self,
postprocessor: Box<dyn Postprocessor<S::Prediction>>,
) -> Self {
self.postprocessors.push(postprocessor);
self
}
pub fn fit(
&self,
config: &S::Config,
x: &ArrayView2<f64>,
y: &ArrayView1<f64>,
) -> Result<FittedPipeline<S>, SklearsError> {
let mut processed_x = x.to_owned();
let mut processed_y = y.to_owned();
for preprocessor in &self.preprocessors {
let (new_x, new_y) =
preprocessor.transform(&processed_x.view(), &processed_y.view())?;
processed_x = new_x;
processed_y = new_y;
}
let fitted_data = self
.strategy
.fit(config, &processed_x.view(), &processed_y.view())?;
Ok(FittedPipeline {
strategy: self.strategy.clone(),
fitted_data,
preprocessors: Vec::new(), postprocessors: Vec::new(), })
}
}
pub struct FittedPipeline<S: BaselineStrategy + Clone> {
strategy: S,
fitted_data: S::FittedData,
preprocessors: Vec<Box<dyn Preprocessor>>,
postprocessors: Vec<Box<dyn Postprocessor<S::Prediction>>>,
}
impl<S: BaselineStrategy + Clone> FittedPipeline<S> {
pub fn predict(&self, x: &ArrayView2<f64>) -> Result<Vec<S::Prediction>, SklearsError> {
let mut processed_x = x.to_owned();
for preprocessor in &self.preprocessors {
let (new_x, _) =
preprocessor.transform(&processed_x.view(), &ArrayView1::from(&[0.0][..]))?;
processed_x = new_x;
}
let mut predictions = self
.strategy
.predict(&self.fitted_data, &processed_x.view())?;
for postprocessor in &self.postprocessors {
predictions = postprocessor.transform(&predictions)?;
}
Ok(predictions)
}
}
pub trait Preprocessor: Send + Sync + std::fmt::Debug {
fn transform(
&self,
x: &ArrayView2<f64>,
y: &ArrayView1<f64>,
) -> Result<(Array2<f64>, Array1<f64>), SklearsError>;
}
pub trait Postprocessor<T>: Send + Sync + std::fmt::Debug {
fn transform(&self, predictions: &[T]) -> Result<Vec<T>, SklearsError>;
}
#[derive(Debug, Clone)]
pub struct StandardScaler {
mean: Vec<f64>,
std: Vec<f64>,
fitted: bool,
}
impl Default for StandardScaler {
fn default() -> Self {
Self::new()
}
}
impl StandardScaler {
pub fn new() -> Self {
Self {
mean: Vec::new(),
std: Vec::new(),
fitted: false,
}
}
pub fn fit(&mut self, x: &ArrayView2<f64>) -> Result<(), SklearsError> {
let n_features = x.ncols();
let n_samples = x.nrows();
if n_samples == 0 {
return Err(SklearsError::InvalidInput("Empty input array".to_string()));
}
self.mean = vec![0.0; n_features];
self.std = vec![1.0; n_features];
for j in 0..n_features {
self.mean[j] = x.column(j).iter().sum::<f64>() / n_samples as f64;
}
if n_samples > 1 {
for j in 0..n_features {
let variance = x
.column(j)
.iter()
.map(|&value| (value - self.mean[j]).powi(2))
.sum::<f64>()
/ (n_samples - 1) as f64;
self.std[j] = variance.sqrt().max(1e-8); }
}
self.fitted = true;
Ok(())
}
pub fn transform(&self, x: &ArrayView2<f64>) -> Result<Array2<f64>, SklearsError> {
if !self.fitted {
return Err(SklearsError::InvalidInput("Scaler not fitted".to_string()));
}
let mut result = Array2::zeros(x.raw_dim());
for (i, row) in x.outer_iter().enumerate() {
for (j, &value) in row.iter().enumerate() {
result[[i, j]] = (value - self.mean[j]) / self.std[j];
}
}
Ok(result)
}
}
impl Preprocessor for StandardScaler {
fn transform(
&self,
x: &ArrayView2<f64>,
y: &ArrayView1<f64>,
) -> Result<(Array2<f64>, Array1<f64>), SklearsError> {
let transformed_x = self.transform(x)?;
Ok((transformed_x, y.to_owned()))
}
}
#[derive(Debug, Clone)]
pub struct ClippingPostprocessor {
min_value: f64,
max_value: f64,
}
impl ClippingPostprocessor {
pub fn new(min_value: f64, max_value: f64) -> Self {
Self {
min_value,
max_value,
}
}
}
impl Postprocessor<f64> for ClippingPostprocessor {
fn transform(&self, predictions: &[f64]) -> Result<Vec<f64>, SklearsError> {
let clipped = predictions
.iter()
.map(|&pred| pred.max(self.min_value).min(self.max_value))
.collect();
Ok(clipped)
}
}
pub mod statistical_methods {
use super::*;
pub trait StatisticalEstimator: Send + Sync + std::fmt::Debug {
type Input: ?Sized;
type Output;
fn estimate(&self, data: &Self::Input) -> Result<Self::Output, SklearsError>;
}
#[derive(Debug, Clone)]
pub struct TrimmedMeanEstimator {
trim_percentage: f64,
}
impl TrimmedMeanEstimator {
pub fn new(trim_percentage: f64) -> Result<Self, SklearsError> {
if !(0.0..=0.5).contains(&trim_percentage) {
return Err(SklearsError::InvalidInput(
"Trim percentage must be between 0 and 0.5".to_string(),
));
}
Ok(Self { trim_percentage })
}
}
impl StatisticalEstimator for TrimmedMeanEstimator {
type Input = [f64];
type Output = f64;
fn estimate(&self, data: &Self::Input) -> Result<Self::Output, SklearsError> {
if data.is_empty() {
return Err(SklearsError::InvalidInput("Empty data array".to_string()));
}
let mut sorted_data = data.to_vec();
sorted_data.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
let n = sorted_data.len();
let trim_count = (n as f64 * self.trim_percentage).floor() as usize;
if trim_count * 2 >= n {
return Ok(sorted_data[n / 2]);
}
let trimmed_data = &sorted_data[trim_count..n - trim_count];
let mean = trimmed_data.iter().sum::<f64>() / trimmed_data.len() as f64;
Ok(mean)
}
}
#[derive(Debug, Clone)]
pub struct MedianAbsoluteDeviationEstimator;
impl StatisticalEstimator for MedianAbsoluteDeviationEstimator {
type Input = [f64];
type Output = f64;
fn estimate(&self, data: &Self::Input) -> Result<Self::Output, SklearsError> {
if data.is_empty() {
return Err(SklearsError::InvalidInput("Empty data array".to_string()));
}
let mut sorted_data = data.to_vec();
sorted_data.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
let n = sorted_data.len();
let median = if n % 2 == 0 {
(sorted_data[n / 2 - 1] + sorted_data[n / 2]) / 2.0
} else {
sorted_data[n / 2]
};
let deviations: Vec<f64> = sorted_data.iter().map(|&x| (x - median).abs()).collect();
let mut sorted_deviations = deviations;
sorted_deviations.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
let mad = if n % 2 == 0 {
(sorted_deviations[n / 2 - 1] + sorted_deviations[n / 2]) / 2.0
} else {
sorted_deviations[n / 2]
};
Ok(mad)
}
}
#[derive(Debug, Clone)]
pub struct QuantileEstimator {
quantile: f64,
}
impl QuantileEstimator {
pub fn new(quantile: f64) -> Result<Self, SklearsError> {
if !(0.0..=1.0).contains(&quantile) {
return Err(SklearsError::InvalidInput(
"Quantile must be between 0 and 1".to_string(),
));
}
Ok(Self { quantile })
}
}
impl StatisticalEstimator for QuantileEstimator {
type Input = [f64];
type Output = f64;
fn estimate(&self, data: &Self::Input) -> Result<Self::Output, SklearsError> {
if data.is_empty() {
return Err(SklearsError::InvalidInput("Empty data array".to_string()));
}
let mut sorted_data = data.to_vec();
sorted_data.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
let n = sorted_data.len();
let index = (self.quantile * (n - 1) as f64).floor() as usize;
let fraction = self.quantile * (n - 1) as f64 - index as f64;
let quantile_value = if index >= n - 1 {
sorted_data[n - 1]
} else {
sorted_data[index] + fraction * (sorted_data[index + 1] - sorted_data[index])
};
Ok(quantile_value)
}
}
}
pub struct BaselineStrategyFactory;
impl BaselineStrategyFactory {
pub fn most_frequent() -> MostFrequentStrategy {
MostFrequentStrategy
}
pub fn mean() -> MeanStrategy {
MeanStrategy
}
pub fn standard_pipeline<S: BaselineStrategy + Clone>(strategy: S) -> PredictionPipeline<S> {
PredictionPipeline::new(strategy).with_preprocessor(Box::new(StandardScaler::new()))
}
pub fn robust_regression_pipeline() -> PredictionPipeline<MeanStrategy> {
PredictionPipeline::new(MeanStrategy)
.with_preprocessor(Box::new(StandardScaler::new()))
.with_postprocessor(Box::new(ClippingPostprocessor::new(-1e6, 1e6)))
}
}
#[allow(non_snake_case)]
#[cfg(test)]
mod tests {
use super::statistical_methods::StatisticalEstimator;
use super::*;
use scirs2_core::ndarray::array;
#[test]
fn test_most_frequent_strategy() {
let strategy = MostFrequentStrategy;
let config = MostFrequentConfig {
random_state: Some(42),
};
let x = Array2::from_shape_vec((4, 2), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0])
.expect("shape and data length should match");
let y = array![0.0, 1.0, 1.0, 0.0];
let fitted = strategy
.fit(&config, &x.view(), &y.view())
.expect("model fitting should succeed");
assert!(fitted.class_counts.contains_key(&0));
assert!(fitted.class_counts.contains_key(&1));
let predictions = strategy
.predict(&fitted, &x.view())
.expect("prediction should succeed");
assert_eq!(predictions.len(), 4);
assert!(predictions.iter().all(|&p| p == 0 || p == 1));
}
#[test]
fn test_mean_strategy() {
let strategy = MeanStrategy;
let config = MeanConfig {
random_state: Some(42),
};
let x = Array2::from_shape_vec((4, 2), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0])
.expect("shape and data length should match");
let y = array![1.0, 2.0, 3.0, 4.0];
let fitted = strategy
.fit(&config, &x.view(), &y.view())
.expect("model fitting should succeed");
assert_eq!(fitted.target_mean, 2.5);
let predictions = strategy
.predict(&fitted, &x.view())
.expect("prediction should succeed");
assert_eq!(predictions.len(), 4);
assert!(predictions.iter().all(|&p| p == 2.5));
}
#[test]
fn test_prediction_pipeline() {
let strategy = MeanStrategy;
let config = MeanConfig {
random_state: Some(42),
};
let pipeline = PredictionPipeline::new(strategy)
.with_postprocessor(Box::new(ClippingPostprocessor::new(0.0, 10.0)));
let x = Array2::from_shape_vec((4, 2), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0])
.expect("shape and data length should match");
let y = array![1.0, 2.0, 3.0, 4.0];
let fitted_pipeline = pipeline
.fit(&config, &x.view(), &y.view())
.expect("model fitting should succeed");
let predictions = fitted_pipeline
.predict(&x.view())
.expect("prediction should succeed");
assert_eq!(predictions.len(), 4);
assert!(predictions.iter().all(|&p| (0.0..=10.0).contains(&p)));
}
#[test]
fn test_trimmed_mean_estimator() {
let estimator =
statistical_methods::TrimmedMeanEstimator::new(0.1).expect("operation should succeed");
let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 100.0];
let result = estimator.estimate(&data).expect("operation should succeed");
assert!(result > 0.0 && result < 50.0); }
#[test]
fn test_mad_estimator() {
let estimator = statistical_methods::MedianAbsoluteDeviationEstimator;
let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
let result = estimator.estimate(&data).expect("operation should succeed");
assert!(result > 0.0);
}
#[test]
fn test_quantile_estimator() {
let estimator =
statistical_methods::QuantileEstimator::new(0.5).expect("operation should succeed"); let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
let result = estimator.estimate(&data).expect("operation should succeed");
assert_eq!(result, 3.0);
}
#[test]
fn test_factory_methods() {
let most_frequent = BaselineStrategyFactory::most_frequent();
assert_eq!(most_frequent.name(), "most_frequent");
let mean = BaselineStrategyFactory::mean();
assert_eq!(mean.name(), "mean");
let pipeline = BaselineStrategyFactory::standard_pipeline(mean);
assert_eq!(pipeline.strategy.name(), "mean");
}
#[test]
fn test_standard_scaler() {
let mut scaler = StandardScaler::new();
let x = Array2::from_shape_vec((4, 2), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0])
.expect("shape and data length should match");
scaler.fit(&x.view()).expect("model fitting should succeed");
let transformed = scaler
.transform(&x.view())
.expect("transformation should succeed");
assert_eq!(transformed.shape(), x.shape());
for j in 0..transformed.ncols() {
let col_mean = transformed.column(j).iter().sum::<f64>() / transformed.nrows() as f64;
assert!((col_mean).abs() < 1e-10); }
}
#[test]
fn test_clipping_postprocessor() {
let clipper = ClippingPostprocessor::new(-1.0, 1.0);
let predictions = vec![-2.0, -0.5, 0.0, 0.5, 2.0];
let clipped = clipper
.transform(&predictions)
.expect("transformation should succeed");
assert_eq!(clipped, vec![-1.0, -0.5, 0.0, 0.5, 1.0]);
}
}