scirs2-metrics 0.3.2

Machine Learning evaluation metrics module for SciRS2 (scirs2-metrics)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
//! Error metrics for regression models
//!
//! This module provides functions for calculating error metrics between
//! predicted values and true values in regression models.

use scirs2_core::ndarray::{ArrayBase, ArrayView1, Data, Dimension};
use scirs2_core::numeric::{Float, FromPrimitive, NumCast};
use scirs2_core::simd_ops::SimdUnifiedOps;
use std::cmp::Ordering;

use super::check_sameshape;
use crate::error::{MetricsError, Result};

/// Calculates the mean squared error (MSE)
///
/// # Mathematical Formulation
///
/// Mean Squared Error is defined as:
///
/// ```text
/// MSE = (1/n) * Σ(yᵢ - ŷᵢ)²
/// ```
///
/// Where:
/// - n = number of samples
/// - yᵢ = true value for sample i
/// - ŷᵢ = predicted value for sample i
/// - Σ = sum over all samples
///
/// # Properties
///
/// - MSE is always non-negative (≥ 0)
/// - MSE = 0 indicates perfect predictions
/// - MSE penalizes larger errors more heavily due to squaring
/// - Units: squared units of the target variable
/// - Differentiable everywhere (useful for optimization)
///
/// # Interpretation
///
/// MSE measures the average squared difference between predicted and actual values:
/// - Lower MSE indicates better model performance
/// - Sensitive to outliers due to squaring of errors
/// - Large errors contribute disproportionately to the total error
///
/// # Relationship to Other Metrics
///
/// - RMSE = √MSE (same units as target variable)
/// - MAE typically ≤ RMSE, with equality when all errors are equal
/// - MSE is the expected value of squared error in probabilistic terms
///
/// # Use Cases
///
/// MSE is widely used because:
/// - It's differentiable (good for gradient-based optimization)
/// - It heavily penalizes large errors
/// - It's the basis for ordinary least squares regression
/// - It corresponds to Gaussian likelihood in probabilistic models
///
/// # Arguments
///
/// * `y_true` - Ground truth (correct) target values
/// * `y_pred` - Estimated target values
///
/// # Returns
///
/// * The mean squared error
///
/// # Examples
///
/// ```no_run
/// use scirs2_core::ndarray::array;
/// use scirs2_metrics::regression::mean_squared_error;
///
/// let y_true = array![3.0, -0.5, 2.0, 7.0];
/// let y_pred = array![2.5, 0.0, 2.0, 8.0];
///
/// let mse: f64 = mean_squared_error(&y_true, &y_pred).expect("Operation failed");
/// // Expecting: ((3.0-2.5)² + (-0.5-0.0)² + (2.0-2.0)² + (7.0-8.0)²) / 4
/// assert!(mse < 0.38 && mse > 0.37);
/// ```
#[allow(dead_code)]
pub fn mean_squared_error<F, S1, S2, D1, D2>(
    y_true: &ArrayBase<S1, D1>,
    y_pred: &ArrayBase<S2, D2>,
) -> Result<F>
where
    F: Float + NumCast + std::fmt::Debug + scirs2_core::simd_ops::SimdUnifiedOps,
    S1: Data<Elem = F>,
    S2: Data<Elem = F>,
    D1: Dimension,
    D2: Dimension,
{
    // Check that arrays have the same shape
    check_sameshape::<F, S1, S2, D1, D2>(y_true, y_pred)?;

    let n_samples = y_true.len();

    // Use SIMD optimizations for vector operations when data is contiguous
    let squared_error_sum = if y_true.is_standard_layout() && y_pred.is_standard_layout() {
        // SIMD-optimized computation - convert to 1D views for SIMD _ops
        let y_true_view = y_true.view();
        let y_pred_view = y_pred.view();
        let y_true_reshaped = y_true_view
            .to_shape(y_true.len())
            .expect("Operation failed");
        let y_pred_reshaped = y_pred_view
            .to_shape(y_pred.len())
            .expect("Operation failed");
        let y_true_1d = y_true_reshaped.view();
        let y_pred_1d = y_pred_reshaped.view();
        let diff = F::simd_sub(&y_true_1d, &y_pred_1d);
        let squared_diff = F::simd_mul(&diff.view(), &diff.view());
        F::simd_sum(&squared_diff.view())
    } else {
        // Fallback for non-contiguous arrays
        let mut sum = F::zero();
        for (yt, yp) in y_true.iter().zip(y_pred.iter()) {
            let error = *yt - *yp;
            sum = sum + error * error;
        }
        sum
    };

    Ok(squared_error_sum / NumCast::from(n_samples).expect("Operation failed"))
}

