Class: SimpleNeuralNetwork::Layer

Inherits:
Object
  • Object
show all
Defined in:
lib/layer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(size, network) ⇒ Layer

Returns a new instance of Layer.



16
17
18
19
20
21
22
23
24
25
# File 'lib/layer.rb', line 16

def initialize(size, network)
  @size = size
  @neurons = []
  @network = network

  @prev_layer = nil
  @next_layer = nil

  populate_neurons
end

Instance Attribute Details

#networkObject

Returns the value of attribute network.



14
15
16
# File 'lib/layer.rb', line 14

def network
  @network
end

#neuronsObject

List of ##size neurons



12
13
14
# File 'lib/layer.rb', line 12

def neurons
  @neurons
end

#next_layerObject

Returns the value of attribute next_layer.



9
10
11
# File 'lib/layer.rb', line 9

def next_layer
  @next_layer
end

#prev_layerObject

Returns the value of attribute prev_layer.



8
9
10
# File 'lib/layer.rb', line 8

def prev_layer
  @prev_layer
end

#sizeObject

Number of neurons



6
7
8
# File 'lib/layer.rb', line 6

def size
  @size
end

Instance Method Details

#get_outputObject

The method that drives network output resolution. get_output calculates the array of neuron values for this layer. This is calculated by recursively fetching the output from the previous layer, then applying edge/node weight and bias rules. The first layer will fetch it’s values from @network.inputs



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
# File 'lib/layer.rb', line 31

def get_output
  if !prev_layer
    # This is the first layer, so the output set is simply the network input set
    @network.inputs
  else
    # Each neuron output value is calculated by:
    # output[i] = (
    #                (prev_layer.neurons[0] * prev_layer.neurons[0].edges[i])
    #              + (prev_layer.neurons[1] * prev_layer.neurons[1].edges[i])
    #              + ...
    #             ) + self.neurons[i].bias

    prev_layer_output = prev_layer.get_output

    # Generate the output values for the layer
    (0..@size-1).map do |i|
      value = 0

      prev_layer_output.each_with_index do |output, index|
        value += (output * prev_layer.neurons[index].edges[i])
      end

     value + @neurons[i].bias
    end
  end
end

#initialize_neuron_edgesObject



58
59
60
61
62
63
64
# File 'lib/layer.rb', line 58

def initialize_neuron_edges
  return unless @next_layer

  @neurons.each do |neuron|
    neuron.initialize_edges(@next_layer.size)
  end
end