neuronika 0.2.0

Tensors and dynamic neural networks.
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
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
//! Data loading and manipulation utilities.
//!
//! # Dataset Types
//!
//! Neuronika provides two kinds of datasets, an unlabeled one, that is [`Dataset`], and a labeled
//! one, that is [`LabeledDataset`]. They both own their data uniquely.
//!
//! Datasets are basic containers for your data and are designed to easily interact with models
//! built with neuronika. They are created with the help of the [`DataLoader`] struct which performs
//! the actual I/O operations.
//!
//! Both datasets are generic on the [dimensionality] of their records and are organized as a tensors
//! in which the length of the outermost axis is equal to the total number of records and the
//! number of remaining axes represent the dimensionality of each data point.
//!
//! [`.from_csv()`]: crate::data::DataLoader::from_csv
//! [dimensionality]: ndarray::Dimension
//!
//! # Loading Data
//!
//! At the core of neuronika data utilities is the [`DataLoader`] struct. It can be used to load
//! data in *comma-separated values format* from a [*reader*](Read) or directly from a *.csv* file.
//!
//! Additional parsing settings are passed using `DataLoader`'s methods in the following way.
//!
//! ```should_panic
//! use neuronika::data::DataLoader;
//!
//! let data = DataLoader::default()           // A typical use case would be
//!     .with_labels(&[5, 6, 7])               // to load some data from
//!     .with_delimiter(',')                   // a .csv file.
//!     .from_csv("./folder/data.csv", 3, 1);
//! ```
//!
//! The result of the loading operation is either a [`Dataset`] or a [`LabeledDataset`], depending
//! on how the loader was configured.
//!
//! ## Handling Labels
//!
//! You may find useful, in many real world scenarios, to convert labels to floating point numbers.
//! In neuronika this is quickly achievable with closures. Take a look at the following example.
//!
//! ```rust
//! use neuronika::data::DataLoader;
//!
//! let csv_content = "\
//!     Paw_size,Tail_length,Weight,Animal\n\
//!     0.2,5.0,15.0,Dog\n\
//!     0.08,12.0,4.0,Cat\n\
//!     0.05,3.0,0.8,Mouse";
//!
//! let dataset = DataLoader::default().with_labels(&[3]).from_reader_fn(
//!     csv_content.as_bytes(),
//!     3,
//!     1,
//!     |(record, label): (Vec<f32>, String)| {
//!         let float_label = match label.as_str() {
//!             "Dog" => 1.,
//!             "Cat" => 2.,
//!              _ => 3.,
//!         };
//!         (record, vec![float_label])
//!     },
//! );
//! ```

use csv::{ReaderBuilder, StringRecord};
use itertools::Itertools;
use ndarray::{
    iter::AxisChunksIter, Array, ArrayView, Axis, Dimension, IntoDimension, Ix, RemoveAxis, Zip,
};
use rand::{rngs::StdRng, Rng, SeedableRng};
use serde::de::DeserializeOwned;
use std::{fs::File, io::Read};

/// Computes the correct shape for the stacked records of a dataset.
fn stacked_shape<D: Dimension>(rows: usize, shape: D) -> D::Larger {
    let mut new_shape = D::Larger::zeros(shape.ndim() + 1);
    new_shape[0] = rows;
    new_shape.slice_mut()[1..].clone_from_slice(shape.slice());

    new_shape
}

/// A collection of uniquely owned unlabeled records.
///
/// See also [*data*](index.html#data).
pub struct Dataset<D> {
    records: Array<f32, D>,
}

impl<D: RemoveAxis> Dataset<D> {
    /// Creates a new dataset from an [`Array`](ndarray::Array).
    ///
    /// # Arguments
    ///
    /// `records` - records to store into the dataset
    fn new(records: Array<f32, D>) -> Self {
        Self { records }
    }

    /// Returns a reference to the records.
    pub fn records(&self) -> &Array<f32, D> {
        &self.records
    }

    /// Returns the number of records stored in the dataset.
    pub fn len(&self) -> usize {
        self.records.len_of(Axis(0))
    }

    /// Checks whether the dataset is empty or not.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Constructs a K-Fold iterator from the dataset.
    ///
    /// The dataset is split *without shuffling* into k consecutive folds.
    ///
    /// Items returned by the [`KFold`] iterator are splits of the dataset. Each fold is used
    /// exactly once as a validation set, while the remaining k - 1 form the training set.
    ///
    /// Returned items are of the form `(Dataset, Dataset)`.
    ///
    /// # Arguments
    ///
    /// `k` - number of folds to perform.
    ///
    /// # Panics
    ///
    /// If `k < 2`.
    pub fn kfold(&self, k: usize) -> KFold<D> {
        KFold::new(self.records.view(), k)
    }

    /// Divides the dataset into batches of size `batch_size`.
    ///
    /// # Arguments
    ///
    /// `batch_size` - size of a single batch.
    pub fn batch(&self, batch_size: usize) -> Batch<D> {
        Batch::new(&self.records, batch_size)
    }

