Class: Brainz::Network

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input_size, hidden_sizes, output_size, options = {}) ⇒ Network

Returns a new instance of Network.



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/brainz/network.rb', line 7

def initialize(input_size, hidden_sizes, output_size, options = {})
  self.training_algorithm = :backpropagation

  @input = Layer.new(input_size + 1, self)
  @hidden = hidden_sizes.collect { |size| Layer.new(size, self) }
  @output = Layer.new(output_size, self)

  @learning_rate = options[:learning_rate] || 0.5
  @momentum = options[:momentum] || 0.15
  @mse = 0

  join_layers
end

Instance Attribute Details

#hiddenObject (readonly)

Returns the value of attribute hidden.



3
4
5
# File 'lib/brainz/network.rb', line 3

def hidden
  @hidden
end

#inputObject (readonly)

Returns the value of attribute input.



3
4
5
# File 'lib/brainz/network.rb', line 3

def input
  @input
end

#learning_rateObject

Returns the value of attribute learning_rate.



5
6
7
# File 'lib/brainz/network.rb', line 5

def learning_rate
  @learning_rate
end

#momentumObject

Returns the value of attribute momentum.



5
6
7
# File 'lib/brainz/network.rb', line 5

def momentum
  @momentum
end

#mseObject

Returns the value of attribute mse.



5
6
7
# File 'lib/brainz/network.rb', line 5

def mse
  @mse
end

#outputObject (readonly)

Returns the value of attribute output.



3
4
5
# File 'lib/brainz/network.rb', line 3

def output
  @output
end

#training_algorithmObject

Returns the value of attribute training_algorithm.



5
6
7
# File 'lib/brainz/network.rb', line 5

def training_algorithm
  @training_algorithm
end

Instance Method Details

#calculate_deltas(targets) ⇒ Object



34
35
36
37
38
39
40
41
# File 'lib/brainz/network.rb', line 34

def calculate_deltas(targets)
  output.neurons.each_with_index do |neuron, index|
    neuron.calculate_delta targets[index]
  end
  self.mse += output.calculate_mse(targets)

  hidden.last.calculate_deltas
end

#fix_weights(targets) ⇒ Object



43
44
45
46
# File 'lib/brainz/network.rb', line 43

def fix_weights(targets)
  calculate_deltas(targets)
  output.adjust_weights
end

#join_layersObject



21
22
23
24
25
# File 'lib/brainz/network.rb', line 21

def join_layers
  input.link_to(hidden.first)
  hidden.each_with_index { |layer, i| layer.link_to(hidden[i + 1]) if hidden[i + 1] }
  hidden.last.link_to(output)
end

#update(inputs) ⇒ Object



27
28
29
30
31
32
# File 'lib/brainz/network.rb', line 27

def update(inputs)
  inputs.each_with_index do |value, index|
    input.neurons[index].activation = value
  end
  input.update_forward
end