/// Calculates the root mean squared error (RMSE)
///
/// Root mean squared error is the square root of the mean squared error.
///
/// # Arguments
///
/// * `y_true` - Ground truth (correct) target values
/// * `y_pred` - Estimated target values
///
/// # Returns
///
/// * The root mean squared error
///
/// # Examples
///
/// ```no_run
/// use scirs2_core::ndarray::array;
/// use scirs2_metrics::regression::root_mean_squared_error;
///
/// let y_true = array![3.0, -0.5, 2.0, 7.0];
/// let y_pred = array![2.5, 0.0, 2.0, 8.0];
///
/// let rmse: f64 = root_mean_squared_error(&y_true, &y_pred).expect("Operation failed");
/// // RMSE is the square root of MSE
/// assert!(rmse < 0.62 && rmse > 0.61);
/// ```
#[allow(dead_code)]
pub fn root_mean_squared_error<F, S1, S2, D1, D2>(
    y_true: &ArrayBase<S1, D1>,
    y_pred: &ArrayBase<S2, D2>,
) -> Result<F>
where
    F: Float + NumCast + std::fmt::Debug + scirs2_core::simd_ops::SimdUnifiedOps,
    S1: Data<Elem = F>,
    S2: Data<Elem = F>,
    D1: Dimension,
    D2: Dimension,
{
    let mse = mean_squared_error(y_true, y_pred)?;
    Ok(mse.sqrt())
}

/// Calculates the mean absolute error (MAE)
///
/// Mean absolute error measures the average absolute difference between
/// the estimated values and the actual value.
///
/// # Arguments
///
/// * `y_true` - Ground truth (correct) target values
/// * `y_pred` - Estimated target values
///
/// # Returns
///
/// * The mean absolute error
///
/// # Examples
///
/// ```no_run
/// use scirs2_core::ndarray::array;
/// use scirs2_metrics::regression::mean_absolute_error;
///
/// let y_true = array![3.0, -0.5, 2.0, 7.0];
/// let y_pred = array![2.5, 0.0, 2.0, 8.0];
///
/// let mae: f64 = mean_absolute_error(&y_true, &y_pred).expect("Operation failed");
/// // Expecting: (|3.0-2.5| + |-0.5-0.0| + |2.0-2.0| + |7.0-8.0|) / 4 = 0.5
/// assert!(mae > 0.499 && mae < 0.501);
/// ```
#[allow(dead_code)]
pub fn mean_absolute_error<F, S1, S2, D1, D2>(
    y_true: &ArrayBase<S1, D1>,
    y_pred: &ArrayBase<S2, D2>,
) -> Result<F>
where
    F: Float + NumCast + std::fmt::Debug + scirs2_core::simd_ops::SimdUnifiedOps,
    S1: Data<Elem = F>,
    S2: Data<Elem = F>,
    D1: Dimension,
    D2: Dimension,
{
    // Check that arrays have the same shape
    check_sameshape::<F, S1, S2, D1, D2>(y_true, y_pred)?;

    let n_samples = y_true.len();

    // Use SIMD optimizations for vector operations when data is contiguous
    let abs_error_sum = if y_true.is_standard_layout() && y_pred.is_standard_layout() {
        // SIMD-optimized computation for 1D arrays
        let y_true_view = y_true.view();
        let y_pred_view = y_pred.view();
        let y_true_reshaped = y_true_view
            .to_shape(y_true.len())
            .expect("Operation failed");
        let y_pred_reshaped = y_pred_view
            .to_shape(y_pred.len())
            .expect("Operation failed");
        let y_true_1d = y_true_reshaped.view();
        let y_pred_1d = y_pred_reshaped.view();
        let diff = F::simd_sub(&y_true_1d, &y_pred_1d);
        let abs_diff = F::simd_abs(&diff.view());
        F::simd_sum(&abs_diff.view())
    } else {
        // Fallback for non-contiguous arrays
        let mut sum = F::zero();
        for (yt, yp) in y_true.iter().zip(y_pred.iter()) {
            let error = (*yt - *yp).abs();
            sum = sum + error;
        }
        sum
    };

    Ok(abs_error_sum / NumCast::from(n_samples).expect("Operation failed"))
}

