rustyml 0.13.0

A high-performance machine learning & deep learning library in pure Rust, offering ML algorithms and neural network support
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
//! Internal input-validation helpers shared across machine-learning estimators
//!
//! Provides checks for feature/target matrices and common hyperparameters
//! (learning rate, max iterations, tolerance, regularization) plus a fitted-state
//! guard, each returning a consistent [`Error`] on failure

use super::RegularizationType;
use crate::error::Error;
use ndarray::{ArrayBase, Data, Ix1, Ix2};

/// Performs validation checks on the input data matrices
///
/// Validates that:
/// - The input data matrix is not empty
/// - The input data does not contain NaN or infinite values
/// - When a target vector is provided:
///   - The target vector is not empty
///   - The target vector length matches the number of rows in the input data
///
/// # Parameters
///
/// - `x` - A 2D array of feature values where rows represent samples and columns represent features
/// - `y` - An optional 1D array of target variables or labels corresponding to each sample
///
/// # Returns
///
/// - `Ok(())` if all validation checks pass, otherwise an `Error`
///
/// # Errors
///
/// - [`Error::EmptyInput`] - If the input data or target vector is empty
/// - [`Error::NonFinite`] - If the input data contains NaN or infinite values
/// - [`Error::DimensionMismatch`] - If the dimensions of `x` and `y` mismatch
pub(super) fn preliminary_check<S>(
    x: &ArrayBase<S, Ix2>,
    y: Option<&ArrayBase<S, Ix1>>,
) -> Result<(), Error>
where
    S: Data<Elem = f64>,
{
    if x.nrows() == 0 {
        return Err(Error::empty_input("input data"));
    }

    for (i, row) in x.outer_iter().enumerate() {
        for (j, &val) in row.iter().enumerate() {
            if val.is_nan() || val.is_infinite() {
                return Err(Error::non_finite(format!(
                    "input data at position [{}][{}]",
                    i, j
                )));
            }
        }
    }

    if let Some(y) = y {
        if y.is_empty() {
            return Err(Error::empty_input("target vector"));
        }

        if y.len() != x.nrows() {
            return Err(Error::dimension_mismatch(x.nrows(), y.len()));
        }
    }
    Ok(())
}

/// Validates that the learning rate parameter is positive and finite
///
/// The learning rate controls the step size in gradient descent optimization,
/// so it must be a positive, finite value to ensure proper convergence behavior
///
/// # Parameters
///
/// - `learning_rate` - The learning rate value to validate
///
/// # Returns
///
/// - `Ok(())` if the learning rate is valid, otherwise an `Error`
///
/// # Errors
///
/// - [`Error::InvalidParameter`] - If the learning rate is non-positive, NaN, or infinite
pub(super) fn validate_learning_rate(learning_rate: f64) -> Result<(), Error> {
    if learning_rate <= 0.0 || !learning_rate.is_finite() {
        return Err(Error::invalid_parameter(
            "learning_rate",
            format!("must be positive and finite, got {}", learning_rate),
        ));
    }

    Ok(())
}

/// Validates that the maximum iterations parameter is greater than zero
///
/// The maximum iterations parameter determines the upper bound on the number
/// of training iterations. It must be at least 1 to allow the algorithm to run
///
/// # Parameters
///
/// - `max_iterations` - The maximum number of iterations to validate
///
/// # Returns
///
/// - `Ok(())` if the maximum iterations value is valid, otherwise an `Error`
///
/// # Errors
///
/// - [`Error::InvalidParameter`] - If the maximum iterations value is 0
pub(super) fn validate_max_iterations(max_iterations: usize) -> Result<(), Error> {
    if max_iterations == 0 {
        return Err(Error::invalid_parameter(
            "max_iterations",
            "must be greater than 0",
        ));
    }

    Ok(())
}

