|
| 1 | +use crate::{ |
| 2 | + ml::neural_network::Neuron, |
| 3 | + util::types::{ |
| 4 | + InstanceInput, |
| 5 | + NeuralNetworkLayer, |
| 6 | + ProblemSet |
| 7 | + } |
| 8 | +}; |
| 9 | + |
| 10 | +use rand::Rng; |
| 11 | + |
| 12 | +pub struct NeuralNetwork { |
| 13 | + pub layers: Vec<NeuralNetworkLayer>, |
| 14 | + test_instances: usize, |
| 15 | + tests_correct: usize, |
| 16 | + pub update_bias: bool, |
| 17 | + pub mse: f32 |
| 18 | +} |
| 19 | + |
| 20 | +impl NeuralNetwork { |
| 21 | + pub fn new(layout: Vec<usize>, learning_rate: f32, feature_amount: usize) -> Self { |
| 22 | + let mut layers = Vec::with_capacity(layout.len()); |
| 23 | + let mut rng = rand::thread_rng(); |
| 24 | + // The initial input is the features themselves |
| 25 | + let mut next_input_size = feature_amount; |
| 26 | + |
| 27 | + // Find the size of each layer |
| 28 | + for node_amount in layout { |
| 29 | + // Auto generate a bias [0.0, 1.0] |
| 30 | + let bias = rng.gen(); |
| 31 | + let mut layer = Vec::with_capacity(node_amount); |
| 32 | + |
| 33 | + // Instantiate the correct amount of neurons for this layer |
| 34 | + for _ in 0..node_amount { |
| 35 | + // Make sure the amount of weights equals the size of the input to this layer |
| 36 | + let mut weights = Vec::with_capacity(next_input_size); |
| 37 | + |
| 38 | + // Auto generate weights [0.0, 1.0] |
| 39 | + for _ in 0..next_input_size { |
| 40 | + weights.push(rng.gen()); |
| 41 | + } |
| 42 | + |
| 43 | + // Instantiate neuron |
| 44 | + let node = Neuron::new(weights, bias, learning_rate); |
| 45 | + layer.push(node); |
| 46 | + } |
| 47 | + |
| 48 | + // Add layer to network along with its associated generated bias value |
| 49 | + layers.push(layer); |
| 50 | + // The size of the next input is the size of this layers output |
| 51 | + next_input_size = node_amount; |
| 52 | + } |
| 53 | + |
| 54 | + Self { |
| 55 | + layers, |
| 56 | + test_instances: 0, |
| 57 | + tests_correct: 0, |
| 58 | + update_bias: true, |
| 59 | + mse: 0.0 |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + fn feed_forward(&mut self, instance: InstanceInput) { |
| 64 | + let mut this_input = instance; |
| 65 | + |
| 66 | + for nodes in &mut self.layers { |
| 67 | + let mut next_input = Vec::with_capacity(nodes.len()); |
| 68 | + |
| 69 | + for node in nodes { |
| 70 | + node.calc_activity(this_input.clone()); |
| 71 | + node.calc_activation(); |
| 72 | + |
| 73 | + // The output of this node is an input to the next layer |
| 74 | + next_input.push(node.activation); |
| 75 | + } |
| 76 | + |
| 77 | + // The outputs of this layer is the inputs of the next layer |
| 78 | + this_input = next_input; |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + fn back_propagation(&mut self, expected_output: f32) { |
| 83 | + let mut is_output_layer = true; |
| 84 | + let mut error_sum_vec: Vec<f32>; |
| 85 | + let mut next_error_sum_vec: Vec<f32> = vec![]; |
| 86 | + |
| 87 | + // For every layer, working backwards |
| 88 | + for layer in &mut self.layers.iter_mut().rev() { |
| 89 | + error_sum_vec = next_error_sum_vec; |
| 90 | + next_error_sum_vec = Vec::with_capacity(layer.len()); |
| 91 | + |
| 92 | + // Make sure the vector has enough elements |
| 93 | + for _ in 0..layer[0].get_weights().len() { |
| 94 | + next_error_sum_vec.push(0.0); |
| 95 | + } |
| 96 | + |
| 97 | + for node in layer { |
| 98 | + if is_output_layer { |
| 99 | + node.calc_delta_weights(expected_output - node.activation); |
| 100 | + } else { |
| 101 | + node.calc_delta_weights(error_sum_vec.remove(0)); |
| 102 | + } |
| 103 | + |
| 104 | + // Determine the appropriate error value for the next iteration |
| 105 | + for index in 0..next_error_sum_vec.len() { |
| 106 | + next_error_sum_vec[index] += node.weights[index] * node.delta; |
| 107 | + } |
| 108 | + |
| 109 | + // Find the delta for the weight associated with the bias |
| 110 | + node.calc_delta_bias() |
| 111 | + } |
| 112 | + |
| 113 | + is_output_layer = false; |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + /// All the weights need to be updated at the same time |
| 118 | + /// So here we update the weights based off of the calculated deltas |
| 119 | + fn update_weights(&mut self) { |
| 120 | + for layer in &mut self.layers { |
| 121 | + for node in layer { |
| 122 | + node.update_weights(); |
| 123 | + |
| 124 | + if self.update_bias { |
| 125 | + node.update_bias(); |
| 126 | + } |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + // TODO: Figure out later |
| 132 | + // pub fn train(&mut self, training_set: ProblemSet, epochs: usize, is_online: bool) { |
| 133 | + // for _ in 0..epochs { |
| 134 | + // for (training_instance, expected_output) in training_set.clone() { |
| 135 | + // // Feed Forward |
| 136 | + // self.feed_forward(training_instance); |
| 137 | + // |
| 138 | + // // Back Propagation |
| 139 | + // self.back_propagation(expected_output); |
| 140 | + // |
| 141 | + // // Update weights |
| 142 | + // if is_online { |
| 143 | + // self.update_weights(); |
| 144 | + // } |
| 145 | + // } |
| 146 | + // |
| 147 | + // if !is_online { |
| 148 | + // self.update_weights(); |
| 149 | + // } |
| 150 | + // } |
| 151 | + // } |
| 152 | + |
| 153 | + pub fn test(&mut self, test_instance: Vec<f32>, maybe_threshold: Option<f32>) -> Vec<f32> { |
| 154 | + self.feed_forward(test_instance); |
| 155 | + |
| 156 | + self.layers |
| 157 | + .last() |
| 158 | + .unwrap() |
| 159 | + .iter() |
| 160 | + .map(|neuron| neuron.activation) |
| 161 | + .collect::<Vec<f32>>() |
| 162 | + } |
| 163 | + |
| 164 | + pub fn print(&self) { |
| 165 | + for layer in &self.layers { |
| 166 | + println!("********************"); |
| 167 | + for neuron in layer { |
| 168 | + println!("Bias: {}", neuron.bias); |
| 169 | + println!("{:?}", neuron.get_weights()); |
| 170 | + } |
| 171 | + println!("********************"); |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + pub fn accuracy(&self, is_classification: bool) -> Option<f32> { |
| 176 | + if self.test_instances == 0 { |
| 177 | + None |
| 178 | + } else { |
| 179 | + if is_classification { |
| 180 | + Some((self.tests_correct as f32 / self.test_instances as f32) * 100.0) |
| 181 | + } else { |
| 182 | + Some(self.mse) |
| 183 | + } |
| 184 | + } |
| 185 | + } |
| 186 | + |
| 187 | + pub fn get_output(&self) -> Vec<f32> { |
| 188 | + self.layers[self.layers.len() - 1].iter().map(|node| node.activation).collect::<Vec<f32>>() |
| 189 | + } |
| 190 | +} |
0 commit comments