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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
extern crate num;
use self::num::traits::Float;
use matrix::*;
use vectors::group;
pub fn scan<D, T: Float>(m: &Matrix<T>, example: &[T], k: usize, df: D) -> Option<Vec<usize>>
where D : Fn(&[T], &[T]) -> T {
if example.len() != m.cols() {
return None;
}
let mut near: Vec<(usize, T)> = Vec::with_capacity(k);
for (idx, row) in m.row_iter().enumerate() {
let d = df(row, example);
let p = near.iter().position(|&(_, val)| val > d);
match p {
Some(pos) => {
near.insert(pos, (idx, d));
if near.len() > k {
near.pop();
}
}
_ => {
if idx < k {
near.push((idx, d))
}
}
}
}
Some(near.iter().map(|&(idx, _)| idx.clone()).collect())
}
pub fn classify<T, L, D>(m: &Matrix<T>, labels: &Vec<L>, example: &[T], k: usize, df: D) -> L
where T: Float, L: Clone + Ord, D: Fn(&[T], &[T]) -> T {
let idx = scan(&m, example, k, df).unwrap();
let mut targets: Vec<L> = idx.iter().map(|pos| labels.get(*pos).unwrap()).cloned().collect();
targets.sort_by(|a, b| a.cmp(&b));
let mut r = group(&targets);
r.sort_by(|a, b| a.1.cmp(&b.1));
r.last().unwrap().0.clone()
}
#[cfg(test)]
mod tests {
use super::*;
use matrix::*;
use distance::*;
#[test]
fn test_knn_classify() {
let m = mat![
1.0, 2.0;
1.1, 2.1;
2.0, 3.0;
0.9, 1.9;
2.1, 2.9
];
let labels = vec![1, 2, 2, 1, 2];
let target = classify(&m, &labels, &[1.3, 2.0], 3, |x, y| Euclid::compute(x, y).unwrap());
assert_eq!(target, 1);
}
#[test]
fn test_scan() {
let mut m = mat![
1.0, 2.0;
2.0, 2.0;
3.0, 3.0
];
let a = scan(&m, &[1.0, 1.0, 2.0], 1, |x, y| Euclid::compute(x, y).unwrap());
assert!(a.is_none());
let mut label = scan(&m, &[1.0, 1.0], 1, |x, y| Euclid::compute(x, y).unwrap()).unwrap();
assert_eq!(label, vec![0]);
label = scan(&m, &[1.0, 2.0], 1, |x, y| Euclid::compute(x, y).unwrap()).unwrap();
assert_eq!(label, vec![0]);
label = scan(&m, &[2.0, 2.2], 1, |x, y| Euclid::compute(x, y).unwrap()).unwrap();
assert_eq!(label, vec![1]);
label = scan(&m, &[5.0, 6.0], 1, |x, y| Euclid::compute(x, y).unwrap()).unwrap();
assert_eq!(label, vec![2]);
m = mat![
1.0, 2.0;
1.3, 1.8;
1.2, 2.1;
2.0, 2.0
];
label = scan(&m, &[1.1, 2.0], 1, |x, y| Euclid::compute(x, y).unwrap()).unwrap();
assert_eq!(label, vec![0]);
label = scan(&m, &[1.1, 2.0], 2, |x, y| Euclid::compute(x, y).unwrap()).unwrap();
assert_eq!(label, vec![0, 2]);
label = scan(&m, &[1.1, 2.0], 3, |x, y| Euclid::compute(x, y).unwrap()).unwrap();
assert_eq!(label, vec![0, 2, 1]);
label = scan(&m, &[1.1, 2.0], 4, |x, y| Euclid::compute(x, y).unwrap()).unwrap();
assert_eq!(label, vec![0, 2, 1, 3]);
}
}