Skip to content

Commit 754aa20

Browse files
authored
Add Mean Absolute Error Loss (#587)
1 parent 59ca8dc commit 754aa20

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
//! # Mean Absolute Error Loss Function
2+
//!
3+
//! The `mae_loss` function calculates the Mean Absolute Error loss, which is a
4+
//! robust loss function used in machine learning.
5+
//!
6+
//! ## Formula
7+
//!
8+
//! For a pair of actual and predicted values, represented as vectors `actual`
9+
//! and `predicted`, the Mean Absolute loss is calculated as:
10+
//!
11+
//! - loss = `(actual - predicted) / n_elements`.
12+
//!
13+
//! It returns the average loss by dividing the `total_loss` by total no. of
14+
//! elements.
15+
//!
16+
pub fn mae_loss(predicted: &Vec<f64>, actual: &[f64]) -> f64 {
17+
let mut total_loss: f64 = 0.0;
18+
for (p, a) in predicted.iter().zip(actual.iter()) {
19+
let diff: f64 = p - a;
20+
let absolute_diff: f64 = diff.abs();
21+
total_loss += absolute_diff;
22+
}
23+
total_loss / (predicted.len() as f64)
24+
}
25+
26+
#[cfg(test)]
27+
mod tests {
28+
use super::*;
29+
30+
#[test]
31+
fn test_mae_loss() {
32+
let predicted_values: Vec<f64> = vec![1.0, 2.0, 3.0, 4.0];
33+
let actual_values: Vec<f64> = vec![1.0, 3.0, 3.5, 4.5];
34+
assert_eq!(mae_loss(&predicted_values, &actual_values), 0.5);
35+
}
36+
}
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
mod mae_loss;
12
mod mse_loss;
23

4+
pub use self::mae_loss::mae_loss;
35
pub use self::mse_loss::mse_loss;

src/machine_learning/mod.rs

+3
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,8 @@ mod loss_function;
33
mod optimization;
44

55
pub use self::linear_regression::linear_regression;
6+
7+
pub use self::loss_function::mae_loss;
68
pub use self::loss_function::mse_loss;
9+
710
pub use self::optimization::gradient_descent;

0 commit comments

Comments
 (0)