    /// Splits a dataset into non-overlapping new datasets of given lengths.
    ///
    /// # Arguments
    ///
    /// `lengths` -  lengths of splits to be produced.
    ///
    /// # Panics
    ///
    /// If the sum of the input lengths do not cover the whole dataset.
    pub fn split(self, lengths: &[usize]) -> Vec<Dataset<D>> {
        if self.len() != lengths.iter().sum::<usize>() {
            panic!("error: input lengths do not cover the whole dataset.");
        }

        let mut shape = self.records.raw_dim();
        let elems: Ix = shape.slice().iter().skip(1).product();
        let mut records = self.records.into_raw_vec();

        let mut datasets = Vec::with_capacity(lengths.len());
        for length in lengths {
            shape[0] = *length;

            datasets.push(Dataset::new(
                Array::from_shape_vec(shape.clone(), records.drain(..length * elems).collect())
                    .unwrap(),
            ));
        }

        datasets
    }

    /// Randomly shuffles the dataset.
    pub fn shuffle(&mut self) -> &mut Self {
        self.shuffle_with_seed(rand::thread_rng().gen())
    }

    /// Randomly shuffles the dataset.
    ///
    /// This version allows for a seed to be specified for results reproducibility.
    pub fn shuffle_with_seed(&mut self, seed: u64) -> &mut Self {
        let len = self.records.len_of(Axis(0));

        if len == 0 {
            return self;
        }

        let mut rng = StdRng::seed_from_u64(seed);
        for i in 0..len - 1 {
            // Since `iter.nth(pos)` consumes all the elements in `[0, pos]`
            // j will be in the interval `[pos + 1, len - 1]`, that contains `len - pos - 1`
            // elements
            let j = rng.gen_range(0..len - i - 1);

            let mut iter = self.records.outer_iter_mut();
            Zip::from(iter.nth(i).unwrap())
                .and(iter.nth(j).unwrap())
                .for_each(std::mem::swap);
        }

        self
    }
}

/// Configurable data loader.
pub struct DataLoader {
    r_builder: ReaderBuilder,
}

impl DataLoader {
    /// Specifies the columns where the labels are located.
    ///
    /// # Arguments
    ///
    /// `labels` - labels' columns indices.
    ///
    /// # Panics
    ///
    /// If the supplied labels are empty or if they contain duplicate columns.
    pub fn with_labels(self, labels: &[usize]) -> LabeledDataLoader {
        LabeledDataLoader::new(self, labels)
    }

    /// Configures the loader so that it parses the first row. To be used in the absence of an
    /// header row, as in most datasets the first row usually contains the columns' identifiers.
    pub fn without_headers(&mut self) -> &mut Self {
        self.r_builder.has_headers(false);

        self
    }

    /// Specifies the field delimiter character.
    ///
    /// # Arguments
    ///
    /// `delimiter` - delimiter character.
    pub fn with_delimiter(&mut self, delimiter: char) -> &mut Self {
        self.r_builder.delimiter(delimiter as u8);

        self
    }

    /// Builds a data collection by loading the content of the specified `.csv` file applying the
    /// previously supplied configuration.
    ///
    /// # Arguments
    ///
    /// * `src` - path of the source file.
    /// * `shape` - shape of a single record.
    ///
    /// # Panics
    ///
    /// In the case of errors during I/O or if `shape` generates an empty record.
    pub fn from_csv<S>(&mut self, src: &str, shape: S) -> Dataset<<S::Dim as Dimension>::Larger>
    where
        S: IntoDimension,
    {
        self.from_reader_fn(File::open(src).unwrap(), shape, |r| r)
    }

    /// Builds a data collection by loading the content of the specified source reader applying the
    /// previously supplied configuration.    
    ///
    /// # Arguments
    ///
    /// * `src` - reader from which to load the data.
    /// * `shape` - shape of a single record.
    ///
    /// # Panics
    ///
    /// In the event of a deserialization error or if `shape` would generate an empty record.
    pub fn from_reader<R, S>(&mut self, src: R, shape: S) -> Dataset<<S::Dim as Dimension>::Larger>
    where
        R: Read,
        S: IntoDimension,
    {
        self.from_reader_fn(src, shape, |r| r)
    }

    /// Builds a data collection by loading the content of the specified `.csv` file applying the
    /// previously supplied configuration. Applies `fn` to each record.
    ///
    /// # Arguments
    ///
    /// * `src` - reader from which to load the data.
    /// * `shape` - shape of a single record.
    /// * `fn` - closure to be applied to each record.
    ///
    /// # Panics
    ///
    /// In the event of a deserialization error or if `shape` would generate an empty record.
    pub fn from_csv_fn<S, T, F>(
        &mut self,
        src: &str,
        shape: S,
        f: F,
    ) -> Dataset<<S::Dim as Dimension>::Larger>
    where
        S: IntoDimension,
        T: DeserializeOwned,
        F: Fn(T) -> Vec<f32>,
    {
        self.from_reader_fn(File::open(src).unwrap(), shape, f)
    }

