File tree 3 files changed +41
-0
lines changed
3 files changed +41
-0
lines changed Original file line number Diff line number Diff line change
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 number Diff line number Diff line change
1
+ mod mae_loss;
1
2
mod mse_loss;
2
3
4
+ pub use self :: mae_loss:: mae_loss;
3
5
pub use self :: mse_loss:: mse_loss;
Original file line number Diff line number Diff line change @@ -3,5 +3,8 @@ mod loss_function;
3
3
mod optimization;
4
4
5
5
pub use self :: linear_regression:: linear_regression;
6
+
7
+ pub use self :: loss_function:: mae_loss;
6
8
pub use self :: loss_function:: mse_loss;
9
+
7
10
pub use self :: optimization:: gradient_descent;
You can’t perform that action at this time.
0 commit comments