/// Validates that the tolerance parameter is positive and finite
///
/// The tolerance parameter defines the convergence criterion for iterative algorithms:
/// training stops when the change in loss between iterations falls below this threshold,
/// so it must be a positive, finite value to ensure meaningful convergence detection
///
/// # Parameters
///
/// - `tolerance` - The convergence tolerance value to validate
///
/// # Returns
///
/// - `Ok(())` if the tolerance is valid, otherwise an `Error`
///
/// # Errors
///
/// - [`Error::InvalidParameter`] - If the tolerance is non-positive, NaN, or infinite
pub(super) fn validate_tolerance(tolerance: f64) -> Result<(), Error> {
    if tolerance <= 0.0 || !tolerance.is_finite() {
        return Err(Error::invalid_parameter(
            "tolerance",
            format!("must be positive and finite, got {}", tolerance),
        ));
    }

    Ok(())
}

/// Validates the regularization type and its associated parameters
///
/// Checks that regularization parameters are properly configured:
/// - For L1 and L2 regularization, the alpha (regularization strength) parameter
///   must be non-negative and finite
/// - None (no regularization) is always valid
///
/// # Parameters
///
/// - `reg_type` - An optional regularization type with its strength parameter
///
/// # Returns
///
/// - `Ok(())` if the regularization configuration is valid, otherwise an `Error`
///
/// # Errors
///
/// - [`Error::InvalidParameter`] - If the regularization alpha is negative, NaN, or infinite
pub(super) fn validate_regularization_type(
    reg_type: Option<RegularizationType>,
) -> Result<(), Error> {
    if let Some(reg) = &reg_type {
        match reg {
            RegularizationType::L1(alpha) | RegularizationType::L2(alpha) => {
                if *alpha < 0.0 || !alpha.is_finite() {
                    return Err(Error::invalid_parameter(
                        "alpha",
                        format!("must be non-negative and finite, got {}", alpha),
                    ));
                }
            }
        }
    }

    Ok(())
}

/// Returns [`Error::NotFitted`] when a model has not been fitted yet
///
/// Centralizes the "is this model fitted?" guard so every estimator emits the
/// same error instead of hand-rolling the check at each call site
///
/// # Parameters
///
/// - `is_fitted` - Whether the model has already been trained (e.g. `self.weights.is_some()`)
/// - `model` - The model's name, used to build the [`Error::NotFitted`] payload
///
/// # Returns
///
/// - `Ok(())` if the model is fitted, otherwise [`Error::NotFitted`]
///
/// # Errors
///
/// - [`Error::NotFitted`] - If `is_fitted` is `false`
#[inline]
pub(super) fn check_is_fitted(
    is_fitted: bool,
    model: &'static str,
) -> crate::error::RustymlResult<()> {
    if is_fitted {
        Ok(())
    } else {
        Err(Error::not_fitted(model))
    }
}

