/
perceptron.go
247 lines (215 loc) · 6.89 KB
/
perceptron.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
// Package goceptron is a more-or-less complete package to manage a perceptron
package goceptron
import (
"encoding/gob"
"fmt"
"math"
"math/rand"
"os"
"time"
)
// Neuron struct, contains the neuron Value, and the Weights coming out frmo this neuron
type Neuron struct {
Value float64
Weights []float64
}
// Layer struct, contains the Position of the layer in the perceptron, the number of Neurons in it, and the list of the Neurons in the layer
type Layer struct {
Position int
Size int
Neurons []Neuron
Biases []float64
}
// Perceptron struct, contains the number of Layers, and the list of Layers in the perceptron
type Perceptron struct {
LayerNb int
Layers []Layer
}
// Init initializes the perceptron
func (p *Perceptron) Init(inputLayersize int, hiddenLayersSizes []int, outputLayersize int) {
// Create Layers
p.AddLayer(inputLayersize)
for _, Size := range hiddenLayersSizes {
p.AddLayer(Size)
}
p.AddLayer(outputLayersize)
randSource := rand.NewSource(time.Now().UnixNano())
rand := rand.New(randSource)
// Create Weights
for il, l := range p.Layers {
// If not the last layer
if l.Position != p.LayerNb-1 {
nextLayersize := p.Layers[il+1].Size
// For each neuron
for in := range l.Neurons {
// Create slice of Weights
p.Layers[il].Neurons[in].Weights = make([]float64, nextLayersize)
// Initialize each weight
for iw := range p.Layers[il].Neurons[in].Weights {
p.Layers[il].Neurons[in].Weights[iw] = rand.Float64() / float64(l.Size+1)
}
}
// Initialize bias
for ib := 0; ib < nextLayersize; ib++ {
p.Layers[il].Biases[ib] = rand.Float64() / float64(l.Size+1)
}
}
}
for il := range p.Layers {
p.Layers[il].Position = 10
}
}
// AddLayer adds a layer containing <Size> Neurons to the Perceptron
func (p *Perceptron) AddLayer(Size int) {
if Size > 0 {
Neurons := make([]Neuron, Size)
p.Layers = append(p.Layers, Layer{p.LayerNb, Size, Neurons, []float64{}})
p.LayerNb++
}
if p.LayerNb > 1 {
p.Layers[p.LayerNb-2].Biases = make([]float64, p.Layers[p.LayerNb-1].Size)
}
}
// CalculateLayer calculates the new neuron Values of the layer which have the Position <layerPos> in the perceptron
// The activation function is a sigmoid
func (p *Perceptron) CalculateLayer(layerPos int) {
activation := func(input float64) float64 {
return 1 / (1 + math.Exp(-input))
}
p.CalculateLayerCustom(layerPos, activation)
}
// CalculateLayerCustom calculates the new neuron Values of the layer which have the Position <layerPos> in the perceptron
// The activation function is given as a parameter
func (p *Perceptron) CalculateLayerCustom(layerPos int, fn func(float64) float64) {
if layerPos > 0 {
layer := p.Layers[layerPos]
prevLayer := p.Layers[layerPos-1]
sum := make([]float64, layer.Size)
for in := range layer.Neurons {
for _, pn := range prevLayer.Neurons {
sum[in] += pn.Value * pn.Weights[in]
}
sum[in] += prevLayer.Biases[in]
p.Layers[layerPos].Neurons[in].Value = fn(sum[in])
}
}
}
// ComputeFromInput computes new neuron Values, except for the first layer
// The activation function is a sigmoid
func (p *Perceptron) ComputeFromInput() {
activation := func(input float64) float64 {
return 1 / (1 + math.Exp(-input))
}
p.ComputeFromInputCustom(activation)
}
// ComputeFromInputCustom computes new neuron Values, except for the first layer
// The activation function is given as a parameter
func (p *Perceptron) ComputeFromInputCustom(fn func(float64) float64) {
for i := 1; i < p.LayerNb; i++ {
p.CalculateLayerCustom(i, fn)
}
}
// Backpropagation makes the perceptron learn by modifying the Weights on all Neurons
func (p *Perceptron) Backpropagation(expected []float64, eta float64) (outputError float64) {
derivative := func(input float64) float64 {
return input * (1 - input)
}
return p.BackpropagationCustom(expected, eta, derivative)
}
// BackpropagationCustom makes the perceptron learn by modifying the Weights on all Neurons
// The derivative of the activation function is given as parameter
func (p *Perceptron) BackpropagationCustom(expected []float64, eta float64, fn func(float64) float64) (outputError float64) {
var (
diff float64
delta [][]float64
)
delta = make([][]float64, p.LayerNb-1)
// Calculate error and delta for the output layer
delta[p.LayerNb-2] = make([]float64, p.Layers[p.LayerNb-1].Size)
for in, n := range p.Layers[p.LayerNb-1].Neurons {
diff = expected[in] - n.Value
delta[p.LayerNb-2][in] = fn(n.Value) * diff
outputError += math.Pow(diff, 2)
}
// Calculates delta for all hidden Layers
// delta[il-1] is the delta for the layer with Position il (since the input layer doesn't have a delta)
for il := p.LayerNb - 2; il > 0; il-- {
layer := p.Layers[il]
delta[il-1] = make([]float64, layer.Size)
for in, n := range layer.Neurons {
for inn := range p.Layers[il+1].Neurons {
delta[il-1][in] += n.Weights[inn] * delta[il][inn]
}
delta[il-1][in] = fn(n.Value) * delta[il-1][in]
}
}
// Update Weights for hidden & input Layers, as well as Biases
for il := p.LayerNb - 2; il >= 0; il-- {
layer := p.Layers[il]
for in, n := range layer.Neurons {
for inn := range p.Layers[il+1].Neurons {
p.Layers[il].Neurons[in].Weights[inn] += eta * delta[il][inn] * n.Value
}
}
for ib := range layer.Biases {
p.Layers[il].Biases[ib] += eta * delta[il][ib]
}
}
return
}
// TryRecognition tests the rate of recognition of the values in the input neurons
// The activation function is a sigmoid
func (p Perceptron) TryRecognition(expected int) (float64, bool) {
activation := func(input float64) float64 {
return 1 / (1 + math.Exp(-input))
}
return p.TryRecognitionCustom(expected, activation)
}
// TryRecognitionCustom tests the rate of recognition of the values in the input neurons
// The activation function is given as a parameter
func (p Perceptron) TryRecognitionCustom(expected int, fn func(float64) float64) (float64, bool) {
var (
sum float64
max float64
imax int
lastLayerNeurons []Neuron
)
p.ComputeFromInputCustom(fn)
lastLayerNeurons = p.Layers[p.LayerNb-1].Neurons
for in, n := range lastLayerNeurons {
sum += n.Value
if n.Value > max {
max = n.Value
imax = in
}
}
return lastLayerNeurons[expected].Value / sum, (imax == expected)
}
// SaveToFile saves the perceptron to a given file
func (p Perceptron) SaveToFile(path string) (err error) {
file, err := os.Create(path)
if err == nil {
encoder := gob.NewEncoder(file)
encoder.Encode(p)
}
file.Close()
return
}
// LoadFromFile loads the perceptron from a given file
func (p *Perceptron) LoadFromFile(path string) (err error) {
file, err := os.Open(path)
if err == nil {
decoder := gob.NewDecoder(file)
err = decoder.Decode(p)
}
file.Close()
return
}
// Println prints neuron Values in layer
func (l Layer) Println() {
Values := make([]float64, l.Size)
for i, n := range l.Neurons {
Values[i] = n.Value
}
fmt.Println(Values)
}