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.



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

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)

layers



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

def hidden
  @hidden
end

#inputObject (readonly)

layers



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

def input
  @input
end

#learning_rateObject

Returns the value of attribute learning_rate.



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

def learning_rate
  @learning_rate
end

#momentumObject

Returns the value of attribute momentum.



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

def momentum
  @momentum
end

#mseObject

Returns the value of attribute mse.



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

def mse
  @mse
end

#outputObject (readonly)

layers



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

def output
  @output
end

#training_algorithmObject

Returns the value of attribute training_algorithm.



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

def training_algorithm
  @training_algorithm
end

Instance Method Details

#calculate_deltas(targets) ⇒ Object



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

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



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

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

#join_layersObject



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

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



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

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