/// Validates a feature matrix passed to a `predict`-style method
///
/// Performs the three checks every estimator needs before predicting, with a
/// single consistent error message for each failure mode:
/// - the matrix is not empty
/// - the feature count matches the training data
/// - no value is NaN or infinite
///
/// # Parameters
///
/// - `x` - Feature matrix where rows are samples and columns are features
/// - `expected_features` - Number of features the fitted model was trained on
///
/// # Returns
///
/// - `Ok(())` if all checks pass, otherwise an `Error`
///
/// # Errors
///
/// - [`Error::EmptyInput`] - If `x` is empty
/// - [`Error::DimensionMismatch`] - If `x` has a mismatched feature count
/// - [`Error::NonFinite`] - If `x` contains non-finite values
pub(super) fn validate_predict_input<S>(
    x: &ArrayBase<S, Ix2>,
    expected_features: usize,
) -> Result<(), Error>
where
    S: Data<Elem = f64>,
{
    if x.is_empty() {
        return Err(Error::empty_input("dataset to predict on"));
    }

    if x.ncols() != expected_features {
        return Err(Error::dimension_mismatch(expected_features, x.ncols()));
    }

    if x.iter().any(|&val| !val.is_finite()) {
        return Err(Error::non_finite("input data"));
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::Error;
    use ndarray::{Array1, Array2};

    // preliminary_check

    /// preliminary_check with an empty x (0 rows) returns Error::EmptyInput
    #[test]
    fn preliminary_check_empty_x_gives_empty_input() {
        let x: Array2<f64> = Array2::zeros((0, 3));
        let err = preliminary_check(&x, None).unwrap_err();
        match err {
            Error::EmptyInput(_) => {}
            other => panic!("expected EmptyInput, got {:?}", other),
        }
    }

    /// preliminary_check with NaN in x returns Error::NonFinite
    #[test]
    fn preliminary_check_x_with_nan_gives_non_finite() {
        let x = ndarray::array![[1.0, f64::NAN], [2.0, 3.0]];
        let err = preliminary_check(&x, None).unwrap_err();
        match err {
            Error::NonFinite(_) => {}
            other => panic!("expected NonFinite, got {:?}", other),
        }
    }

    /// preliminary_check with infinity in x returns Error::NonFinite
    #[test]
    fn preliminary_check_x_with_inf_gives_non_finite() {
        let x = ndarray::array![[1.0, f64::INFINITY]];
        let err = preliminary_check(&x, None).unwrap_err();
        match err {
            Error::NonFinite(_) => {}
            other => panic!("expected NonFinite, got {:?}", other),
        }
    }

    /// preliminary_check with y.len() != x.nrows() returns Error::DimensionMismatch
    #[test]
    fn preliminary_check_y_len_mismatch_gives_dimension_mismatch() {
        let x = ndarray::array![[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]];
        let y = Array1::from_vec(vec![1.0, 2.0]); // len 2, but x has 3 rows
        let err = preliminary_check(&x, Some(&y)).unwrap_err();
        match err {
            Error::DimensionMismatch { expected, found } => {
                assert_eq!(expected, 3, "expected count should be x.nrows()=3");
                assert_eq!(found, 2, "found count should be y.len()=2");
            }
            other => panic!("expected DimensionMismatch, got {:?}", other),
        }
    }

    /// preliminary_check with a valid finite x and no y returns Ok
    #[test]
    fn preliminary_check_valid_x_no_y_gives_ok() {
        let x = ndarray::array![[1.0, 2.0], [3.0, 4.0]];
        assert!(preliminary_check(&x, None).is_ok());
    }

    /// preliminary_check with a valid x and matching-length y returns Ok
    #[test]
    fn preliminary_check_valid_x_and_y_gives_ok() {
        let x = ndarray::array![[1.0, 2.0], [3.0, 4.0]];
        let y = Array1::from_vec(vec![0.0, 1.0]);
        assert!(preliminary_check(&x, Some(&y)).is_ok());
    }

    // validate_predict_input

    /// validate_predict_input with an empty x returns Error::EmptyInput
    #[test]
    fn validate_predict_input_empty_gives_empty_input() {
        let x: Array2<f64> = Array2::zeros((0, 3));
        let err = validate_predict_input(&x, 3).unwrap_err();
        match err {
            Error::EmptyInput(_) => {}
            other => panic!("expected EmptyInput, got {:?}", other),
        }
    }

    /// validate_predict_input with a feature-count mismatch returns Error::DimensionMismatch
    #[test]
    fn validate_predict_input_ncols_mismatch_gives_dimension_mismatch() {
        let x = ndarray::array![[1.0, 2.0], [3.0, 4.0]]; // ncols = 2
        let err = validate_predict_input(&x, 3).unwrap_err(); // expected 3 cols
        match err {
            Error::DimensionMismatch { expected, found } => {
                assert_eq!(expected, 3);
                assert_eq!(found, 2);
            }
            other => panic!("expected DimensionMismatch, got {:?}", other),
        }
    }

    /// validate_predict_input with NaN in x returns Error::NonFinite
    #[test]
    fn validate_predict_input_nan_gives_non_finite() {
        let x = ndarray::array![[1.0, f64::NAN], [2.0, 3.0]];
        let err = validate_predict_input(&x, 2).unwrap_err();
        match err {
            Error::NonFinite(_) => {}
            other => panic!("expected NonFinite, got {:?}", other),
        }
    }

    /// validate_predict_input with a valid x returns Ok
    #[test]
    fn validate_predict_input_valid_gives_ok() {
        let x = ndarray::array![[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]];
        assert!(validate_predict_input(&x, 3).is_ok());
    }

    // validate_learning_rate

    /// validate_learning_rate with a positive finite value returns Ok
    #[test]
    fn validate_learning_rate_positive_gives_ok() {
        assert!(validate_learning_rate(0.1).is_ok());
    }

    /// validate_learning_rate with 0.0 returns Error::InvalidParameter
    #[test]
    fn validate_learning_rate_zero_gives_invalid_parameter() {
        let err = validate_learning_rate(0.0).unwrap_err();
        match err {
            Error::InvalidParameter { name, .. } => {
                assert_eq!(name, "learning_rate");
            }
            other => panic!("expected InvalidParameter, got {:?}", other),
        }
    }

    /// validate_learning_rate with a negative value returns Error::InvalidParameter
    #[test]
    fn validate_learning_rate_negative_gives_invalid_parameter() {
        let err = validate_learning_rate(-1.0).unwrap_err();
        match err {
            Error::InvalidParameter { name, .. } => assert_eq!(name, "learning_rate"),
            other => panic!("expected InvalidParameter, got {:?}", other),
        }
    }

    /// validate_learning_rate with NaN returns Error::InvalidParameter
    #[test]
    fn validate_learning_rate_nan_gives_invalid_parameter() {
        let err = validate_learning_rate(f64::NAN).unwrap_err();
        match err {
            Error::InvalidParameter { name, .. } => assert_eq!(name, "learning_rate"),
            other => panic!("expected InvalidParameter, got {:?}", other),
        }
    }

    /// validate_learning_rate with infinity returns Error::InvalidParameter
    #[test]
    fn validate_learning_rate_inf_gives_invalid_parameter() {
        let err = validate_learning_rate(f64::INFINITY).unwrap_err();
        match err {
            Error::InvalidParameter { name, .. } => assert_eq!(name, "learning_rate"),
            other => panic!("expected InvalidParameter, got {:?}", other),
        }
    }

    // validate_max_iterations

    /// validate_max_iterations with a value >= 1 returns Ok
    #[test]
    fn validate_max_iterations_one_gives_ok() {
        assert!(validate_max_iterations(1).is_ok());
    }

    /// validate_max_iterations with 0 returns Error::InvalidParameter
    #[test]
    fn validate_max_iterations_zero_gives_invalid_parameter() {
        let err = validate_max_iterations(0).unwrap_err();
        match err {
            Error::InvalidParameter { name, .. } => {
                assert_eq!(name, "max_iterations");
            }
            other => panic!("expected InvalidParameter, got {:?}", other),
        }
    }

    // validate_tolerance

    /// validate_tolerance with a positive finite value returns Ok
    #[test]
    fn validate_tolerance_positive_gives_ok() {
        assert!(validate_tolerance(1e-4).is_ok());
    }

    /// validate_tolerance with 0.0 returns Error::InvalidParameter
    #[test]
    fn validate_tolerance_zero_gives_invalid_parameter() {
        let err = validate_tolerance(0.0).unwrap_err();
        match err {
            Error::InvalidParameter { name, .. } => assert_eq!(name, "tolerance"),
            other => panic!("expected InvalidParameter, got {:?}", other),
        }
    }

    /// validate_tolerance with a negative value returns Error::InvalidParameter
    #[test]
    fn validate_tolerance_negative_gives_invalid_parameter() {
        let err = validate_tolerance(-0.5).unwrap_err();
        match err {
            Error::InvalidParameter { name, .. } => assert_eq!(name, "tolerance"),
            other => panic!("expected InvalidParameter, got {:?}", other),
        }
    }

    /// validate_tolerance with NaN returns Error::InvalidParameter
    #[test]
    fn validate_tolerance_nan_gives_invalid_parameter() {
        let err = validate_tolerance(f64::NAN).unwrap_err();
        match err {
            Error::InvalidParameter { name, .. } => assert_eq!(name, "tolerance"),
            other => panic!("expected InvalidParameter, got {:?}", other),
        }
    }

    /// validate_tolerance with infinity returns Error::InvalidParameter
    #[test]
    fn validate_tolerance_inf_gives_invalid_parameter() {
        let err = validate_tolerance(f64::INFINITY).unwrap_err();
        match err {
            Error::InvalidParameter { name, .. } => assert_eq!(name, "tolerance"),
            other => panic!("expected InvalidParameter, got {:?}", other),
        }
    }

    // validate_regularization_type

    /// validate_regularization_type with None returns Ok
    #[test]
    fn validate_regularization_type_none_gives_ok() {
        assert!(validate_regularization_type(None).is_ok());
    }

    /// validate_regularization_type with a zero L1 alpha returns Ok
    #[test]
    fn validate_regularization_type_l1_zero_gives_ok() {
        assert!(validate_regularization_type(Some(RegularizationType::L1(0.0))).is_ok());
    }

    /// validate_regularization_type with a positive L2 alpha returns Ok
    #[test]
    fn validate_regularization_type_l2_positive_gives_ok() {
        assert!(validate_regularization_type(Some(RegularizationType::L2(0.5))).is_ok());
    }

    /// validate_regularization_type with a negative L1 alpha returns Error::InvalidParameter
    #[test]
    fn validate_regularization_type_l1_negative_gives_invalid_parameter() {
        let err = validate_regularization_type(Some(RegularizationType::L1(-1.0))).unwrap_err();
        match err {
            Error::InvalidParameter { name, .. } => assert_eq!(name, "alpha"),
            other => panic!("expected InvalidParameter, got {:?}", other),
        }
    }

    /// validate_regularization_type with a NaN L1 alpha returns Error::InvalidParameter
    #[test]
    fn validate_regularization_type_l1_nan_gives_invalid_parameter() {
        let err = validate_regularization_type(Some(RegularizationType::L1(f64::NAN))).unwrap_err();
        match err {
            Error::InvalidParameter { name, .. } => assert_eq!(name, "alpha"),
            other => panic!("expected InvalidParameter, got {:?}", other),
        }
    }

    /// validate_regularization_type with an infinite L1 alpha returns Error::InvalidParameter
    #[test]
    fn validate_regularization_type_l1_inf_gives_invalid_parameter() {
        let err =
            validate_regularization_type(Some(RegularizationType::L1(f64::INFINITY))).unwrap_err();
        match err {
            Error::InvalidParameter { name, .. } => assert_eq!(name, "alpha"),
            other => panic!("expected InvalidParameter, got {:?}", other),
        }
    }

    // check_is_fitted

    /// check_is_fitted with is_fitted == true returns Ok
    #[test]
    fn check_is_fitted_true_gives_ok() {
        assert!(check_is_fitted(true, "SomeModel").is_ok());
    }

    /// check_is_fitted with is_fitted == false returns Error::NotFitted carrying the model name
    #[test]
    fn check_is_fitted_false_gives_not_fitted() {
        let err = check_is_fitted(false, "SomeModel").unwrap_err();
        match err {
            Error::NotFitted(model) => assert_eq!(model, "SomeModel"),
            other => panic!("expected NotFitted, got {:?}", other),
        }
    }
}