/// Calculates the mean absolute percentage error (MAPE)
///
/// Mean absolute percentage error expresses the difference between true
/// and predicted values as a percentage of the true values.
///
/// # Arguments
///
/// * `y_true` - Ground truth (correct) target values
/// * `y_pred` - Estimated target values
///
/// # Returns
///
/// * The mean absolute percentage error
///
/// # Notes
///
/// MAPE is undefined when true values are zero. This implementation
/// excludes those samples from the calculation.
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_metrics::regression::mean_absolute_percentage_error;
///
/// let y_true = array![3.0, 0.5, 2.0, 7.0];
/// let y_pred = array![2.7, 0.4, 1.8, 7.7];
///
/// let mape = mean_absolute_percentage_error(&y_true, &y_pred).expect("Operation failed");
/// // Example calculation: (|3.0-2.7|/3.0 + |0.5-0.4|/0.5 + |2.0-1.8|/2.0 + |7.0-7.7|/7.0) / 4 * 100
/// assert!(mape < 13.0 && mape > 9.0);
/// ```
#[allow(dead_code)]
pub fn mean_absolute_percentage_error<F, S1, S2, D1, D2>(
    y_true: &ArrayBase<S1, D1>,
    y_pred: &ArrayBase<S2, D2>,
) -> Result<F>
where
    F: Float + NumCast + std::fmt::Debug + scirs2_core::simd_ops::SimdUnifiedOps,
    S1: Data<Elem = F>,
    S2: Data<Elem = F>,
    D1: Dimension,
    D2: Dimension,
{
    // Check that arrays have the same shape
    check_sameshape::<F, S1, S2, D1, D2>(y_true, y_pred)?;

    let mut percentage_error_sum = F::zero();
    let mut valid_samples = 0;

    for (yt, yp) in y_true.iter().zip(y_pred.iter()) {
        if yt.abs() > F::epsilon() {
            let percentage_error = ((*yt - *yp) / *yt).abs();
            percentage_error_sum = percentage_error_sum + percentage_error;
            valid_samples += 1;
        }
    }

    if valid_samples == 0 {
        return Err(MetricsError::InvalidInput(
            "All y_true values are zero. MAPE is undefined.".to_string(),
        ));
    }

    // Multiply by 100 to get percentage
    Ok(
        percentage_error_sum / NumCast::from(valid_samples).expect("Operation failed")
            * NumCast::from(100).expect("Operation failed"),
    )
}

/// Calculates the symmetric mean absolute percentage error (SMAPE)
///
/// SMAPE is an alternative to MAPE that handles zero or near-zero values better.
///
/// # Arguments
///
/// * `y_true` - Ground truth (correct) target values
/// * `y_pred` - Estimated target values
///
/// # Returns
///
/// * The symmetric mean absolute percentage error
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_metrics::regression::symmetric_mean_absolute_percentage_error;
///
/// let y_true = array![3.0, 0.01, 2.0, 7.0];
/// let y_pred = array![2.7, 0.0, 1.8, 7.7];
///
/// let smape = symmetric_mean_absolute_percentage_error(&y_true, &y_pred).expect("Operation failed");
/// assert!(smape > 0.0);
/// ```
#[allow(dead_code)]
pub fn symmetric_mean_absolute_percentage_error<F, S1, S2, D1, D2>(
    y_true: &ArrayBase<S1, D1>,
    y_pred: &ArrayBase<S2, D2>,
) -> Result<F>
where
    F: Float + NumCast + std::fmt::Debug + scirs2_core::simd_ops::SimdUnifiedOps,
    S1: Data<Elem = F>,
    S2: Data<Elem = F>,
    D1: Dimension,
    D2: Dimension,
{
    // Check that arrays have the same shape
    check_sameshape::<F, S1, S2, D1, D2>(y_true, y_pred)?;

    let mut percentage_error_sum = F::zero();
    let mut valid_samples = 0;

    for (yt, yp) in y_true.iter().zip(y_pred.iter()) {
        // Skip samples where both y_true and y_pred are zero to avoid undefined values
        if yt.abs() > F::epsilon() || yp.abs() > F::epsilon() {
            let percentage_error = ((*yt - *yp).abs()) / (yt.abs() + yp.abs());
            percentage_error_sum = percentage_error_sum + percentage_error;
            valid_samples += 1;
        }
    }

    if valid_samples == 0 {
        return Err(MetricsError::InvalidInput(
            "All values are zero. SMAPE is undefined.".to_string(),
        ));
    }

    // Multiply by 200 to get percentage (SMAPE is typically defined with factor of 2)
    Ok(
        percentage_error_sum / NumCast::from(valid_samples).expect("Operation failed")
            * NumCast::from(200).expect("Operation failed"),
    )
}

