forked from sjwhitworth/golearn
/
layered.go
345 lines (299 loc) · 9.23 KB
/
layered.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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
package neural
import (
"fmt"
"github.com/antongulenko/golearn/base"
"github.com/antongulenko/golearn/filters"
"gonum.org/v1/gonum/mat"
"math"
"math/rand"
)
// MultiLayerNet creates a new Network which is conceptually
// organised into layers, zero or more of which are hidden.
//
// Within each layer, no neurons are connected.
//
// No neurons in a given layer are connected with any neurons
// in a previous layer.
//
// Neurons can only be connected to neurons in the layer above.
type MultiLayerNet struct {
network *Network
attrs map[base.Attribute]int
layers []int
classAttrOffset int
classAttrCount int
Convergence float64
MaxIterations int
LearningRate float64
}
// NewMultiLayerNet returns an underlying
// Network conceptuallyorganised into layers
//
// Layers variable = slice of integers representing
// node count at each layer.
func NewMultiLayerNet(layers []int) *MultiLayerNet {
return &MultiLayerNet{
nil,
make(map[base.Attribute]int),
layers,
0,
0,
0.001,
500,
0.90,
}
}
// String returns a human-readable summary of this network.
func (m *MultiLayerNet) String() string {
return fmt.Sprintf("MultiLayerNet(%v, %v, %f, %f, %d", m.layers, m.network, m.Convergence, m.LearningRate, m.MaxIterations)
}
func (m *MultiLayerNet) convertToFloatInsts(X base.FixedDataGrid) base.FixedDataGrid {
// Make sure everything's a FloatAttribute
fFilt := filters.NewFloatConvertFilter()
for _, a := range X.AllAttributes() {
fFilt.AddAttribute(a)
}
fFilt.Train()
insts := base.NewLazilyFilteredInstances(X, fFilt)
return insts
}
// Predict uses the underlying network to produce predictions for the
// class variables of X.
//
// Can only predict one CategoricalAttribute at a time, or up to n
// FloatAttributes. Set or unset ClassAttributes to work around this
// limitation.
func (m *MultiLayerNet) Predict(X base.FixedDataGrid) base.FixedDataGrid {
// Create the return vector
ret := base.GeneratePredictionVector(X)
// Make sure everything's a FloatAttribute
insts := m.convertToFloatInsts(X)
// Get the input/output Attributes
inputAttrs := base.NonClassAttributes(insts)
outputAttrs := ret.AllClassAttributes()
// Compute layers
layers := 2 + len(m.layers)
// Check that we're operating in a singular mode
floatMode := 0
categoricalMode := 0
for _, a := range outputAttrs {
if _, ok := a.(*base.CategoricalAttribute); ok {
categoricalMode++
} else if _, ok := a.(*base.FloatAttribute); ok {
floatMode++
} else {
panic("Unsupported output Attribute type!")
}
}
if floatMode > 0 && categoricalMode > 0 {
panic("Can't predict a mix of float and categorical Attributes")
} else if categoricalMode > 1 {
panic("Can't predict more than one categorical class Attribute")
}
// Create the activation vector
a := mat.NewDense(m.network.size, 1, make([]float64, m.network.size))
// Resolve the input AttributeSpecs
inputAs := base.ResolveAttributes(insts, inputAttrs)
// Resolve the output Attributespecs
outputAs := base.ResolveAttributes(ret, outputAttrs)
// Map over each input row
insts.MapOverRows(inputAs, func(row [][]byte, rc int) (bool, error) {
// Clear the activation vector
for i := 0; i < m.network.size; i++ {
a.Set(i, 0, 0.0)
}
// Build the activation vector
for i, vb := range row {
if cIndex, ok := m.attrs[inputAs[i].GetAttribute()]; !ok {
panic("Can't resolve the Attribute!")
} else {
a.Set(cIndex, 0, base.UnpackBytesToFloat(vb))
}
}
// Robots, activate!
m.network.Activate(a, layers)
// Decide which class to set
if floatMode > 0 {
for _, as := range outputAs {
cIndex := m.attrs[as.GetAttribute()]
ret.Set(as, rc, base.PackFloatToBytes(a.At(cIndex, 0)))
}
} else {
maxIndex := 0
maxVal := 0.0
for i := m.classAttrOffset; i < m.classAttrOffset+m.classAttrCount; i++ {
val := a.At(i, 0)
if val > maxVal {
maxIndex = i
maxVal = val
}
}
maxIndex -= m.classAttrOffset
ret.Set(outputAs[0], rc, base.PackU64ToBytes(uint64(maxIndex)))
}
return true, nil
})
return ret
}
// Fit trains the neural network on the given fixed datagrid.
//
// Training stops when the mean-squared error acheived is less
// than the Convergence value, or when back-propagation has occured
// more times than the value set by MaxIterations.
func (m *MultiLayerNet) Fit(X base.FixedDataGrid) {
// Make sure everything's a FloatAttribute
insts := m.convertToFloatInsts(X)
// The size of the first layer is the number of things
// in the revised instances which aren't class Attributes
inputAttrsVec := base.NonClassAttributes(insts)
// The size of the output layer is the number of things
// in the revised instances which are class Attributes
classAttrsVec := insts.AllClassAttributes()
// The total number of layers is input layer + output layer
// plus number of layers specified
totalLayers := 2 + len(m.layers)
// The size is then augmented by the number of nodes
// in the centre
size := len(inputAttrsVec)
size += len(classAttrsVec)
hiddenSize := 0
for _, a := range m.layers {
size += a
hiddenSize += a
}
// Enumerate the Attributes
trainingAttrs := make(map[base.Attribute]int)
classAttrs := make(map[base.Attribute]int)
attrCounter := 0
for i, a := range inputAttrsVec {
attrCounter = i
m.attrs[a] = attrCounter
trainingAttrs[a] = attrCounter
}
m.classAttrOffset = attrCounter + 1
for _, a := range classAttrsVec {
attrCounter++
m.attrs[a] = attrCounter + hiddenSize
classAttrs[a] = attrCounter + hiddenSize
m.classAttrCount++
}
// Create the underlying Network
m.network = NewNetwork(size, len(inputAttrsVec), Sigmoid)
// Initialise inter-hidden layer weights and biases to small random values
layerOffset := len(inputAttrsVec)
for i := 0; i < len(m.layers)-1; i++ {
// Get the size of this layer
thisLayerSize := m.layers[i]
// Next layer size
nextLayerSize := m.layers[i+1]
// For every node in this layer
for j := 1; j <= thisLayerSize; j++ {
// Compute the offset
nodeOffset1 := layerOffset + j
// For every node in the next layer
for k := 1; k <= nextLayerSize; k++ {
// Compute offset
nodeOffset2 := layerOffset + thisLayerSize + k
// Set weight randomly
m.network.SetWeight(nodeOffset1, nodeOffset2, rand.NormFloat64()*0.1)
}
}
layerOffset += thisLayerSize
}
// Initialise biases with each hidden layer
layerOffset = len(inputAttrsVec)
for _, l := range m.layers {
for j := 1; j <= l; j++ {
nodeOffset := layerOffset + j
m.network.SetBias(nodeOffset, rand.NormFloat64()*0.1)
}
layerOffset += l
}
// Initialise biases for output layer
for i := 0; i < len(classAttrsVec); i++ {
nodeOffset := layerOffset + i
m.network.SetBias(nodeOffset, rand.NormFloat64()*0.1)
}
// Connect final hidden layer with the output layer
layerOffset = len(inputAttrsVec)
for i, l := range m.layers {
if i == len(m.layers)-1 {
for j := 1; j <= l; j++ {
nodeOffset1 := layerOffset + j
for k := 1; k <= len(classAttrsVec); k++ {
nodeOffset2 := layerOffset + l + k
m.network.SetWeight(nodeOffset1, nodeOffset2, rand.NormFloat64()*0.1)
}
}
}
layerOffset += l
}
// Connect input layer with first hidden layer (or output layer
for i := 1; i <= len(inputAttrsVec); i++ {
nextLayerLen := 0
if len(m.layers) > 0 {
nextLayerLen = m.layers[0]
} else {
nextLayerLen = len(classAttrsVec)
}
for j := 1; j <= nextLayerLen; j++ {
nodeOffset := len(inputAttrsVec) + j
v := rand.NormFloat64() * 0.1
m.network.SetWeight(i, nodeOffset, v)
}
}
// Create the training activation vector
trainVec := mat.NewDense(size, 1, make([]float64, size))
// Create the error vector
errVec := mat.NewDense(size, 1, make([]float64, size))
// Resolve training AttributeSpecs
trainAs := base.ResolveAllAttributes(insts)
// Feed-forward, compute error and update for each training example
// until convergence (what's that)
for iteration := 0; iteration < m.MaxIterations; iteration++ {
totalError := 0.0
maxRow := 0
insts.MapOverRows(trainAs, func(row [][]byte, i int) (bool, error) {
maxRow = i
// Clear vectors
for i := 0; i < size; i++ {
trainVec.Set(i, 0, 0.0)
errVec.Set(i, 0, 0.0)
}
// Build vectors
for i, vb := range row {
v := base.UnpackBytesToFloat(vb)
if attrIndex, ok := trainingAttrs[trainAs[i].GetAttribute()]; ok {
// Add to Activation vector
trainVec.Set(attrIndex, 0, v)
} else if attrIndex, ok := classAttrs[trainAs[i].GetAttribute()]; ok {
// Set to error vector
errVec.Set(attrIndex, 0, v)
} else {
panic("Should be able to find this Attribute!")
}
}
// Activate the network
m.network.Activate(trainVec, totalLayers-1)
// Compute the error
for a := range classAttrs {
cIndex := classAttrs[a]
errVec.Set(cIndex, 0, errVec.At(cIndex, 0)-trainVec.At(cIndex, 0))
}
// Update total error
totalError += math.Abs(mat.Sum(errVec))
// Back-propagate the error
b := m.network.Error(trainVec, errVec, totalLayers)
// Update the weights
m.network.UpdateWeights(trainVec, b, m.LearningRate)
// Update the biases
m.network.UpdateBias(b, m.LearningRate)
return true, nil
})
totalError /= float64(maxRow)
// If we've converged, no need to carry on
if totalError < m.Convergence {
break
}
}
}