blob: 0c639117de16bbb6b064faefaa3b96d81ef099e2 (
plain)
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
|
use super::MetricElem;
use serde::{Deserialize, Serialize};
pub trait VecMetric: MetricElem + From<Vec<f32>> {}
#[derive(Deserialize, Serialize)]
pub struct CosineSimilarity(pub Vec<f32>);
#[derive(Deserialize, Serialize)]
pub struct EuclidianDistance(pub Vec<f32>);
#[derive(Deserialize, Serialize)]
pub struct ManhattenDistance(pub Vec<f32>);
impl VecMetric for CosineSimilarity {}
impl VecMetric for EuclidianDistance {}
impl VecMetric for ManhattenDistance {}
#[rustfmt::skip] impl From<Vec<f32>> for CosineSimilarity { fn from(value: Vec<f32>) -> Self { Self(value) } }
#[rustfmt::skip] impl From<Vec<f32>> for EuclidianDistance { fn from(value: Vec<f32>) -> Self { Self(value) } }
#[rustfmt::skip] impl From<Vec<f32>> for ManhattenDistance { fn from(value: Vec<f32>) -> Self { Self(value) } }
impl MetricElem for CosineSimilarity {
fn dist(&self, other: &Self) -> f64 {
let x = self
.0
.iter()
.zip(other.0.iter())
.map(|(a, b)| *a * *b)
.sum::<f32>();
let mag_a = self.0.iter().map(|x| x.powi(2)).sum::<f32>();
let mag_b = other.0.iter().map(|x| x.powi(2)).sum::<f32>();
(x / (mag_a * mag_b).sqrt()) as f64
}
}
impl MetricElem for EuclidianDistance {
fn dist(&self, other: &Self) -> f64 {
self.0
.iter()
.zip(other.0.iter())
.map(|(a, b)| (a - b).powf(2.))
.sum::<f32>()
.sqrt() as f64
}
}
impl MetricElem for ManhattenDistance {
fn dist(&self, other: &Self) -> f64 {
self.0
.iter()
.zip(other.0.iter())
.map(|(a, b)| (a - b).abs())
.sum::<f32>() as f64
}
}
|