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
875
876
877
878
879
//! Preprocessing helpers for the loaded datasets.
//!
//! Every loader in this crate returns a [`Table`](crate::table::Table) of raw
//! [`ndarray`] columns: numbers exactly as the source published them, and
//! categorical values as strings. Model input usually needs four steps: split
//! off an evaluation set, scale the numeric columns, encode the categorical
//! columns, and encode the labels. This module provides those steps, so a user
//! does not need to reimplement them or add a framework dependency just to run a
//! baseline.
//!
//! # Splitting is index-based
//!
//! The splitting functions ([`train_test_split`](crate::preprocessing::train_test_split),
//! [`stratified_split`](crate::preprocessing::stratified_split),
//! [`k_fold_indices`](crate::preprocessing::k_fold_indices),
//! [`shuffled_indices`](crate::preprocessing::shuffled_indices)) return **row indices**, not arrays.
//! That is deliberate. A sample spans every column of the loader's
//! [`Table`](crate::table::Table). One index list keeps them aligned. Convert
//! indices to arrays with ndarray's own `select`. The example below also needs the
//! `dataset` feature:
//!
//! ```no_run
//! use dataset_ml::Iris;
//! use dataset_ml::preprocessing::train_test_split;
//! use ndarray::Axis;
//!
//! let dataset = Iris::new("./data");
//! let table = dataset.data().unwrap();
//!
//! let features = table.numeric_matrix(&Iris::FEATURE_NAMES).unwrap();
//! let species = table.column(Iris::TARGET).unwrap().as_string().unwrap();
//!
//! let (train, test) = train_test_split(features.nrows(), 0.2, 42).unwrap();
//!
//! let train_x = features.select(Axis(0), &train);
//! let train_y = species.select(Axis(0), &train);
//! let test_x = features.select(Axis(0), &test);
//! let test_y = species.select(Axis(0), &test);
//!
//! assert_eq!(train_x.nrows(), 120);
//! assert_eq!(test_x.nrows(), 30);
//! ```
//!
//! # Determinism
//!
//! Everything that shuffles takes an explicit `u64` seed and uses a
//! [SplitMix64](https://doi.org/10.1145/2714064.2660195) generator built into this
//! crate. It has no `rand` dependency and no hidden global state. The same seed
//! and the same inputs always produce the same split, on every platform and every
//! release of this crate.
//!
//! # Missing values
//!
//! Several loaders encode a missing number as `NaN` (`titanic`, `palmer_penguins`,
//! `heart_disease`). The scalers here compute their statistics over the
//! **finite** values of each column. Non-finite entries stay untouched, so a
//! missing value stays missing instead of corrupting the whole column's
//! statistics. Decide how to impute it yourself.
use DatasetError;
use ;
use HashMap;
/// The name this module uses to tag its errors.
const MODULE_NAME: &str = "preprocessing";
/// A pair of disjoint row-index lists that a splitting function produces.
///
/// The first list is the training side, the second is the held-out side (the test
/// set for [`train_test_split`] / [`stratified_split`], the validation fold for
/// [`k_fold_indices`]). Use them to index into your arrays with ndarray's
/// `select(Axis(0), &indices)`.
pub type IndexSplit = ;
/// A small, fast, fully deterministic pseudo-random number generator.
///
/// This is Steele, Lea, and Flood's SplitMix64, the finalizer that seeds many
/// modern generators. It is not cryptographically secure. It does not need to
/// be: it exists to make shuffling and splitting reproducible across platforms
/// without adding a dependency. It works well enough for choosing which rows
/// land in which fold.
/// Return `0..n_samples` in a deterministic pseudo-random order.
///
/// The other functions in this module build on this shuffling primitive. Use it
/// directly to reorder a dataset without splitting it. For example, use it before
/// a pass over data that arrived grouped by class, as `iris`, `covtype`, and
/// `movie_review_polarity` do.
///
/// # Parameters
///
/// - `n_samples` - How many indices to produce.
/// - `seed` - Seed for the internal generator. The same seed always yields the same order.
///
/// # Returns
///
/// - `Vec<usize>` - A permutation of `0..n_samples`.
///
/// # Example
/// ```rust
/// use dataset_ml::preprocessing::shuffled_indices;
///
/// let order = shuffled_indices(5, 42);
/// assert_eq!(order.len(), 5);
///
/// // Every index appears exactly once...
/// let mut sorted = order.clone();
/// sorted.sort_unstable();
/// assert_eq!(sorted, vec![0, 1, 2, 3, 4]);
///
/// // ...and the same seed reproduces the same order.
/// assert_eq!(shuffled_indices(5, 42), order);
/// ```
/// Split `0..n_samples` into shuffled train and test index lists.
///
/// The test set gets `round(n_samples * test_ratio)` rows, clamped so that neither
/// side is empty whenever there are at least two samples. The train set gets the
/// rest. Both lists are in shuffled order, so a dataset stored grouped by class
/// (the common case) does not produce a train set missing a class.
///
/// To keep each class's proportion intact, use [`stratified_split`] instead.
///
/// # Parameters
///
/// - `n_samples` - Total number of samples to split.
/// - `test_ratio` - Fraction of samples to place in the test set, in `0.0..=1.0`.
/// - `seed` - Seed for the internal generator. The same seed always yields the same split.
///
/// # Returns
///
/// - `IndexSplit` - The `(train, test)` row indices. Together they are
/// a permutation of `0..n_samples`, and they never overlap.
///
/// # Errors
///
/// - `DatasetError::ValidationError` - Returns this when `n_samples` is 0, or when
/// `test_ratio` is not a finite value in `0.0..=1.0`.
///
/// # Example
/// ```rust
/// use dataset_ml::preprocessing::train_test_split;
///
/// let (train, test) = train_test_split(150, 0.2, 42).unwrap();
/// assert_eq!(train.len(), 120);
/// assert_eq!(test.len(), 30);
///
/// // The two sides are disjoint and cover everything.
/// let mut all: Vec<usize> = train.iter().chain(test.iter()).copied().collect();
/// all.sort_unstable();
/// assert_eq!(all, (0..150).collect::<Vec<_>>());
/// ```
/// Split into train and test index lists that preserve each class's proportion.
///
/// Like [`train_test_split`], but this function draws the split **within** each
/// class rather than over the whole dataset. A class that holds 10% of the
/// samples then holds about 10% of the train set and 10% of the test set. This
/// matters for the imbalanced loaders: `sms_spam` (13% spam), `covtype` (its
/// rarest cover type is under 0.5%), and `kddcup99`. An unstratified split can
/// omit a rare class from the test set completely.
///
/// Every class with at least two members contributes at least one row to each side.
/// A class with a single member contributes it to the train set.
///
/// # Parameters
///
/// - `labels` - The per-sample class labels, of any comparable, hashable type
/// (`&str`, `String`, `u8`, `char`, and so on). This covers every label type
/// this crate produces.
/// - `test_ratio` - Fraction of each class to place in the test set, in `0.0..=1.0`.
/// - `seed` - Seed for the internal generator. The same seed always yields the same split.
///
/// # Returns
///
/// - `IndexSplit` - The `(train, test)` row indices, each in shuffled
/// order. Together they are a permutation of `0..labels.len()`.
///
/// # Errors
///
/// - `DatasetError::ValidationError` - Returns this when `labels` is empty, or when
/// `test_ratio` is not a finite value in `0.0..=1.0`.
///
/// # Example
/// ```rust
/// use dataset_ml::preprocessing::stratified_split;
///
/// // Nine samples of class "a", one of class "b".
/// let labels = ["a", "a", "a", "a", "a", "a", "a", "a", "a", "b"];
/// let (train, test) = stratified_split(&labels, 0.5, 7).unwrap();
///
/// // The lone "b" cannot be in both sides, so it stays in the train set.
/// assert!(train.contains(&9));
/// assert_eq!(train.len() + test.len(), 10);
/// ```
/// Partition `0..n_samples` into `k` cross-validation folds.
///
/// This function shuffles the samples once and deals them into `k` folds whose
/// sizes differ by at most one. Each entry of the result is the
/// `(train, validation)` pair for one fold. The validation list is that fold, and
/// the train list is everything else. Every sample serves as validation exactly
/// once across the `k` rounds.
///
/// # Parameters
///
/// - `n_samples` - Total number of samples to partition.
/// - `k` - Number of folds. Must be at least 2 and at most `n_samples`.
/// - `seed` - Seed for the internal generator. The same seed always yields the same folds.
///
/// # Returns
///
/// - `Vec<IndexSplit>` - `k` pairs of `(train, validation)` row indices.
///
/// # Errors
///
/// - `DatasetError::ValidationError` - Returns this when `n_samples` is 0, or when `k`
/// is less than 2 or greater than `n_samples`.
///
/// # Example
/// ```rust
/// use dataset_ml::preprocessing::k_fold_indices;
///
/// let folds = k_fold_indices(10, 5, 42).unwrap();
/// assert_eq!(folds.len(), 5);
///
/// for (train, validation) in &folds {
/// assert_eq!(validation.len(), 2);
/// assert_eq!(train.len(), 8);
/// }
///
/// // Each sample is validated exactly once.
/// let mut validated: Vec<usize> = folds.iter().flat_map(|(_, v)| v.clone()).collect();
/// validated.sort_unstable();
/// assert_eq!(validated, (0..10).collect::<Vec<_>>());
/// ```
/// Map labels of any type to consecutive integer codes.
///
/// Turns a label vector into the `0..n_classes` codes most training code
/// expects. A loader holds its labels in an `Array1<String>`, and this function
/// also accepts any other comparable type. It returns the class list needed to
/// decode a prediction. This function numbers classes in **sorted** order, so the
/// encoding depends only on the set of labels present, never on their order in
/// the file.
///
/// # Parameters
///
/// - `labels` - The per-sample labels to encode.
///
/// # Returns
///
/// - `(Array1<usize>, Vec<T>)` - The per-sample codes, and the sorted class list
/// where index `i` is the class encoded as `i`.
///
/// # Errors
///
/// - `DatasetError::ValidationError` - Returns this when `labels` is empty.
///
/// # Example
/// ```rust
/// use dataset_ml::preprocessing::label_encode;
/// use ndarray::array;
///
/// let labels = array!["virginica", "setosa", "setosa", "versicolor"];
/// let (codes, classes) = label_encode(&labels).unwrap();
///
/// // Classes get numbers alphabetically, not in order of appearance.
/// assert_eq!(classes, vec!["setosa", "versicolor", "virginica"]);
/// assert_eq!(codes, array![2, 0, 0, 1]);
///
/// // Decode a prediction through the class list.
/// assert_eq!(classes[codes[0]], "virginica");
/// ```
/// Count how many samples carry each label.
///
/// This is a quick way to see how balanced a dataset is before choosing between
/// [`train_test_split`] and [`stratified_split`]. This function returns counts in
/// sorted class order, matching the numbering [`label_encode`] assigns.
///
/// # Parameters
///
/// - `labels` - The per-sample labels to count.
///
/// # Returns
///
/// - `Vec<(T, usize)>` - Each distinct class and its sample count, sorted by class.
///
/// # Example
/// ```rust
/// use dataset_ml::preprocessing::class_counts;
/// use ndarray::array;
///
/// let labels = array!["spam", "ham", "ham", "ham"];
/// assert_eq!(class_counts(&labels), vec![("ham", 3), ("spam", 1)]);
/// ```
/// Fitting a scaler produces these per-column statistics. Reuse them to replay the
/// same transform on new data.
///
/// Fit a scaler on the **training** rows only. Then apply it unchanged to the test
/// rows. Fitting it on everything leaks information about the test set into
/// training. That is why [`standardize`] and [`min_max_scale`] return this struct.
/// Keep it. Pass it to [`apply_scaler`] for every later batch.
///
/// The two field names describe the general shape of the transform,
/// `(value - center) / scale`:
///
/// - [`standardize`] sets `center` to the column mean and `scale` to its standard
/// deviation.
/// - [`min_max_scale`] sets `center` to the column minimum and `scale` to its range.
/// Standardize each feature column to zero mean and unit variance.
///
/// This is the classic z-score transform, `(value - mean) / std_dev`, applied per
/// column. It is what distance-based and gradient-based models want from the raw
/// numeric matrices these loaders return. Those columns routinely differ by orders
/// of magnitude: for example, `adult`'s `fnlwgt` runs to the hundreds of thousands,
/// while `education-num` goes no higher than 16.
///
/// This function computes the mean and standard deviation (population, that is,
/// divided by `n`) over the **finite** values of each column. Non-finite entries
/// stay untouched, so a `NaN` marking a missing value stays a `NaN`. A column with
/// no variation gets a scale of 1 and maps to all zeros rather than dividing by 0.
///
/// # Parameters
///
/// - `features` - The numeric feature matrix, shape `(n_samples, n_features)`.
///
/// # Returns
///
/// - `(Array2<f64>, Scaler)` - The standardized matrix, and the fitted per-column
/// statistics to replay on later data with [`apply_scaler`].
///
/// # Errors
///
/// - `DatasetError::ValidationError` - Returns this when `features` has no rows or no columns.
///
/// # Example
/// ```rust
/// use dataset_ml::preprocessing::standardize;
/// use ndarray::array;
///
/// let features = array![[1.0, 10.0], [2.0, 20.0], [3.0, 30.0]];
/// let (scaled, scaler) = standardize(&features).unwrap();
///
/// assert_eq!(scaler.center, array![2.0, 20.0]);
/// assert_eq!(scaled[[1, 0]], 0.0); // the mean row maps to 0
/// assert!((scaled[[0, 0]] + scaled[[2, 0]]).abs() < 1e-12); // symmetric about it
/// ```
/// Rescale each feature column into the `[0, 1]` range.
///
/// This is min-max scaling, `(value - min) / (max - min)`, applied per column.
/// Prefer it over [`standardize`] when a bounded range matters more than a
/// comparable spread. Use it for pixel-like features (`digits`), or as input to a
/// model that expects `[0, 1]`.
///
/// As with [`standardize`], the minimum and maximum come from the **finite**
/// values of each column. Non-finite entries stay untouched. A constant column
/// maps to all zeros rather than dividing by 0.
///
/// # Parameters
///
/// - `features` - The numeric feature matrix, shape `(n_samples, n_features)`.
///
/// # Returns
///
/// - `(Array2<f64>, Scaler)` - The rescaled matrix, and the fitted per-column
/// statistics to replay on later data with [`apply_scaler`].
///
/// # Errors
///
/// - `DatasetError::ValidationError` - Returns this when `features` has no rows or no columns.
///
/// # Example
/// ```rust
/// use dataset_ml::preprocessing::min_max_scale;
/// use ndarray::array;
///
/// let features = array![[1.0, -5.0], [3.0, 5.0]];
/// let (scaled, _scaler) = min_max_scale(&features).unwrap();
///
/// assert_eq!(scaled, array![[0.0, 0.0], [1.0, 1.0]]);
/// ```
/// Apply an already-fitted [`Scaler`] to a feature matrix.
///
/// Use this to replay a training-fitted scaler onto the test rows, or onto later
/// data, without refitting. Refitting would give the two sets different transforms
/// and leak test statistics into training.
///
/// Non-finite entries stay untouched, matching the fitting functions.
///
/// # Parameters
///
/// - `features` - The numeric feature matrix to transform, shape `(n_samples, n_features)`.
/// - `scaler` - Statistics from a previous [`standardize`] or [`min_max_scale`] call.
///
/// # Returns
///
/// - `Array2<f64>` - The transformed matrix, with the same shape as `features`.
///
/// # Errors
///
/// - `DatasetError::LengthMismatch` - Returns this when `features` has a different
/// number of columns than the scaler expects.
///
/// # Example
/// ```rust
/// use dataset_ml::preprocessing::{apply_scaler, standardize};
/// use ndarray::array;
///
/// let train = array![[1.0], [2.0], [3.0]];
/// let (_scaled_train, scaler) = standardize(&train).unwrap();
///
/// // This transforms the test rows with the training statistics, not their own.
/// let test = array![[2.0], [4.0]];
/// let scaled_test = apply_scaler(&test, &scaler).unwrap();
/// assert_eq!(scaled_test[[0, 0]], 0.0); // 2.0 was the training mean
/// ```
/// One-hot encode a matrix of categorical string features.
///
/// The mixed-type loaders (`adult`, `titanic`, `bank_marketing`, `abalone`,
/// `kddcup99`, `palmer_penguins`) and the all-categorical ones (`mushroom`,
/// `car_evaluation`) keep their categorical values in
/// [`ColumnData::String`](crate::table::ColumnData::String) columns. Read each
/// column by name with `as_string`, then stack the columns into an
/// `Array2<String>`. No numeric model can consume strings directly. This function
/// expands each column into one indicator column per level it takes. A row gets
/// `1.0` in the column for its own level, and `0.0` everywhere else.
///
/// This function sorts levels within a column, so the output layout depends only
/// on the values present. The returned names identify the columns as
/// `<column>=<level>`, using `column_names` when supplied, and `column_0`,
/// `column_1`, and so on otherwise.
///
/// This widens the matrix by however many distinct levels the data holds. That is
/// harmless for `mushroom` (22 columns become 117). Before running it on
/// `kddcup99`'s `service` column (70 levels over millions of rows), check the
/// resulting width.
///
/// # Parameters
///
/// - `categorical` - The categorical matrix, shape `(n_samples, n_features)`.
/// - `column_names` - Optional names for the source columns, used to build the
/// output names. Must have one entry per column when supplied.
///
/// # Returns
///
/// - `(Array2<f64>, Vec<String>)` - The indicator matrix, shape
/// `(n_samples, total_levels)`, and one name per output column.
///
/// # Errors
///
/// - `DatasetError::ValidationError` - Returns this when `categorical` has no rows or no columns.
/// - `DatasetError::LengthMismatch` - Returns this when `column_names` is `Some` but
/// its length does not match the column count.
///
/// # Example
/// ```rust
/// use dataset_ml::preprocessing::one_hot_encode;
/// use ndarray::array;
///
/// let categorical = array![
/// ["male".to_string(), "S".to_string()],
/// ["female".to_string(), "C".to_string()],
/// ["male".to_string(), "C".to_string()],
/// ];
/// let (encoded, names) = one_hot_encode(&categorical, Some(&["sex", "port"])).unwrap();
///
/// assert_eq!(names, vec!["sex=female", "sex=male", "port=C", "port=S"]);
/// assert_eq!(encoded.row(0).to_vec(), vec![0.0, 1.0, 0.0, 1.0]); // male, S
/// ```
/// Reject a ratio that is not a finite fraction.
/// How many of `n` samples go to the test side. Both sides stay non-empty
/// whenever more than one sample exists.
/// Sum a column's finite values, and count how many there were.
/// Build a [`Scaler`] by applying `statistics` to every column of `features`.
///
/// The closure returns that column's `(center, scale)`. If the scale is 0 (a
/// constant column), the function replaces it with 1, so the transform maps that
/// column to zeros instead of `NaN`.