    /// Builds a data collection by loading the content of the specified source reader applying the
    /// previously supplied configuration. Applies `fn` to each record.
    ///
    /// # Arguments
    ///
    /// * `src` - reader from which to load the data.
    /// * `shape` - shape of a single record.
    /// * `fn` - closure to be applied to each record.
    ///
    /// # Panics
    ///
    /// In the event of a deserialization error or if `shape` would generate an empty record.
    pub fn from_reader_fn<R, S, T, F>(
        &mut self,
        src: R,
        shape: S,
        f: F,
    ) -> Dataset<<S::Dim as Dimension>::Larger>
    where
        R: Read,
        S: IntoDimension,
        T: DeserializeOwned,
        F: Fn(T) -> Vec<f32>,
    {
        let shape = shape.into_dimension();
        if shape.size() == 0 {
            panic!("error: cannot handle empty records.")
        }

        let mut records = Vec::new();
        let mut rows = 0;
        for record in self.r_builder.from_reader(src).deserialize() {
            let record = f(record.unwrap());
            records.extend(record);
            rows += 1;
        }

        Dataset::new(Array::from_shape_vec(stacked_shape(rows, shape), records).unwrap())
    }
}

impl Default for DataLoader {
    /// Creates a preconfigured data loader.
    ///
    /// The base configuration considers the first row of the source as an header, skipping it, and
    /// it uses `,` as the field delimiter.
    fn default() -> Self {
        Self {
            r_builder: ReaderBuilder::new(),
        }
    }
}

/// Configurable loader for labeled data.
pub struct LabeledDataLoader {
    r_builder: ReaderBuilder,
    labels: Vec<usize>,
}

impl LabeledDataLoader {
    fn deserialize_record<T, U>(&self, record: StringRecord) -> (T, U)
    where
        T: DeserializeOwned,
        U: DeserializeOwned,
    {
        let mut input = StringRecord::new();
        let mut label = StringRecord::new();
        for (id, value) in record.iter().enumerate() {
            match self.labels.binary_search(&id) {
                Ok(_) => label.push_field(value),
                Err(_) => input.push_field(value),
            }
        }

        (
            input.deserialize(None).unwrap(),
            label.deserialize(None).unwrap(),
        )
    }

    fn new(builder: DataLoader, labels: &[usize]) -> Self {
        if labels.is_empty() {
            panic!("error: labels were not provided.");
        }

        let mut labels = labels.to_vec();
        labels.sort_unstable();
        if labels.windows(2).any(|w| w[0] == w[1]) {
            panic!("error: duplicated labels.");
        }

        Self {
            r_builder: builder.r_builder,
            labels,
        }
    }

    /// Configures the loader so that it parses the first row. To be used in the absence of an
    /// header row, as in most datasets the first row usually contains the columns' identifiers.
    pub fn without_headers(&mut self) -> &mut Self {
        self.r_builder.has_headers(false);

        self
    }

    /// Specifies the field delimiter character.
    ///
    /// # Arguments
    ///
    /// `delimiter` - delimiter character.
    pub fn with_delimiter(&mut self, delimiter: char) -> &mut Self {
        self.r_builder.delimiter(delimiter as u8);

        self
    }

    /// Builds a labeled data collection by loading the content of the specified `.csv` file
    /// applying the previously supplied configuration.
    ///
    /// # Arguments
    ///
    /// * `src` - path of the source file.
    /// * `record_shape` - shape of a single record.
    /// * `label_shape` - shape of a single label.
    ///
    /// # Panics
    ///
    /// In the case of I/O errors or if `record_shape` generates an empty record or `label_shape`
    /// generates an empty label.
    pub fn from_csv<S1, S2>(
        &mut self,
        src: &str,
        record_shape: S1,
        label_shape: S2,
    ) -> LabeledDataset<<S1::Dim as Dimension>::Larger, <S2::Dim as Dimension>::Larger>
    where
        S1: IntoDimension,
        S2: IntoDimension,
    {
        self.from_reader_fn(File::open(src).unwrap(), record_shape, label_shape, |r| r)
    }

    /// Builds a data collection by loading the content of the specified source reader applying the
    /// previously supplied configuration.    
    ///
    /// # Arguments
    ///
    /// * `src` - reader from which to load the data.
    /// * `record_shape` - shape of a single record.
    /// * `label_shape` - shape of a single label.
    ///
    /// # Panics
    ///
    /// In the event of a deserialization error or if `record_shape` generates an empty record or
    /// `label_shape` generates an empty label.
    pub fn from_reader<R, S1, S2>(
        &mut self,
        src: R,
        record_shape: S1,
        label_shape: S2,
    ) -> LabeledDataset<<S1::Dim as Dimension>::Larger, <S2::Dim as Dimension>::Larger>
    where
        R: Read,
        S1: IntoDimension,
        S2: IntoDimension,
    {
        self.from_reader_fn(src, record_shape, label_shape, |r| r)
    }

    /// Builds a data collection by loading the content of the specified `.csv` file applying the
    /// previously supplied configuration. Applies `fn` to each record and each label.
    ///
    /// # Arguments
    ///
    /// * `src` - reader from which to load the data.
    /// * `record_shape` - shape of a single record.
    /// * `label_shape` - shape of a single label.    
    /// * `fn` - closure to be applied to records and labels.
    ///
    /// # Panics
    ///
    /// In the event of a deserialization error or if `record_shape` generates an empty record or
    /// `label_shape` generates an empty label.
    pub fn from_csv_fn<S1, S2, T, U, F>(
        &mut self,
        src: &str,
        record_shape: S1,
        label_shape: S2,
        f: F,
    ) -> LabeledDataset<<S1::Dim as Dimension>::Larger, <S2::Dim as Dimension>::Larger>
    where
        S1: IntoDimension,
        S2: IntoDimension,
        T: DeserializeOwned,
        U: DeserializeOwned,
        F: Fn((T, U)) -> (Vec<f32>, Vec<f32>),
    {
        self.from_reader_fn(File::open(src).unwrap(), record_shape, label_shape, f)
    }

