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
142
143
144
145
146
use std::iter::Iterator;
use rand;
use rand::{Rng, StdRng};
pub struct CrossValidation {
n_samples: usize,
n_folds: usize,
indices: Vec<usize>,
iter: usize,
rng: StdRng,
}
impl CrossValidation {
pub fn new(n_samples: usize, n_folds: usize) -> CrossValidation {
assert!(n_folds < n_samples,
"Number of folds must be smaller than number of samples");
assert!(n_folds > 1, "Number of folds must be greater than one");
let mut indices = (0..n_samples).collect::<Vec<_>>();
let mut rng = rand::StdRng::new().unwrap();
rng.shuffle(&mut indices);
CrossValidation {
n_samples: n_samples,
n_folds: n_folds,
indices: indices,
iter: 0,
rng: rng,
}
}
pub fn set_rng(&mut self, rng: rand::StdRng) {
self.rng = rng;
self.indices = (0..self.n_samples).collect::<Vec<_>>();
self.rng.shuffle(&mut self.indices);
}
}
impl Iterator for CrossValidation {
type Item = (Vec<usize>, Vec<usize>);
fn next(&mut self) -> Option<(Vec<usize>, Vec<usize>)> {
let ret = if self.iter < self.n_folds {
let fold_step = self.n_samples / self.n_folds;
let validation_start = self.iter * fold_step;
let validation_stop = (self.iter + 1) * fold_step;
let train = (0..validation_start)
.chain(validation_stop..self.indices.len())
.map(|i| self.indices[i])
.collect::<Vec<_>>();
let test = (validation_start..validation_stop)
.map(|i| self.indices[i])
.collect::<Vec<_>>();
Some((train, test))
} else {
None
};
self.iter += 1;
ret
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
extern crate rand;
#[test]
fn cross_validate_iteration() {
let split = CrossValidation::new(100, 4);
let mut count = 0;
for _ in split {
count += 1;
}
assert!(count == 4);
}
#[test]
fn cross_validate_size_split() {
let split = CrossValidation::new(100, 4);
for (train, test) in split {
let mut set = HashSet::new();
assert!(train.len() == 75);
assert!(test.len() == 25);
for idx in train.iter().chain(test.iter()) {
set.insert(idx);
}
assert!(set.len() == 100);
}
}
}