/// Calculates the maximum error
///
/// Maximum error is the maximum absolute difference between the true and predicted values.
///
/// # Arguments
///
/// * `y_true` - Ground truth (correct) target values
/// * `y_pred` - Estimated target values
///
/// # Returns
///
/// * The maximum error
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_metrics::regression::max_error;
///
/// let y_true = array![3.0, -0.5, 2.0, 7.0];
/// let y_pred = array![2.5, 0.0, 2.0, 8.0];
///
/// let me = max_error(&y_true, &y_pred).expect("Operation failed");
/// // Maximum of [|3.0-2.5|, |-0.5-0.0|, |2.0-2.0|, |7.0-8.0|]
/// assert_eq!(me, 1.0);
/// ```
#[allow(dead_code)]
pub fn max_error<F, S1, S2, D1, D2>(
    y_true: &ArrayBase<S1, D1>,
    y_pred: &ArrayBase<S2, D2>,
) -> Result<F>
where
    F: Float + NumCast + std::fmt::Debug + scirs2_core::simd_ops::SimdUnifiedOps,
    S1: Data<Elem = F>,
    S2: Data<Elem = F>,
    D1: Dimension,
    D2: Dimension,
{
    // Check that arrays have the same shape
    check_sameshape::<F, S1, S2, D1, D2>(y_true, y_pred)?;

    let mut max_err = F::zero();
    for (yt, yp) in y_true.iter().zip(y_pred.iter()) {
        let error = (*yt - *yp).abs();
        if error > max_err {
            max_err = error;
        }
    }

    Ok(max_err)
}

/// Calculates the median absolute error
///
/// Median absolute error is the median of all absolute differences between
/// the true and predicted values. It is robust to outliers.
///
/// # Arguments
///
/// * `y_true` - Ground truth (correct) target values
/// * `y_pred` - Estimated target values
///
/// # Returns
///
/// * The median absolute error
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_metrics::regression::median_absolute_error;
///
/// let y_true = array![3.0, -0.5, 2.0, 7.0];
/// let y_pred = array![2.5, 0.0, 2.0, 8.0];
///
/// let medae = median_absolute_error(&y_true, &y_pred).expect("Operation failed");
/// // Median of [|3.0-2.5|, |-0.5-0.0|, |2.0-2.0|, |7.0-8.0|] = Median of [0.5, 0.5, 0.0, 1.0]
/// assert_eq!(medae, 0.5);
/// ```
#[allow(dead_code)]
pub fn median_absolute_error<F, S1, S2, D1, D2>(
    y_true: &ArrayBase<S1, D1>,
    y_pred: &ArrayBase<S2, D2>,
) -> Result<F>
where
    F: Float + NumCast + std::fmt::Debug + scirs2_core::simd_ops::SimdUnifiedOps,
    S1: Data<Elem = F>,
    S2: Data<Elem = F>,
    D1: Dimension,
    D2: Dimension,
{
    // Check that arrays have the same shape
    check_sameshape::<F, S1, S2, D1, D2>(y_true, y_pred)?;

    let n_samples = y_true.len();

    // Calculate absolute errors
    let mut abs_errors = Vec::with_capacity(n_samples);
    for (yt, yp) in y_true.iter().zip(y_pred.iter()) {
        abs_errors.push((*yt - *yp).abs());
    }

    // Sort and get median
    abs_errors.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));

    if n_samples % 2 == 1 {
        // Odd number of samples
        Ok(abs_errors[n_samples / 2])
    } else {
        // Even number of samples
        let mid = n_samples / 2;
        Ok((abs_errors[mid - 1] + abs_errors[mid]) / NumCast::from(2).expect("Operation failed"))
    }
}

