forked from made2591/go-perceptron-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validation.go
477 lines (385 loc) · 12.7 KB
/
validation.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
package validation
import (
"math/rand"
"time"
// third part import
log "github.com/sirupsen/logrus"
// internal import
mn "github.com/made2591/go-perceptron-go/model/neural"
mu "github.com/made2591/go-perceptron-go/util"
//"fmt"
)
// TrainTestPatternsSplit split an array of patterns in training and testing.
// if shuffle is 0 the function takes the first percentage items as train and the other as test
// otherwise the patterns array is shuffled before partitioning
func TrainTestPatternsSplit(patterns []mn.Pattern, percentage float64, shuffle int) (train []mn.Pattern, test []mn.Pattern) {
// create splitting pivot
var splitPivot int = int(float64(len(patterns)) * percentage)
train = make([]mn.Pattern, splitPivot)
test = make([]mn.Pattern, len(patterns)-splitPivot)
// if mixed mode, split with shuffling
if shuffle == 1 {
// create random indexes permutation
rand.Seed(time.Now().UTC().UnixNano())
perm := rand.Perm(len(patterns))
// copy training data
for i := 0; i < splitPivot; i++ {
train[i] = patterns[perm[i]]
}
// copy test data
for i := 0; i < len(patterns)-splitPivot; i++ {
test[i] = patterns[perm[i]]
}
} else {
// else, split without shuffle
train = patterns[:splitPivot]
test = patterns[splitPivot:]
}
log.WithFields(log.Fields{
"level": "info",
"msg": "splitting completed",
"trainSet": len(train),
"testSet: ": len(test),
}).Info("Complete splitting train/test set.")
return train, test
}
// TrainTestPatternsSplit split an array of patterns in training and testing.
// if shuffle is 0 the function takes the first percentage items as train and the other as test
// otherwise the patterns array is shuffled before partitioning
func TrainTestPatternSplit(patterns []mn.Pattern, percentage float64, shuffle int) (train []mn.Pattern, test []mn.Pattern) {
// create splitting pivot
var splitPivot int = int(float64(len(patterns)) * percentage)
train = make([]mn.Pattern, splitPivot)
test = make([]mn.Pattern, len(patterns)-splitPivot)
// if mixed mode, split with shuffling
if shuffle == 1 {
// create random indexes permutation
rand.Seed(time.Now().UTC().UnixNano())
perm := rand.Perm(len(patterns))
// copy training data
for i := 0; i < splitPivot; i++ {
train[i] = patterns[perm[i]]
}
// copy test data
for i := 0; i < len(patterns)-splitPivot; i++ {
test[i] = patterns[perm[i]]
}
} else {
// else, split without shuffle
train = patterns[:splitPivot]
test = patterns[splitPivot:]
}
log.WithFields(log.Fields{
"level": "info",
"msg": "splitting completed",
"trainSet": len(train),
"testSet: ": len(test),
}).Info("Complete splitting train/test set.")
return train, test
}
// KFoldPatternsSplit split an array of patterns in k subsets.
// if shuffle is 0 the function partitions the items maintaining the order
// otherwise the patterns array is shuffled before partitioning
func KFoldPatternsSplit(patterns []mn.Pattern, k int, shuffle int) [][]mn.Pattern {
// get the size of each fold
var size = int(len(patterns) / k)
var freeElements = int(len(patterns) % k)
folds := make([][]mn.Pattern, k)
var perm []int
// if mixed mode, split with shuffling
if shuffle == 1 {
// create random indexes permutation
rand.Seed(time.Now().UTC().UnixNano())
perm = rand.Perm(len(patterns))
}
// start splitting
currSize := 0
foldStart := 0
curr := 0
for f := 0; f < k; f++ {
curr = foldStart
currSize = size
if f < freeElements {
// add another
currSize++
}
// create array
folds[f] = make([]mn.Pattern, currSize)
// copy elements
for i := 0; i < currSize; i++ {
if shuffle == 1 {
folds[f][i] = patterns[perm[curr]]
} else {
folds[f][i] = patterns[curr]
}
curr++
}
foldStart = curr
}
log.WithFields(log.Fields{
"level": "info",
"msg": "splitting completed",
"numberOfFolds": k,
"meanFoldSize: ": size,
"consideredElements": (size * k) + freeElements,
}).Info("Complete folds splitting.")
return folds
}
// RandomSubsamplingValidation perform evaluation on neuron algorithm.
// It returns scores reached for each fold iteration.
func RandomSubsamplingValidation(neuron *mn.NeuronUnit, patterns []mn.Pattern, percentage float64, epochs int, folds int, shuffle int) []float64 {
// results and predictions vars init
var scores, actual, predicted []float64
var train, test []mn.Pattern
scores = make([]float64, folds)
for t := 0; t < folds; t++ {
// split the dataset with shuffling
train, test = TrainTestPatternsSplit(patterns, percentage, shuffle)
// train neuron with set of patterns, for specified number of epochs
mn.TrainNeuron(neuron, train, epochs, 1)
// compute predictions for each pattern in testing set
for _, pattern := range test {
actual = append(actual, pattern.SingleExpectation)
predicted = append(predicted, mn.Predict(neuron, &pattern))
}
// compute score
_, percentageCorrect := mn.Accuracy(actual, predicted)
scores[t] = percentageCorrect
log.WithFields(log.Fields{
"level": "info",
"place": "validation",
"method": "RandomSubsamplingValidation",
"foldNumber": t,
"trainSetLen": len(train),
"testSetLen": len(test),
"percentageCorrect": percentageCorrect,
}).Info("Evaluation completed for current fold.")
}
// compute average score
acc := 0.0
for i := 0; i < len(scores); i++ {
acc += scores[i]
}
mean := acc / float64(len(scores))
log.WithFields(log.Fields{
"level": "info",
"place": "validation",
"method": "RandomSubsamplingValidation",
"folds": folds,
"trainSetLen": len(train),
"testSetLen": len(test),
"meanScore": mean,
}).Info("Evaluation completed for all folds.")
return scores
}
// RandomSubsamplingValidation perform evaluation on neuron algorithm.
// It returns scores reached for each fold iteration.
func KFoldValidation(neuron *mn.NeuronUnit, patterns []mn.Pattern, epochs int, k int, shuffle int) []float64 {
// results and predictions vars init
var scores, actual, predicted []float64
var train, test []mn.Pattern
scores = make([]float64, k)
// split the dataset with shuffling
folds := KFoldPatternsSplit(patterns, k, shuffle)
// the t-th fold is used as test
for t := 0; t < k; t++ {
// prepare train
train = nil
for i := 0; i < k; i++ {
if i != t {
train = append(train, folds[i]...)
}
}
test = folds[t]
// train neuron with set of patterns, for specified number of epochs
mn.TrainNeuron(neuron, train, epochs, 1)
// compute predictions for each pattern in testing set
for _, pattern := range test {
actual = append(actual, pattern.SingleExpectation)
predicted = append(predicted, mn.Predict(neuron, &pattern))
}
// compute score
_, percentageCorrect := mn.Accuracy(actual, predicted)
scores[t] = percentageCorrect
log.WithFields(log.Fields{
"level": "info",
"place": "validation",
"method": "KFoldValidation",
"foldNumber": t,
"trainSetLen": len(train),
"testSetLen": len(test),
"percentageCorrect": percentageCorrect,
}).Info("Evaluation completed for current fold.")
}
// compute average score
acc := 0.0
for i := 0; i < len(scores); i++ {
acc += scores[i]
}
mean := acc / float64(len(scores))
log.WithFields(log.Fields{
"level": "info",
"place": "validation",
"method": "KFoldValidation",
"folds": k,
"trainSetLen": len(train),
"testSetLen": len(test),
"meanScore": mean,
}).Info("Evaluation completed for all folds.")
return scores
}
// It returns scores reached for each fold iteration.
func MLPRandomSubsamplingValidation(mlp *mn.MultiLayerNetwork, patterns []mn.Pattern, percentage float64, epochs int, folds int, shuffle int, mapped []string) []float64 {
// results and predictions vars init
var scores, actual, predicted []float64
var train, test []mn.Pattern
scores = make([]float64, folds)
for t := 0; t < folds; t++ {
// split the dataset with shuffling
train, test = TrainTestPatternsSplit(patterns, percentage, shuffle)
// train mlp with set of patterns, for specified number of epochs
mn.MLPTrain(mlp, patterns, mapped, epochs)
// compute predictions for each pattern in testing set
for _, pattern := range test {
// get actual
actual = append(actual, pattern.SingleExpectation)
// get output from network
o_out := mn.Execute(mlp, &pattern)
// get index of max output
_, indexMaxOut := mu.MaxInSlice(o_out)
// add to predicted values
predicted = append(predicted, float64(indexMaxOut))
}
// compute score
_, percentageCorrect := mn.Accuracy(actual, predicted)
scores[t] = percentageCorrect
log.WithFields(log.Fields{
"level": "info",
"place": "validation",
"method": "MLPRandomSubsamplingValidation",
"foldNumber": t,
"trainSetLen": len(train),
"testSetLen": len(test),
"percentageCorrect": percentageCorrect,
}).Info("Evaluation completed for current fold.")
}
// compute average score
acc := 0.0
for i := 0; i < len(scores); i++ {
acc += scores[i]
}
mean := acc / float64(len(scores))
log.WithFields(log.Fields{
"level": "info",
"place": "validation",
"method": "MLPRandomSubsamplingValidation",
"folds": folds,
"trainSetLen": len(train),
"testSetLen": len(test),
"meanScore": mean,
}).Info("Evaluation completed for all folds.")
return scores
}
// RandomSubsamplingValidation perform evaluation on neuron algorithm.
// It returns scores reached for each fold iteration.
func MLPKFoldValidation(mlp *mn.MultiLayerNetwork, patterns []mn.Pattern, epochs int, k int, shuffle int, mapped []string) []float64 {
// results and predictions vars init
var scores, actual, predicted []float64
var train, test []mn.Pattern
scores = make([]float64, k)
// split the dataset with shuffling
folds := KFoldPatternsSplit(patterns, k, shuffle)
// the t-th fold is used as test
for t := 0; t < k; t++ {
// prepare train
train = nil
for i := 0; i < k; i++ {
if i != t {
train = append(train, folds[i]...)
}
}
test = folds[t]
// train mlp with set of patterns, for specified number of epochs
mn.MLPTrain(mlp, patterns, mapped, epochs)
// compute predictions for each pattern in testing set
for _, pattern := range test {
// get actual
actual = append(actual, pattern.SingleExpectation)
// get output from network
o_out := mn.Execute(mlp, &pattern)
// get index of max output
_, indexMaxOut := mu.MaxInSlice(o_out)
// add to predicted values
predicted = append(predicted, float64(indexMaxOut))
}
// compute score
_, percentageCorrect := mn.Accuracy(actual, predicted)
scores[t] = percentageCorrect
log.WithFields(log.Fields{
"level": "info",
"place": "validation",
"method": "MLPKFoldValidation",
"foldNumber": t,
"trainSetLen": len(train),
"testSetLen": len(test),
"percentageCorrect": percentageCorrect,
}).Info("Evaluation completed for current fold.")
}
// compute average score
acc := 0.0
for i := 0; i < len(scores); i++ {
acc += scores[i]
}
mean := acc / float64(len(scores))
log.WithFields(log.Fields{
"level": "info",
"place": "validation",
"method": "MLPKFoldValidation",
"folds": k,
"trainSetLen": len(train),
"testSetLen": len(test),
"meanScore": mean,
}).Info("Evaluation completed for all folds.")
return scores
}
// RNNValidation perform evaluation on neuron algorithm.
func RNNValidation(mlp *mn.MultiLayerNetwork, patterns []mn.Pattern, epochs int, shuffle int) (float64, []float64) {
// results and predictions vars init
var scores []float64
scores = make([]float64, len(patterns))
// train mlp with set of patterns, for specified number of epochs
mn.ElmanTrain(mlp, patterns, epochs)
p_cor := 0.0
// compute predictions for each pattern in testing set
for p_i, pattern := range patterns {
// get output from network
o_out := mn.Execute(mlp, &pattern, 1)
for o_out_i, o_out_v := range(o_out) {
o_out[o_out_i] = mu.Round(o_out_v, .5, 0)
}
log.WithFields(log.Fields{
"a_p_b": pattern.Features,
"rea_c": pattern.MultipleExpectation,
"pre_c": o_out,
}).Debug()
// add to predicted values
_, p_cor = mn.Accuracy(pattern.MultipleExpectation, o_out)
// compute score
scores[p_i] = p_cor;
}
// compute average score
acc := 0.0
for i := 0; i < len(scores); i++ {
acc += scores[i]
}
mean := acc / float64(len(scores))
log.WithFields(log.Fields{
"level": "info",
"place": "validation",
"method": "RNNValidation",
"trainSetLen": len(patterns),
"testSetLen": len(patterns),
"meanScore": mean,
}).Info("Evaluation completed for all patterns.")
return mean, scores
}