Module rml::knn [−][src]
Expand description
Implementation for K-Nearest Neighbors.
Allows for predicting data based on a KNN search.
A full, working example is contained in the examples/knn
directory.
Example
// Collect and parse data to a format consistent with:
// type CSVOutput = (Vec<Vec<f64>>, Vec<i32>);
let training_data: CSVOutput = (Vec::new, Vec::new);
let testing_data: CSVOutput = (Vec::new, Vec::new);
// Create a new KNN struct.
let knn = knn::KNN::new(
5, // 5-nearest
training_data.0, // x
training_data.1, // y
None, // Default distance(euclidean)
Some(math::norm::Norm::L2), // L2 Normalization
);
// Get a prediction for each point of the testing data.
let pred: Vec<i32> = testing_data.0.iter().map(|x| knn.predict(x)).collect();
// Count the number that were predicted correctly.
let num_correct = pred
.iter()
.cloned()
.zip(&testing_data.1)
.filter(|(a, b)| *a == **b)
.count();
println!(
"Accuracy: {}",
(num_correct as f64) / (pred.len() as f64)
);