Created
April 3, 2022 21:34
-
-
Save josht-jpg/825662b6a90d4ae0282e998e4b27499a to your computer and use it in GitHub Desktop.
Linear algebra for Rust implementation of K nearest Neighbors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait LinearAlg<T> | |
where | |
T: Add + Sub, | |
{ | |
fn dot(&self, w: &[T]) -> T; | |
fn subtract(&self, w: &[T]) -> Vec<T>; | |
fn sum_of_squares(&self) -> T; | |
fn distance(&self, w: &[T]) -> f64; | |
} | |
impl LinearAlg<f64> for Vec<f64> { | |
fn dot(&self, w: &[f64]) -> f64 { | |
assert_eq!(self.len(), w.len()); | |
self.iter().zip(w).map(|(v_i, w_i)| v_i * w_i).sum() | |
} | |
fn subtract(&self, w: &[f64]) -> Vec<f64> { | |
assert_eq!(self.len(), w.len()); | |
self.iter().zip(w).map(|(v_i, w_i)| v_i - w_i).collect() | |
} | |
fn sum_of_squares(&self) -> f64 { | |
self.dot(&self) | |
} | |
fn distance(&self, w: &[f64]) -> f64 { | |
assert_eq!(self.len(), w.len()); | |
self.subtract(w).sum_of_squares().sqrt() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment