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
use failure::Error;
use ndarray::Array2;
use ndarray_stats::QuantileExt;
use num::Float;
use std::fmt;
pub mod activate_functions;
#[derive(Default)]
pub struct NeuralNetwork<T> {
neurons: Array2<T>,
}
impl<T: Float + fmt::Display> fmt::Display for NeuralNetwork<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.neurons)
}
}
impl<T: Float + 'static> NeuralNetwork<T> {
pub fn new(init_neurons: Array2<T>) -> Result<Self, Error> {
if init_neurons.is_empty() {
return Err(failure::format_err!("the matrix is empty"));
}
Ok(NeuralNetwork::<T> {
neurons: init_neurons,
})
}
#[inline]
pub fn safe_next(
&mut self,
weight: &Array2<T>,
bias: &Array2<T>,
activate_function: &Box<dyn Fn(Array2<T>) -> Array2<T>>,
) -> Result<(), Error> {
match (self.neurons.dim(), weight.dim(), bias.dim()) {
((_, width1), (height, width2), (_, width3))
if width1 == height && width2 == width3 =>
{
Ok(self.next(weight, bias, activate_function))
}
_ => Err(failure::format_err!("Invalid argument")),
}
}
#[inline]
pub fn next(
&mut self,
weight: &Array2<T>,
bias: &Array2<T>,
activate_function: &Box<dyn Fn(Array2<T>) -> Array2<T>>,
) {
self.neurons = activate_function(self.neurons.dot(weight) + bias)
}
#[inline]
pub fn dim(&self) -> (ndarray::Ix, ndarray::Ix) {
self.neurons.dim()
}
#[inline]
pub fn argmax(&self) -> Vec<usize> {
self.neurons
.outer_iter()
.map(|x| x.argmax().unwrap())
.collect::<Vec<usize>>()
}
}