Skip to content

Commit 4092fb3

Browse files
committed
break out neuron_error calcuation
1 parent 48f94de commit 4092fb3

File tree

1 file changed

+11
-10
lines changed

1 file changed

+11
-10
lines changed

neural_net.rb

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -99,25 +99,26 @@ def update_gradients training_error
9999
target_layer = layer + 1
100100

101101
@shape[layer].times do |neuron|
102-
output = @outputs[layer][neuron]
103-
activation_derivative = output * (1.0 - output)
104102

105-
# calculate delta for neuron
106-
delta = deltas[layer][neuron] = if layer == output_layer
107-
# For neurons in output layer, use training error
108-
-training_error[neuron] * activation_derivative
103+
neuron_error = if layer == output_layer
104+
-training_error[neuron]
109105
else
110-
# For neurons in hidden layers, weight deltas from target layer
111106
weighted_target_deltas = deltas[target_layer].map.with_index do |target_delta, target_neuron|
112107
target_weight = @weights[target_layer][target_neuron][neuron]
113108
target_delta * target_weight
114109
end
115110

116-
sum_of_weighted_target_deltas = weighted_target_deltas.reduce(:+)
117-
activation_derivative * sum_of_weighted_target_deltas
111+
weighted_target_deltas.reduce(:+)
118112
end
119113

120-
# use delta to calculate gradients
114+
output = @outputs[layer][neuron]
115+
activation_derivative = output * (1.0 - output)
116+
117+
delta = deltas[layer][neuron] = neuron_error * activation_derivative
118+
119+
# gradient for each of this neuron's incoming weights is calculated:
120+
# the last output from incoming source neuron (from -1 layer)
121+
# times this neuron's delta (calculated from error coming back from +1 layer)
121122
source_neurons.times do |source_neuron|
122123
source_output = @outputs[source_layer][source_neuron] || 1 # if no output, this is the bias neuron
123124
gradient = source_output * delta

0 commit comments

Comments
 (0)