/// Calculates the mean squared logarithmic error (MSLE)
///
/// Mean squared logarithmic error measures the average squared difference
/// between the logarithm of the predicted and true values. This metric penalizes
/// underestimates more than overestimates.
///
/// # Arguments
///
/// * `y_true` - Ground truth (correct) target values
/// * `y_pred` - Estimated target values
///
/// # Returns
///
/// * The mean squared logarithmic error
///
/// # Notes
///
/// * This metric cannot be used with negative values
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_metrics::regression::mean_squared_log_error;
///
/// let y_true = array![3.0, 5.0, 2.5, 7.0];
/// let y_pred = array![2.5, 5.0, 3.0, 8.0];
///
/// let msle = mean_squared_log_error(&y_true, &y_pred).expect("Operation failed");
/// assert!(msle > 0.0);
/// ```
#[allow(dead_code)]
pub fn mean_squared_log_error<F, S1, S2, D1, D2>(
    y_true: &ArrayBase<S1, D1>,
    y_pred: &ArrayBase<S2, D2>,
) -> Result<F>
where
    F: Float + NumCast + std::fmt::Debug + scirs2_core::simd_ops::SimdUnifiedOps,
    S1: Data<Elem = F>,
    S2: Data<Elem = F>,
    D1: Dimension,
    D2: Dimension,
{
    // Check that arrays have the same shape
    check_sameshape::<F, S1, S2, D1, D2>(y_true, y_pred)?;

    let n_samples = y_true.len();

    // Check that all values are non-negative
    for &val in y_true.iter() {
        if val < F::zero() {
            return Err(MetricsError::InvalidInput(
                "y_true contains negative values".to_string(),
            ));
        }
    }

    for &val in y_pred.iter() {
        if val < F::zero() {
            return Err(MetricsError::InvalidInput(
                "y_pred contains negative values".to_string(),
            ));
        }
    }

    let mut squared_log_diff_sum = F::zero();
    for (yt, yp) in y_true.iter().zip(y_pred.iter()) {
        // Add 1 to avoid taking log of 0
        let log_yt = (*yt + F::one()).ln();
        let log_yp = (*yp + F::one()).ln();
        let log_diff = log_yt - log_yp;
        squared_log_diff_sum = squared_log_diff_sum + log_diff * log_diff;
    }

    Ok(squared_log_diff_sum / NumCast::from(n_samples).expect("Operation failed"))
}

/// Calculates the Huber loss
///
/// Huber loss is less sensitive to outliers than squared error loss.
/// For small errors, it behaves like squared error, and for large errors,
/// it behaves like absolute error.
///
/// # Arguments
///
/// * `y_true` - Ground truth (correct) target values
/// * `y_pred` - Estimated target values
/// * `delta` - Threshold where the loss changes from squared to linear
///
/// # Returns
///
/// * The Huber loss
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_metrics::regression::huber_loss;
///
/// let y_true = array![3.0, -0.5, 2.0, 7.0];
/// let y_pred = array![2.5, 0.0, 2.0, 8.0];
/// let delta = 0.5;
///
/// let loss = huber_loss(&y_true, &y_pred, delta).expect("Operation failed");
/// assert!(loss > 0.0);
/// ```
#[allow(dead_code)]
pub fn huber_loss<F, S1, S2, D1, D2>(
    y_true: &ArrayBase<S1, D1>,
    y_pred: &ArrayBase<S2, D2>,
    delta: F,
) -> Result<F>
where
    F: Float + NumCast + std::fmt::Debug + scirs2_core::simd_ops::SimdUnifiedOps,
    S1: Data<Elem = F>,
    S2: Data<Elem = F>,
    D1: Dimension,
    D2: Dimension,
{
    // Check that arrays have the same shape
    check_sameshape::<F, S1, S2, D1, D2>(y_true, y_pred)?;

    if delta <= F::zero() {
        return Err(MetricsError::InvalidInput(
            "delta must be positive".to_string(),
        ));
    }

    let n_samples = y_true.len();
    let mut loss_sum = F::zero();

    for (yt, yp) in y_true.iter().zip(y_pred.iter()) {
        let error = (*yt - *yp).abs();
        if error <= delta {
            // Quadratic part
            loss_sum = loss_sum
                + F::from(0.5).expect("Failed to convert constant to float") * error * error;
        } else {
            // Linear part
            loss_sum = loss_sum
                + delta
                    * (error - F::from(0.5).expect("Failed to convert constant to float") * delta);
        }
    }

    Ok(loss_sum / NumCast::from(n_samples).expect("Operation failed"))
}

