use crate::{DType, Error, Matrix, Result, matrix};
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct RegressionErrors {
absolute_sum: f64,
squared_sum: f64,
samples: u64,
}
impl RegressionErrors {
#[inline]
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn update(&mut self, absolute_sum: f64, squared_sum: f64, samples: u64) {
self.absolute_sum += absolute_sum;
self.squared_sum += squared_sum;
self.samples = self.samples.saturating_add(samples);
}
pub fn update_device(&mut self, prediction: &Matrix, target: &Matrix) -> Result<()> {
if prediction.shape() != target.shape()
|| prediction.dtype() != DType::F32
|| target.dtype() != DType::F32
{
return Err(Error::invalid_argument(
"regression metrics require same-shape F32 predictions and targets",
));
}
if !prediction.runtime().same_as(target.runtime()) {
return Err(Error::invalid_argument(
"regression metric inputs must belong to the same runtime",
));
}
if prediction.num_elements() == 0 {
return Err(Error::invalid_argument(
"regression metrics require nonempty batches",
));
}
let difference = matrix::sub(prediction, target)?;
let absolute = matrix::sum(&matrix::abs(&difference)?, -1)?;
let squared = matrix::sum(&matrix::mul(&difference, &difference)?, -1)?;
let pair = matrix::concat(&[absolute, squared], 0)?.read_f32()?;
self.update(
f64::from(pair[0]),
f64::from(pair[1]),
prediction.num_elements() as u64,
);
Ok(())
}
pub fn merge(&mut self, other: &Self) {
self.absolute_sum += other.absolute_sum;
self.squared_sum += other.squared_sum;
self.samples = self.samples.saturating_add(other.samples);
}
#[must_use]
pub fn mae(&self) -> f64 {
if self.samples == 0 {
f64::NAN
} else {
self.absolute_sum / self.samples as f64
}
}
#[must_use]
pub fn rmse(&self) -> f64 {
if self.samples == 0 {
f64::NAN
} else {
(self.squared_sum / self.samples as f64).sqrt()
}
}
#[must_use]
pub const fn samples(&self) -> u64 {
self.samples
}
pub fn reset(&mut self) {
*self = Self::default();
}
}