-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlayer.go
138 lines (114 loc) · 2.49 KB
/
layer.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
package main
import (
"math"
"math/rand"
)
type Layer struct {
Units int
Output []float64
Error []float64
Weights [][]float64
sWeights [][]float64
ΔWeights [][]float64
}
func NewLayer(prev, no int) *Layer {
var (
o, e []float64
w, sw, Δw [][]float64
)
units := numUnits[no]
pUnits := numUnits[prev]
if prev >= 0 {
w = make([][]float64, units)
sw = make([][]float64, units)
Δw = make([][]float64, units)
for i := 0; i < len(w); i++ {
w[i] = make([]float64, pUnits)
sw[i] = make([]float64, pUnits)
Δw[i] = make([]float64, pUnits)
}
}
o = make([]float64, units)
e = make([]float64, units)
return &Layer{
Units: units,
Output: o,
Error: e,
Weights: w,
sWeights: sw,
ΔWeights: Δw,
}
}
func (l *Layer) initializeWeight(prev *Layer) {
for j := 1; j < l.Units; j++ {
for k := 0; k < prev.Units; k++ {
l.Weights[j][k] = -0.5 + rand.Float64()
}
}
}
func (l *Layer) saveWeight(prev *Layer) {
for j := 1; j < l.Units; j++ {
for k := 0; k < prev.Units; k++ {
l.sWeights[j][k] = l.Weights[j][k]
}
}
}
func (l *Layer) restoreWeight(prev *Layer) {
for j := 1; j < l.Units; j++ {
for k := 0; k < prev.Units; k++ {
l.Weights[j][k] = l.sWeights[j][k]
}
}
}
func (l *Layer) adjustWeight(prev *Layer, α, η float64) {
for j := 1; j < l.Units; j++ {
for k := 0; k < prev.Units; k++ {
o := prev.Output[k]
e := l.Error[j]
Δw := l.ΔWeights[j][k]
l.Weights[j][k] = η*e*o + α*Δw
l.ΔWeights[j][k] = η * e * o
}
}
}
func (l *Layer) setInput(in []float64) {
for i := 1; i <= l.Units; i++ {
l.Output[i] = in[i-1]
}
}
func (l *Layer) getOutput() []float64 {
out := make([]float64, 0)
for i := 1; i < l.Units; i++ {
out[i-1] = l.Output[i]
}
return out
}
func (l *Layer) computeError(targets []float64, gain float64) float64 {
sum := 0.0
for i := 1; i < l.Units; i++ {
o := l.Output[i]
e := targets[i-1] - o
l.Error[i] = gain * o * (1 - o) * e
sum += 0.5 * math.Sqrt(e)
}
return sum
}
func (l *Layer) propagate(next *Layer, gain float64) {
for i := 1; i <= next.Units; i++ {
sum := 0.0
for j := 0; j <= l.Units; j++ {
sum += next.Weights[i][j] * l.Output[j]
}
next.Output[i] = 1 / (1 + math.Exp(-1*gain*sum))
}
}
func (l *Layer) backPropagate(prev *Layer, gain float64) {
for i := 1; i <= prev.Units; i++ {
output := prev.Output[i]
error := 0.0
for j := 1; j <= l.Units; j++ {
error += l.Weights[j][i] * l.Error[j]
}
prev.Error[i] = gain * output * (1 - output) * error
}
}