    /// Builds a data collection by loading the content of the specified source reader applying the
    /// previously supplied configuration. Applies `fn` to each record and each label.
    ///
    /// # Arguments
    ///
    /// * `src` - reader from which to load the data.
    /// * `record_shape` - shape of a single record.
    /// * `label_shape` - shape of a single label.    
    /// * `fn` - closure to be applied to records and labels.
    ///
    /// # Panics
    ///
    /// In the event of a deserialization error if `record_shape` generates an empty record or
    /// `label_shape` generates an empty label.
    pub fn from_reader_fn<R, S1, S2, T, U, F>(
        &mut self,
        src: R,
        record_shape: S1,
        label_shape: S2,
        f: F,
    ) -> LabeledDataset<<S1::Dim as Dimension>::Larger, <S2::Dim as Dimension>::Larger>
    where
        R: Read,
        S1: IntoDimension,
        S2: IntoDimension,
        T: DeserializeOwned,
        U: DeserializeOwned,
        F: Fn((T, U)) -> (Vec<f32>, Vec<f32>),
    {
        let record_shape = record_shape.into_dimension();
        let label_shape = label_shape.into_dimension();
        if record_shape.size() == 0 || label_shape.size() == 0 {
            panic!("error: cannot handle empty records")
        }

        let mut records = Vec::new();
        let mut labels = Vec::new();
        let mut rows = 0;
        for record in self.r_builder.from_reader(src).records() {
            let (record, label) = f(self.deserialize_record(record.unwrap()));
            records.extend(record);
            labels.extend(label);
            rows += 1;
        }

        LabeledDataset::new(
            Array::from_shape_vec(stacked_shape(rows, record_shape), records).unwrap(),
            Array::from_shape_vec(stacked_shape(rows, label_shape), labels).unwrap(),
        )
    }
}

/// A collection of uniquely owned *labeled* records.
///
/// `LabeledDataset` is generic on both the dimensionality of the records, specified by `D1` and
/// that of the labels, specified by `D2`. It's organized as a pair of tensors, one for the data and
/// one for the labels.
///
/// See also [*data*](index.html#data).
pub struct LabeledDataset<D1, D2> {
    records: Array<f32, D1>,
    labels: Array<f32, D2>,
}

impl<D1: RemoveAxis, D2: RemoveAxis> LabeledDataset<D1, D2> {
    /// Creates a new `LabeledDataset` from a pair of [`Array`]s.
    ///
    /// # Arguments
    ///
    /// * `records` - records to be stored.
    /// * `labels` - labels to be stored.
    fn new(records: Array<f32, D1>, labels: Array<f32, D2>) -> Self {
        Self { records, labels }
    }

    /// Returns a reference to the records.
    pub fn records(&self) -> &Array<f32, D1> {
        &self.records
    }

    /// Returns a reference to the labels.
    pub fn labels(&self) -> &Array<f32, D2> {
        &self.labels
    }

    /// Returns the number of records stored in the labeled dataset.
    pub fn len(&self) -> usize {
        self.records.len_of(Axis(0))
    }

    /// Check whether the labeled dataset is empty or not.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Constructs a K-Fold iterator from the labeled dataset.
    ///
    /// The dataset is split *without shuffling* into k consecutive folds.
    ///
    /// Items returned by the [`LabeledKFold`] iterator are splits of the dataset, both records and
    /// labels. Each fold is used exactly once as a validation set, while the remaining k - 1 form
    /// the training set.
    ///
    /// Returned items are of the form `(LabeledDataset, LabeledDataset)`.
    ///
    /// # Arguments
    ///
    /// `k` - number of folds to perform.
    ///
    /// # Panics
    ///
    /// If `k < 2`.
    pub fn kfold(&self, k: usize) -> LabeledKFold<D1, D2> {
        LabeledKFold::new(self.records.view(), self.labels.view(), k)
    }

    /// Divides the labeled dataset into batches of size `batch_size`.
    ///
    /// # Arguments
    ///
    /// `batch_size` - size of a single batch.
    pub fn batch(&self, size: usize) -> LabeledBatch<D1, D2> {
        LabeledBatch::new(&self.records, &self.labels, size)
    }

