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
use crate::{
basis::Composable,
core::{Features, Projector},
geometry::{Card, Space},
};
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub struct Constant {
n_features: usize,
value: f64,
}
impl Constant {
pub fn new(n_features: usize, value: f64) -> Self {
Constant {
n_features: n_features,
value: value,
}
}
pub fn zeros(n_features: usize) -> Self { Constant::new(n_features, 0.0) }
pub fn ones(n_features: usize) -> Self { Constant::new(n_features, 1.0) }
}
impl Space for Constant {
type Value = Features;
fn dim(&self) -> usize { self.n_features }
fn card(&self) -> Card { unimplemented!() }
}
impl<I: ?Sized> Projector<I> for Constant {
fn project(&self, _: &I) -> Features { vec![self.value; self.n_features].into() }
}
impl Composable for Constant {}
#[derive(Clone)]
pub struct Indices {
n_features: usize,
active_features: Vec<usize>,
}
impl Indices {
pub fn new(n_features: usize, active_features: Vec<usize>) -> Self {
Indices {
n_features,
active_features,
}
}
}
impl Space for Indices {
type Value = Features;
fn dim(&self) -> usize { self.n_features }
fn card(&self) -> Card { unimplemented!() }
}
impl<I: ?Sized> Projector<I> for Indices {
fn project(&self, _: &I) -> Features { self.active_features.iter().cloned().collect() }
}
impl Composable for Indices {}
#[cfg(test)]
mod tests {
use super::*;
use quickcheck::quickcheck;
#[test]
fn test_project_zeros() {
fn prop_output(length: usize, input: Vec<f64>) -> bool {
match Constant::zeros(length).project(&input) {
Features::Sparse(_) => false,
Features::Dense(activations) => {
activations.len() == length && activations.into_iter().all(|&v| v == 0.0)
},
}
}
quickcheck(prop_output as fn(usize, Vec<f64>) -> bool);
}
#[test]
fn test_project_ones() {
fn prop_output(length: usize, input: Vec<f64>) -> bool {
match Constant::ones(length).project(&input) {
Features::Sparse(_) => false,
Features::Dense(activations) => {
activations.len() == length && activations.into_iter().all(|&v| v == 1.0)
},
}
}
quickcheck(prop_output as fn(usize, Vec<f64>) -> bool);
}
#[test]
fn test_project_general() {
fn prop_output(length: usize, value: f64, input: Vec<f64>) -> bool {
match Constant::new(length, value).project(&input) {
Features::Sparse(_) => false,
Features::Dense(activations) => {
activations.len() == length && activations.into_iter().all(|&v| v == value)
},
}
}
quickcheck(prop_output as fn(usize, f64, Vec<f64>) -> bool);
}
}