Skip to content

Instantly share code, notes, and snippets.

@josht-jpg
Created April 3, 2022 21:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josht-jpg/825662b6a90d4ae0282e998e4b27499a to your computer and use it in GitHub Desktop.
Save josht-jpg/825662b6a90d4ae0282e998e4b27499a to your computer and use it in GitHub Desktop.
Linear algebra for Rust implementation of K nearest Neighbors
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