neuronet 6.1.0 → 8.0.251113

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Neuronet
4
+ # Output Neuron
5
+ class OutputNeuron
6
+ include NeuronStats
7
+ include Backpropagate
8
+
9
+ def initialize
10
+ @bias = 0.0
11
+ @connections = []
12
+ end
13
+
14
+ attr_accessor :bias
15
+ attr_reader :connections
16
+
17
+ def activation = nil
18
+
19
+ def connect(neuron, weight = 0.0)
20
+ @connections << Connection.new(neuron, weight)
21
+ end
22
+
23
+ def value
24
+ @bias + @connections.sum(&:value)
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Neuronet
4
+ # Perceptron
5
+ class Perceptron
6
+ include NetworkStats
7
+ include Exportable
8
+ include Trainable
9
+ include Arrayable
10
+
11
+ def initialize(input_size, output_size,
12
+ input_neuron: InputNeuron, output_neuron: OutputNeuron)
13
+ @input_layer = InputLayer.new(input_size, input_neuron:)
14
+ @output_layer = OutputLayer.new(output_size, output_neuron:)
15
+ @output_layer.connect(@input_layer)
16
+ end
17
+
18
+ attr_reader :input_layer, :output_layer
19
+
20
+ def set(values)
21
+ @input_layer.set(values)
22
+ end
23
+
24
+ def values
25
+ @output_layer.values
26
+ end
27
+
28
+ def *(other)
29
+ set(other)
30
+ values
31
+ end
32
+
33
+ def to_a = [@input_layer, @output_layer]
34
+ end
35
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Neuronet
4
+ # Squash provides logistic sigmoid function.
5
+ module Squash
6
+ # Logistic sigmoid: maps Real to (0, 1).
7
+ def squash(value) = 1.0 / (1.0 + Math.exp(-value))
8
+ # Inverse sigmoid: maps (0, 1) to Real.
9
+ def unsquash(activation) = Math.log(activation / (1.0 - activation))
10
+ module_function :squash, :unsquash
11
+ end
12
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Neuronet
4
+ # Trainable adds error backpropagation and training.
5
+ module Trainable
6
+ def pairs(pairs, nju: expected_nju)
7
+ pairs.shuffle.each { |inputs, targets| train(inputs, targets, nju:) }
8
+ end
9
+
10
+ def train(inputs, targets, nju:)
11
+ actuals = self * inputs
12
+ errors = targets.zip(actuals).map { |target, actual| target - actual }
13
+ error, index = pivot(errors)
14
+ neuron = output_layer[index]
15
+ neuron.backpropagate(error / nju)
16
+ end
17
+
18
+ def pivot(errors)
19
+ error = index = 0.0
20
+ errors.each_with_index do |e, i|
21
+ next unless e.abs > error.abs
22
+
23
+ error = e
24
+ index = i
25
+ end
26
+ [error, index]
27
+ end
28
+ end
29
+ end