/// Calculates the normalized root mean squared error (NRMSE)
///
/// # Arguments
///
/// * `y_true` - Ground truth (correct) target values
/// * `y_pred` - Estimated target values
/// * `normalization` - Method used for normalization:
///   * "mean" - RMSE / mean(y_true)
///   * "range" - RMSE / (max(y_true) - min(y_true))
///   * "iqr" - RMSE / interquartile range of y_true
///
/// # Returns
///
/// * The normalized root mean squared error
///
/// # Examples
///
/// ```no_run
/// use scirs2_core::ndarray::array;
/// use scirs2_metrics::regression::normalized_root_mean_squared_error;
///
/// let y_true = array![3.0, -0.5, 2.0, 7.0];
/// let y_pred = array![2.5, 0.0, 2.0, 8.0];
///
/// let nrmse_mean: f64 = normalized_root_mean_squared_error(&y_true, &y_pred, "mean").expect("Operation failed");
/// let nrmse_range: f64 = normalized_root_mean_squared_error(&y_true, &y_pred, "range").expect("Operation failed");
/// assert!(nrmse_mean > 0.0);
/// assert!(nrmse_range > 0.0);
/// ```
#[allow(dead_code)]
pub fn normalized_root_mean_squared_error<F, S1, S2, D1, D2>(
    y_true: &ArrayBase<S1, D1>,
    y_pred: &ArrayBase<S2, D2>,
    normalization: &str,
) -> Result<F>
where
    F: Float + NumCast + std::fmt::Debug + scirs2_core::simd_ops::SimdUnifiedOps,
    S1: Data<Elem = F>,
    S2: Data<Elem = F>,
    D1: Dimension,
    D2: Dimension,
{
    let rmse = root_mean_squared_error(y_true, y_pred)?;

    match normalization {
        "mean" => {
            // RMSE / mean(y_true)
            let mean = y_true.iter().fold(F::zero(), |acc, &y| acc + y)
                / NumCast::from(y_true.len()).expect("Operation failed");
            if mean.abs() < F::epsilon() {
                return Err(MetricsError::InvalidInput(
                    "Mean of y_true is zero, cannot normalize by mean".to_string(),
                ));
            }
            Ok(rmse / mean.abs())
        }
        "range" => {
            // RMSE / (max(y_true) - min(y_true))
            let max = y_true
                .iter()
                .fold(F::neg_infinity(), |acc, &y| if y > acc { y } else { acc });
            let min = y_true
                .iter()
                .fold(F::infinity(), |acc, &y| if y < acc { y } else { acc });
            let range = max - min;
            if range < F::epsilon() {
                return Err(MetricsError::InvalidInput(
                    "Range of y_true is zero, cannot normalize by range".to_string(),
                ));
            }
            Ok(rmse / range)
        }
        "iqr" => {
            // RMSE / interquartile range of y_true
            let mut values: Vec<F> = y_true.iter().cloned().collect();
            values.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));

            let n = values.len();
            let q1_idx = n / 4;
            let q3_idx = 3 * n / 4;

            let q1 = if n.is_multiple_of(4) {
                (values[q1_idx - 1] + values[q1_idx]) / NumCast::from(2).expect("Operation failed")
            } else {
                values[q1_idx]
            };

            let q3 = if n.is_multiple_of(4) {
                (values[q3_idx - 1] + values[q3_idx]) / NumCast::from(2).expect("Operation failed")
            } else {
                values[q3_idx]
            };

            let iqr = q3 - q1;
            if iqr < F::epsilon() {
                return Err(MetricsError::InvalidInput(
                    "Interquartile range of y_true is zero, cannot normalize by IQR".to_string(),
                ));
            }
            Ok(rmse / iqr)
        }
        _ => Err(MetricsError::InvalidInput(format!(
            "Unknown normalization method: {}. Valid options are 'mean', 'range', 'iqr'.",
            normalization
        ))),
    }
}

