pub fn label_encode<T: Clone + Ord>(
labels: &Array1<T>,
) -> Result<(Array1<usize>, Vec<T>), DatasetError>Expand description
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 indexiis the class encoded asi.
§Errors
DatasetError::ValidationError- Returns this whenlabelsis empty.
§Example
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");