    /// Splits a labeled dataset into non-overlapping new datasets of given lengths.
    ///
    /// # Arguments
    ///
    /// `lengths` -  lengths of splits to be produced.
    ///
    /// # Panics
    ///
    /// If the sum of the input lengths do not cover the whole dataset.
    pub fn split(self, lengths: &[usize]) -> Vec<LabeledDataset<D1, D2>> {
        if self.len() != lengths.iter().sum::<usize>() {
            panic!("error: input lengths do not cover the whole dataset.");
        }

        let mut r_shape = self.records.raw_dim();
        let r_elems: Ix = r_shape.slice().iter().skip(1).product();
        let mut records = self.records.into_raw_vec();

        let mut l_shape = self.labels.raw_dim();
        let l_elems: Ix = l_shape.slice().iter().skip(1).product();
        let mut labels = self.labels.into_raw_vec();

        let mut datasets = Vec::with_capacity(lengths.len());
        for length in lengths {
            r_shape[0] = *length;
            l_shape[0] = *length;

            datasets.push(LabeledDataset::new(
                Array::from_shape_vec(r_shape.clone(), records.drain(..length * r_elems).collect())
                    .unwrap(),
                Array::from_shape_vec(l_shape.clone(), labels.drain(..length * l_elems).collect())
                    .unwrap(),
            ));
        }

        datasets
    }

    /// Randomly shuffles the labeled dataset.
    pub fn shuffle(&mut self) -> &mut Self {
        self.shuffle_with_seed(rand::thread_rng().gen())
    }

    /// Randomly shuffles the labeled dataset.
    ///
    /// This version allows for a seed to be specified for results reproducibility.
    pub fn shuffle_with_seed(&mut self, seed: u64) -> &mut Self {
        let len = self.records.len_of(Axis(0));

        if len == 0 {
            return self;
        }

        let mut rng = StdRng::seed_from_u64(seed);
        for i in 0..len - 1 {
            // Since `iter.nth(pos)` consumes all the elements in `[0, pos]`
            // j will be in the interval `[pos + 1, len - 1]`, that contains `len - pos - 1`
            // elements
            let j = rng.gen_range(0..len - i - 1);

            let mut iter = self.records.outer_iter_mut();
            Zip::from(iter.nth(i).unwrap())
                .and(iter.nth(j).unwrap())
                .for_each(std::mem::swap);

            let mut iter = self.labels.outer_iter_mut();
            Zip::from(iter.nth(i).unwrap())
                .and(iter.nth(j).unwrap())
                .for_each(std::mem::swap);
        }

        self
    }
}

/// Iterator over batches of unlabeled data.
pub struct Batch<'a, D> {
    iter: AxisChunksIter<'a, f32, D>,
}

impl<'a, D: RemoveAxis> Batch<'a, D> {
    fn new(source: &'a Array<f32, D>, size: usize) -> Self {
        Self {
            iter: source.axis_chunks_iter(Axis(0), size),
        }
    }

    /// Drops the last incomplete batch, if the dataset size is not divisible by the batch size.
    pub fn drop_last(mut self) -> Self {
        let mut current = self.iter.clone();

        if let Some(next) = current.next() {
            if let Some(last) = current.last() {
                if next.len_of(Axis(0)) != last.len_of(Axis(0)) {
                    self.iter = self.iter.dropping_back(1);
                }
            }
        }

        self
    }
}

impl<'a, D: RemoveAxis> Iterator for Batch<'a, D> {
    type Item = <AxisChunksIter<'a, f32, D> as Iterator>::Item;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next()
    }
}

struct SetKFold<'a, D> {
    source: ArrayView<'a, f32, D>,
    step: usize,
    axis_len: usize,
}

impl<'a, D: RemoveAxis> SetKFold<'a, D> {
    pub fn new(source: ArrayView<'a, f32, D>, k: usize) -> Self {
        if k < 2 {
            panic!("error: folds must be > 2.");
        }

        let axis_len = source.len_of(Axis(0));
        debug_assert_ne!(axis_len, 0, "no record provided");

        Self {
            source,
            step: 1 + (axis_len - 1) / k,
            axis_len,
        }
    }

    pub fn compute_fold(&mut self, i: usize) -> (Array<f32, D>, Array<f32, D>) {
        let start = self.step * i;
        let stop = self.axis_len.min(start + self.step);

        let train_ids: Vec<usize> = (0..start).chain(stop..self.axis_len).collect();
        let test_ids: Vec<usize> = (start..stop).collect();

        (
            self.source.select(Axis(0), &train_ids),
            self.source.select(Axis(0), &test_ids),
        )
    }
}

/// K-Folds cross-validator on a labeled dataset.
pub struct LabeledKFold<'a, D1, D2> {
    records: SetKFold<'a, D1>,
    labels: SetKFold<'a, D2>,
    iteration: usize,
    k: usize,
}

impl<'a, D1, D2> LabeledKFold<'a, D1, D2>
where
    D1: RemoveAxis,
    D2: RemoveAxis,
{
    pub fn new(records: ArrayView<'a, f32, D1>, labels: ArrayView<'a, f32, D2>, k: usize) -> Self {
        assert_eq!(records.len_of(Axis(0)), labels.len_of(Axis(0)));

        Self {
            records: SetKFold::new(records, k),
            labels: SetKFold::new(labels, k),
            iteration: 0,
            k,
        }
    }
}

impl<'a, D1, D2> Iterator for LabeledKFold<'a, D1, D2>
where
    D1: RemoveAxis,
    D2: RemoveAxis,
{
    type Item = (LabeledDataset<D1, D2>, LabeledDataset<D1, D2>);

    fn next(&mut self) -> Option<Self::Item> {
        if self.iteration >= self.k {
            return None;
        }

        let (train_in, test_in) = self.records.compute_fold(self.iteration);
        let (train_out, test_out) = self.labels.compute_fold(self.iteration);
        self.iteration += 1;

        Some((
            LabeledDataset::new(train_in, train_out),
            LabeledDataset::new(test_in, test_out),
        ))
    }
}