/// Calculates the relative absolute error (RAE)
///
/// RAE is the ratio of the sum of absolute errors to the sum of absolute
/// deviations from the mean of the true values.
///
/// # Arguments
///
/// * `y_true` - Ground truth (correct) target values
/// * `y_pred` - Estimated target values
///
/// # Returns
///
/// * The relative absolute error
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_metrics::regression::relative_absolute_error;
///
/// let y_true = array![3.0, -0.5, 2.0, 7.0];
/// let y_pred = array![2.5, 0.0, 2.0, 8.0];
///
/// let rae = relative_absolute_error(&y_true, &y_pred).expect("Operation failed");
/// assert!(rae > 0.0 && rae < 1.0);
/// ```
#[allow(dead_code)]
pub fn relative_absolute_error<F, S1, S2, D1, D2>(
    y_true: &ArrayBase<S1, D1>,
    y_pred: &ArrayBase<S2, D2>,
) -> Result<F>
where
    F: Float + NumCast + std::fmt::Debug + scirs2_core::simd_ops::SimdUnifiedOps,
    S1: Data<Elem = F>,
    S2: Data<Elem = F>,
    D1: Dimension,
    D2: Dimension,
{
    // Check that arrays have the same shape
    check_sameshape::<F, S1, S2, D1, D2>(y_true, y_pred)?;

    // Calculate mean of y_true
    let y_true_mean = y_true.iter().fold(F::zero(), |acc, &y| acc + y)
        / NumCast::from(y_true.len()).expect("Operation failed");

    let mut abs_error_sum = F::zero();
    let mut abs_mean_diff_sum = F::zero();

    for (yt, yp) in y_true.iter().zip(y_pred.iter()) {
        abs_error_sum = abs_error_sum + (*yt - *yp).abs();
        abs_mean_diff_sum = abs_mean_diff_sum + (*yt - y_true_mean).abs();
    }

    if abs_mean_diff_sum < F::epsilon() {
        return Err(MetricsError::InvalidInput(
            "Sum of absolute deviations from mean is zero".to_string(),
        ));
    }

    Ok(abs_error_sum / abs_mean_diff_sum)
}

/// Calculates the relative squared error (RSE)
///
/// RSE is the ratio of the sum of squared errors to the sum of squared
/// deviations from the mean of the true values.
///
/// # Arguments
///
/// * `y_true` - Ground truth (correct) target values
/// * `y_pred` - Estimated target values
///
/// # Returns
///
/// * The relative squared error
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_metrics::regression::relative_squared_error;
///
/// let y_true = array![3.0, -0.5, 2.0, 7.0];
/// let y_pred = array![2.5, 0.0, 2.0, 8.0];
///
/// let rse = relative_squared_error(&y_true, &y_pred).expect("Operation failed");
/// assert!(rse > 0.0 && rse < 1.0);
/// ```
#[allow(dead_code)]
pub fn relative_squared_error<F, S1, S2, D1, D2>(
    y_true: &ArrayBase<S1, D1>,
    y_pred: &ArrayBase<S2, D2>,
) -> Result<F>
where
    F: Float + NumCast + std::fmt::Debug + scirs2_core::simd_ops::SimdUnifiedOps,
    S1: Data<Elem = F>,
    S2: Data<Elem = F>,
    D1: Dimension,
    D2: Dimension,
{
    // Check that arrays have the same shape
    check_sameshape::<F, S1, S2, D1, D2>(y_true, y_pred)?;

    // Calculate mean of y_true
    let y_true_mean = y_true.iter().fold(F::zero(), |acc, &y| acc + y)
        / NumCast::from(y_true.len()).expect("Operation failed");

    let mut squared_error_sum = F::zero();
    let mut squared_mean_diff_sum = F::zero();

    for (yt, yp) in y_true.iter().zip(y_pred.iter()) {
        let error = *yt - *yp;
        squared_error_sum = squared_error_sum + error * error;

        let mean_diff = *yt - y_true_mean;
        squared_mean_diff_sum = squared_mean_diff_sum + mean_diff * mean_diff;
    }

    if squared_mean_diff_sum < F::epsilon() {
        return Err(MetricsError::InvalidInput(
            "Sum of squared deviations from mean is zero".to_string(),
        ));
    }

    Ok(squared_error_sum / squared_mean_diff_sum)
}