Skip to content

Commit dd6aabd

Browse files
committed
cache lookups in innermost training loop
1 parent 86ae3fe commit dd6aabd

1 file changed

Lines changed: 9 additions & 7 deletions

File tree

neural_net.rb

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -91,16 +91,14 @@ def update_gradients training_error
9191
deltas = {}
9292
# Starting from output layer and working backwards, backpropagating the training error
9393
output_layer.downto(1).each do |layer|
94-
deltas[layer] = Array.new(@shape[layer])
95-
source_layer = layer - 1
96-
source_neurons = @shape[source_layer] + 1 # account for bias neuron
97-
target_layer = layer + 1
94+
deltas[layer] = []
9895

9996
@shape[layer].times do |neuron|
100-
10197
neuron_error = if layer == output_layer
10298
-training_error[neuron]
10399
else
100+
target_layer = layer + 1
101+
104102
weighted_target_deltas = deltas[target_layer].map.with_index do |target_delta, target_neuron|
105103
target_weight = @weights[target_layer][target_neuron][neuron]
106104
target_delta * target_weight
@@ -117,10 +115,14 @@ def update_gradients training_error
117115
# gradient for each of this neuron's incoming weights is calculated:
118116
# the last output from incoming source neuron (from -1 layer)
119117
# times this neuron's delta (calculated from error coming back from +1 layer)
118+
source_neurons = @shape[layer - 1] + 1 # account for bias neuron
119+
source_outputs = @outputs[layer - 1]
120+
gradients = @gradients[layer][neuron]
121+
120122
source_neurons.times do |source_neuron|
121-
source_output = @outputs[source_layer][source_neuron] || 1 # if no output, this is the bias neuron
123+
source_output = source_outputs[source_neuron] || 1 # if no output, this is the bias neuron
122124
gradient = source_output * delta
123-
@gradients[layer][neuron][source_neuron] += gradient # accumulate gradients from batch
125+
gradients[source_neuron] += gradient # accumulate gradients from batch
124126
end
125127
end
126128
end

0 commit comments

Comments
 (0)