/// Iterator over batches of labeled data.
pub struct LabeledBatch<'a, D1, D2> {
    records: Batch<'a, D1>,
    labels: Batch<'a, D2>,
}

impl<'a, D1: RemoveAxis, D2: RemoveAxis> LabeledBatch<'a, D1, D2> {
    fn new(records: &'a Array<f32, D1>, labels: &'a Array<f32, D2>, size: usize) -> Self {
        assert_eq!(records.len_of(Axis(0)), labels.len_of(Axis(0)));

        Self {
            records: Batch::new(records, size),
            labels: Batch::new(labels, size),
        }
    }

    /// Drops the last incomplete batch, if the dataset size is not divisible by the batch size.
    pub fn drop_last(mut self) -> Self {
        self.records = self.records.drop_last();
        self.labels = self.labels.drop_last();

        self
    }
}

impl<'a, D1: RemoveAxis, D2: RemoveAxis> Iterator for LabeledBatch<'a, D1, D2> {
    type Item = (
        <Batch<'a, D1> as Iterator>::Item,
        <Batch<'a, D2> as Iterator>::Item,
    );

    fn next(&mut self) -> Option<Self::Item> {
        match self.records.next() {
            Some(records) => Some((records, self.labels.next().unwrap())),
            None => None,
        }
    }
}

/// K-Folds cross-validator on a dataset.
pub struct KFold<'a, D> {
    records: SetKFold<'a, D>,
    iteration: usize,
    k: usize,
}

impl<'a, D: RemoveAxis> KFold<'a, D> {
    pub fn new(records: ArrayView<'a, f32, D>, k: usize) -> Self {
        Self {
            records: SetKFold::new(records, k),
            iteration: 0,
            k,
        }
    }
}

impl<'a, D: RemoveAxis> Iterator for KFold<'a, D> {
    type Item = (Dataset<D>, Dataset<D>);

