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
use std::sync::{Mutex, Arc};
use std::fmt;
use std::ops::DerefMut;
use ops::{OpInstance};
use id::OpID;
use ndarray::ArrayViewMutD;
use rand::{thread_rng, Isaac64Rng, SeedableRng};
use rand::distributions::{Distribution, Normal, Range};
#[derive(Clone)]
pub struct Initialiser {
name: String,
func: Arc<Mutex<FnMut(ArrayViewMutD<f32>, Option<&OpInstance>)>>,
op_id: Option<OpID>,
}
impl Initialiser {
pub fn new<F: 'static + FnMut(ArrayViewMutD<f32>, Option<&OpInstance>)>(name: String, func: F) -> Self {
Initialiser {
name: name,
func: Arc::new(Mutex::new(func)),
op_id: None,
}
}
pub fn wrap(name: String, func: Arc<Mutex<FnMut(ArrayViewMutD<f32>, Option<&OpInstance>)>>) -> Self {
Initialiser {
name: name,
func: func,
op_id: None,
}
}
pub fn gaussian(mean: f32, std_dev: f32) -> Initialiser {
Initialiser::new("Gaussian Initialiser".to_string(), move |mut arr: ArrayViewMutD<f32>, _instance: Option<&OpInstance>|{
let mut rng = Isaac64Rng::from_rng(thread_rng()).unwrap();
let norm = Normal::new(mean as f64, std_dev as f64);
for e in arr.iter_mut() {
*e = norm.sample(&mut rng) as f32;
}
})
}
pub fn uniform(low: f32, high: f32) -> Initialiser {
Initialiser::new("Uniform Initialiser".to_string(), move |mut arr: ArrayViewMutD<f32>, _instance: Option<&OpInstance>|{
let mut rng = Isaac64Rng::from_rng(thread_rng()).unwrap();
let rang = Range::new(low, high);
for e in arr.iter_mut() {
*e = rang.sample(&mut rng) as f32;
}
})
}
pub fn fill(val: f32) -> Initialiser {
Initialiser::new("Fill Initialiser".to_string(), move |mut arr: ArrayViewMutD<f32>, _instance: Option<&OpInstance>|{
for e in arr.iter_mut() {
*e = val;
}
})
}
pub fn call(&self, arr: ArrayViewMutD<f32>, op: Option<&OpInstance>) {
let mut guard = self.func.lock().expect(&format!("Could not acquire lock on initialiser: {:?}", self));
guard.deref_mut()(arr, op);
}
pub fn set_op_id(mut self, op_id: OpID) -> Self {
self.op_id = Some(op_id);
self
}
pub fn clear_op_id(mut self) -> Self {
self.op_id = None;
self
}
pub fn op_id(&self) -> Option<OpID> {
self.op_id.clone()
}
}
impl fmt::Debug for Initialiser {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Initialiser {{ name: {}, .. }}", self.name)
}
}