    fn next(&mut self) -> Option<Self::Item> {
        if self.iteration >= self.k {
            return None;
        }

        let (records_in, records_out) = self.records.compute_fold(self.iteration);
        self.iteration += 1;

        Some((Dataset::new(records_in), Dataset::new(records_out)))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    mod dataset {
        use super::*;
        use ndarray::Array;

        static DATASET: &str = "\
            0,1,2,3,4,5,6,7,8,9\n\
            9,8,7,6,5,4,3,2,1,0\n\
            0,1,2,3,4,5,6,7,8,9\n\
            9,8,7,6,5,4,3,2,1,0\n\
            0,1,2,3,4,5,6,7,8,9";

        #[test]
        fn from_reader() {
            let dataset = DataLoader::default()
                .without_headers()
                .from_reader(DATASET.as_bytes(), 10);

            assert_eq!(
                dataset.records(),
                Array::from_shape_vec(
                    (5, 10),
                    vec![
                        0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 9., 8., 7., 6., 5., 4., 3., 2., 1.,
                        0., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 9., 8., 7., 6., 5., 4., 3., 2.,
                        1., 0., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,
                    ]
                )
                .unwrap()
            );
        }

        #[test]
        fn kfold() {
            let dataset = DataLoader::default()
                .without_headers()
                .from_reader(DATASET.as_bytes(), 10);
            let mut kfold = dataset.kfold(2);

            let (train, test) = kfold.next().unwrap();
            assert_eq!(
                train.records(),
                Array::from_shape_vec(
                    (2, 10),
                    vec![
                        9., 8., 7., 6., 5., 4., 3., 2., 1., 0., 0., 1., 2., 3., 4., 5., 6., 7., 8.,
                        9.,
                    ]
                )
                .unwrap()
            );
            assert_eq!(
                test.records(),
                Array::from_shape_vec(
                    (3, 10),
                    vec![
                        0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 9., 8., 7., 6., 5., 4., 3., 2., 1.,
                        0., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,
                    ]
                )
                .unwrap()
            );

            let (train, test) = kfold.next().unwrap();
            assert_eq!(
                train.records(),
                Array::from_shape_vec(
                    (3, 10),
                    vec![
                        0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 9., 8., 7., 6., 5., 4., 3., 2., 1.,
                        0., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,
                    ]
                )
                .unwrap()
            );
            assert_eq!(
                test.records(),
                Array::from_shape_vec(
                    (2, 10),
                    vec![
                        9., 8., 7., 6., 5., 4., 3., 2., 1., 0., 0., 1., 2., 3., 4., 5., 6., 7., 8.,
                        9.,
                    ]
                )
                .unwrap()
            );

            assert!(kfold.next().is_none());
        }

        #[test]
        fn batch() {
            let dataset = DataLoader::default()
                .without_headers()
                .from_reader(DATASET.as_bytes(), 10);

            let mut batch = dataset.batch(3);
            assert_eq!(
                batch.next().unwrap(),
                Array::from_shape_vec(
                    (3, 10),
                    vec![
                        0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 9., 8., 7., 6., 5., 4., 3., 2., 1.,
                        0., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,
                    ]
                )
                .unwrap()
            );

            assert_eq!(
                batch.next().unwrap(),
                Array::from_shape_vec(
                    (2, 10),
                    vec![
                        9., 8., 7., 6., 5., 4., 3., 2., 1., 0., 0., 1., 2., 3., 4., 5., 6., 7., 8.,
                        9.,
                    ]
                )
                .unwrap()
            );

            assert!(batch.next().is_none());
        }

        #[test]
        fn split() {
            let dataset = DataLoader::default()
                .without_headers()
                .from_reader(DATASET.as_bytes(), 10);

            let datasets = dataset.split(&[1, 1, 1, 2]);

            assert_eq!(
                datasets[0].records(),
                Array::from_shape_vec((1, 10), vec![0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,])
                    .unwrap()
            );

            assert_eq!(
                datasets[1].records(),
                Array::from_shape_vec((1, 10), vec![9., 8., 7., 6., 5., 4., 3., 2., 1., 0.])
                    .unwrap()
            );

            assert_eq!(
                datasets[2].records(),
                Array::from_shape_vec((1, 10), vec![0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,])
                    .unwrap()
            );

            assert_eq!(
                datasets[3].records(),
                Array::from_shape_vec(
                    (2, 10),
                    vec![
                        9., 8., 7., 6., 5., 4., 3., 2., 1., 0., 0., 1., 2., 3., 4., 5., 6., 7., 8.,
                        9.,
                    ]
                )
                .unwrap()
            );
        }

        #[test]
        fn shuffle() {
            let mut dataset = DataLoader::default()
                .without_headers()
                .from_reader(DATASET.as_bytes(), 10);

            dataset.shuffle();

            assert_ne!(
                dataset.records(),
                Array::from_shape_vec(
                    (5, 10),
                    vec![
                        0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 9., 8., 7., 6., 5., 4., 3., 2., 1.,
                        0., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 9., 8., 7., 6., 5., 4., 3., 2.,
                        1., 0., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,
                    ]
                )
                .unwrap()
            );
        }

        #[test]
        fn drop_last() {
            let dataset = DataLoader::default()
                .without_headers()
                .from_reader(DATASET.as_bytes(), 10);

            let mut batch = dataset.batch(3).drop_last();
            assert_eq!(
                batch.next().unwrap(),
                Array::from_shape_vec(
                    (3, 10),
                    vec![
                        0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 9., 8., 7., 6., 5., 4., 3., 2., 1.,
                        0., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,
                    ]
                )
                .unwrap()
            );

            assert!(batch.next().is_none());
            assert!(batch.next().is_none());
        }
    }

    mod labeled_dataset {
        use super::*;
        use ndarray::Array;

        static DATASET: &str = "\
            0,1,2,1,3,4,5,6,0,7,8,9\n\
            9,8,7,0,6,5,4,3,1,2,1,0\n\
            0,1,2,1,3,4,5,6,0,7,8,9\n\
            9,8,7,0,6,5,4,3,1,2,1,0\n\
            0,1,2,1,3,4,5,6,0,7,8,9";

        #[test]
        fn from_reader() {
            let dataset = DataLoader::default()
                .with_labels(&[3, 8])
                .without_headers()
                .from_reader(DATASET.as_bytes(), 10, 2);

            assert_eq!(
                dataset.records(),
                Array::from_shape_vec(
                    (5, 10),
                    vec![
                        0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 9., 8., 7., 6., 5., 4., 3., 2., 1.,
                        0., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 9., 8., 7., 6., 5., 4., 3., 2.,
                        1., 0., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,
                    ]
                )
                .unwrap()
            );

            assert_eq!(
                dataset.labels(),
                Array::from_shape_vec((5, 2), vec![1., 0., 0., 1., 1., 0., 0., 1., 1., 0.])
                    .unwrap()
            );
        }

        #[test]
        fn kfold() {
            let dataset = DataLoader::default()
                .with_labels(&[3, 8])
                .without_headers()
                .from_reader(DATASET.as_bytes(), 10, 2);
            let mut kfold = dataset.kfold(2);

            let (train, test) = kfold.next().unwrap();
            assert_eq!(
                train.records(),
                Array::from_shape_vec(
                    (2, 10),
                    vec![
                        9., 8., 7., 6., 5., 4., 3., 2., 1., 0., 0., 1., 2., 3., 4., 5., 6., 7., 8.,
                        9.,
                    ]
                )
                .unwrap()
            );
            assert_eq!(
                train.labels(),
                Array::from_shape_vec((2, 2), vec![0., 1., 1., 0.]).unwrap()
            );
            assert_eq!(
                test.records(),
                Array::from_shape_vec(
                    (3, 10),
                    vec![
                        0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 9., 8., 7., 6., 5., 4., 3., 2., 1.,
                        0., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,
                    ]
                )
                .unwrap()
            );
            assert_eq!(
                test.labels(),
                Array::from_shape_vec((3, 2), vec![1., 0., 0., 1., 1., 0.]).unwrap()
            );

            let (train, test) = kfold.next().unwrap();
            assert_eq!(
                train.records(),
                Array::from_shape_vec(
                    (3, 10),
                    vec![
                        0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 9., 8., 7., 6., 5., 4., 3., 2., 1.,
                        0., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,
                    ]
                )
                .unwrap()
            );
            assert_eq!(
                train.labels(),
                Array::from_shape_vec((3, 2), vec![1., 0., 0., 1., 1., 0.]).unwrap()
            );
            assert_eq!(
                test.records(),
                Array::from_shape_vec(
                    (2, 10),
                    vec![
                        9., 8., 7., 6., 5., 4., 3., 2., 1., 0., 0., 1., 2., 3., 4., 5., 6., 7., 8.,
                        9.,
                    ]
                )
                .unwrap()
            );
            assert_eq!(
                test.labels(),
                Array::from_shape_vec((2, 2), vec![0., 1., 1., 0.]).unwrap()
            );

            assert!(kfold.next().is_none());
        }

        #[test]
        fn batch() {
            let dataset = DataLoader::default()
                .with_labels(&[3, 8])
                .without_headers()
                .from_reader(DATASET.as_bytes(), 10, 2);
            let mut batch = dataset.batch(3);

            let (records, labels) = batch.next().unwrap();
            assert_eq!(
                records,
                Array::from_shape_vec(
                    (3, 10),
                    vec![
                        0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 9., 8., 7., 6., 5., 4., 3., 2., 1.,
                        0., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,
                    ]
                )
                .unwrap()
            );
            assert_eq!(
                labels,
                Array::from_shape_vec((3, 2), vec![1., 0., 0., 1., 1., 0.]).unwrap()
            );

            let (records, labels) = batch.next().unwrap();
            assert_eq!(
                records,
                Array::from_shape_vec(
                    (2, 10),
                    vec![
                        9., 8., 7., 6., 5., 4., 3., 2., 1., 0., 0., 1., 2., 3., 4., 5., 6., 7., 8.,
                        9.,
                    ]
                )
                .unwrap()
            );
            assert_eq!(
                labels,
                Array::from_shape_vec((2, 2), vec![0., 1., 1., 0.]).unwrap()
            );

            assert!(batch.next().is_none());
        }

        #[test]
        fn split() {
            let dataset = DataLoader::default()
                .with_labels(&[3, 8])
                .without_headers()
                .from_reader(DATASET.as_bytes(), 10, 2);

            let datasets = dataset.split(&[1, 1, 1, 2]);
            assert_eq!(
                datasets[0].records(),
                Array::from_shape_vec((1, 10), vec![0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,])
                    .unwrap()
            );
            assert_eq!(
                datasets[0].labels(),
                Array::from_shape_vec((1, 2), vec![1., 0.]).unwrap()
            );

            assert_eq!(
                datasets[1].records(),
                Array::from_shape_vec((1, 10), vec![9., 8., 7., 6., 5., 4., 3., 2., 1., 0.,])
                    .unwrap()
            );
            assert_eq!(
                datasets[1].labels(),
                Array::from_shape_vec((1, 2), vec![0., 1.]).unwrap()
            );

            assert_eq!(
                datasets[2].records(),
                Array::from_shape_vec((1, 10), vec![0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,])
                    .unwrap()
            );
            assert_eq!(
                datasets[2].labels(),
                Array::from_shape_vec((1, 2), vec![1., 0.]).unwrap()
            );

            assert_eq!(
                datasets[3].records(),
                Array::from_shape_vec(
                    (2, 10),
                    vec![
                        9., 8., 7., 6., 5., 4., 3., 2., 1., 0., 0., 1., 2., 3., 4., 5., 6., 7., 8.,
                        9.,
                    ]
                )
                .unwrap()
            );
            assert_eq!(
                datasets[3].labels(),
                Array::from_shape_vec((2, 2), vec![0., 1., 1., 0.]).unwrap()
            );
        }

        #[test]
        fn shuffle() {
            let mut dataset = DataLoader::default()
                .with_labels(&[3, 8])
                .without_headers()
                .from_reader(DATASET.as_bytes(), 10, 2);
            dataset.shuffle();

            assert_ne!(
                dataset.records(),
                Array::from_shape_vec(
                    (5, 10),
                    vec![
                        0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 9., 8., 7., 6., 5., 4., 3., 2., 1.,
                        0., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 9., 8., 7., 6., 5., 4., 3., 2.,
                        1., 0., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,
                    ]
                )
                .unwrap()
            );
        }

        #[test]
        fn drop_last() {
            let dataset = DataLoader::default()
                .with_labels(&[3, 8])
                .without_headers()
                .from_reader(DATASET.as_bytes(), 10, 2);
            let mut batch = dataset.batch(3).drop_last();

            let (records, labels) = batch.next().unwrap();
            assert_eq!(
                records,
                Array::from_shape_vec(
                    (3, 10),
                    vec![
                        0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 9., 8., 7., 6., 5., 4., 3., 2., 1.,
                        0., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,
                    ]
                )
                .unwrap()
            );
            assert_eq!(
                labels,
                Array::from_shape_vec((3, 2), vec![1., 0., 0., 1., 1., 0.]).unwrap()
            );

            assert!(batch.next().is_none());
            assert!(batch.next().is_none());
        }
    }
}