forked from pa-m/sklearn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
basemlp32.go
1369 lines (1261 loc) · 41.4 KB
/
basemlp32.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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package neuralnetwork
import (
"encoding/json"
"fmt"
"log"
"reflect"
"runtime"
"sort"
"strings"
"sync"
"time"
"gonum.org/v1/gonum/blas/blas32"
"github.com/RobinRCM/sklearn/base"
"golang.org/x/exp/rand"
"gonum.org/v1/gonum/blas"
"gonum.org/v1/gonum/mat"
"gonum.org/v1/gonum/optimize"
)
// BaseMultilayerPerceptron32 closely matches sklearn/neural_network/multilayer_perceptron.py
type BaseMultilayerPerceptron32 struct {
Activation string `json:"activation"`
Solver string `json:"solver"`
Alpha float32 `json:"alpha"`
WeightDecay float32 `json:"weight_decay"`
BatchSize int `json:"batch_size"`
BatchNormalize bool
LearningRate string `json:"learning_rate"`
LearningRateInit float32 `json:"learning_rate_init"`
PowerT float32 `json:"power_t"`
MaxIter int `json:"max_iter"`
LossFuncName string `json:"loss_func_name"`
HiddenLayerSizes []int `json:"hidden_layer_sizes"`
Shuffle bool `json:"shuffle"`
RandomState base.RandomState `json:"random_state"`
Tol float32 `json:"tol"`
Verbose bool `json:"verbose"`
WarmStart bool `json:"warm_start"`
Momentum float32 `json:"momentum"`
NesterovsMomentum bool `json:"nesterovs_momentum"`
EarlyStopping bool `json:"early_stopping"`
ValidationFraction float32 `json:"validation_fraction"`
Beta1 float32 `json:"beta_1"`
Beta2 float32 `json:"beta_2"`
Epsilon float32 `json:"epsilon"`
NIterNoChange int `json:"n_iter_no_change"`
// Outputs
NLayers int
NIter int
NOutputs int
Intercepts [][]float32 `json:"intercepts_"`
Coefs []blas32General `json:"coefs_"`
OutActivation string `json:"out_activation_"`
Loss float32
// internal
t int
LossCurve []float32
ValidationScores []float32
BestValidationScore float32
BestLoss float32
NoImprovementCount int
optimizer Optimizer32
packedParameters []float32
packedGrads []float32 // packedGrads allow tests to check gradients
bestParameters []float32
batchNorm [][]float32
lb *LabelBinarizer32
// beforeMinimize allow test to set weights
beforeMinimize func(optimize.Problem, []float64)
}
// Activations32 is a map containing the inplace_activation functions
var Activations32 = map[string]func(z blas32General){
"identity": func(z blas32General) {},
"logistic": func(z blas32General) {
for row, zpos := 0, 0; row < z.Rows; row, zpos = row+1, zpos+z.Stride {
for col := 0; col < z.Cols; col++ {
z.Data[zpos+col] = 1 / (1 + M32.Exp(-z.Data[zpos+col]))
}
}
},
"tanh": func(z blas32General) {
for row, zpos := 0, 0; row < z.Rows; row, zpos = row+1, zpos+z.Stride {
for col := 0; col < z.Cols; col++ {
z.Data[zpos+col] = M32.Tanh(-z.Data[zpos+col])
}
}
},
"relu": func(z blas32General) {
for row, zpos := 0, 0; row < z.Rows; row, zpos = row+1, zpos+z.Stride {
for col := 0; col < z.Cols; col++ {
if z.Data[zpos+col] < 0 {
z.Data[zpos+col] = 0
}
}
}
},
"softmax": func(z blas32General) {
for row, zpos := 0, 0; row < z.Rows; row, zpos = row+1, zpos+z.Stride {
sum := float32(0)
for col := 0; col < z.Cols; col++ {
z.Data[zpos+col] = M32.Exp(z.Data[zpos+col])
sum += z.Data[zpos+col]
}
for col := 0; col < z.Cols; col++ {
z.Data[zpos+col] /= sum
}
}
},
}
// Derivatives32 is a map of functions which multiply deltas with derivative of activation function
var Derivatives32 = map[string]func(Z, deltas blas32General){
"identity": func(Z, deltas blas32General) {
},
"logistic": func(Z, deltas blas32General) {
for row, zpos, dpos := 0, 0, 0; row < Z.Rows; row, zpos, dpos = row+1, zpos+Z.Stride, dpos+deltas.Stride {
for col := 0; col < Z.Cols; col++ {
z := Z.Data[zpos+col]
deltas.Data[dpos+col] *= z * (1 - z)
}
}
},
"tanh": func(Z, deltas blas32General) {
for row, zpos, dpos := 0, 0, 0; row < Z.Rows; row, zpos, dpos = row+1, zpos+Z.Stride, dpos+deltas.Stride {
for col := 0; col < Z.Cols; col++ {
z := Z.Data[zpos+col]
deltas.Data[dpos+col] *= 1 - z*z
}
}
},
"relu": func(Z, deltas blas32General) {
for row, zpos, dpos := 0, 0, 0; row < Z.Rows; row, zpos, dpos = row+1, zpos+Z.Stride, dpos+deltas.Stride {
for col := 0; col < Z.Cols; col++ {
if Z.Data[zpos+col] == 0 {
deltas.Data[dpos+col] = 0
}
}
}
},
}
// LossFunctions32 is a map for loss functions
var LossFunctions32 = map[string]func(y, h blas32General) float32{
"square_loss": func(y, h blas32General) float32 {
sum := float32(0)
for row, hpos, ypos := 0, 0, 0; row < y.Rows; row, hpos, ypos = row+1, hpos+h.Stride, ypos+y.Stride {
for col := 0; col < y.Cols; col++ {
e := h.Data[hpos+col] - y.Data[ypos+col]
sum += e * e
}
}
return sum / 2 / float32(h.Rows)
},
"log_loss": func(y, h blas32General) float32 {
sum := float32(0)
hmin, hmax := M32.Nextafter(0, 1), M32.Nextafter(1, 0)
for row, hpos, ypos := 0, 0, 0; row < y.Rows; row, hpos, ypos = row+1, hpos+h.Stride, ypos+y.Stride {
for col := 0; col < y.Cols; col++ {
hval := h.Data[hpos+col]
if hval < hmin {
hval = hmin
} else if hval > hmax {
hval = hmax
}
if y.Data[ypos+col] != 0 {
sum += -y.Data[ypos+col] * M32.Log(hval)
}
}
}
return sum / float32(h.Rows)
},
"binary_log_loss": func(y, h blas32General) float32 {
sum := float32(0)
hmin, hmax := M32.Nextafter(0, 1), M32.Nextafter(1, 0)
for row, hpos, ypos := 0, 0, 0; row < y.Rows; row, hpos, ypos = row+1, hpos+h.Stride, ypos+y.Stride {
for col := 0; col < y.Cols; col++ {
hval := h.Data[hpos+col]
if hval < hmin {
hval = hmin
} else if hval > hmax {
hval = hmax
}
sum += -y.Data[ypos+col]*M32.Log(hval) - (1-y.Data[ypos+col])*M32.Log1p(-hval)
}
}
return sum / float32(h.Rows)
},
}
// Optimizer32 is an interface for stochastic optimizers
type Optimizer32 interface {
iterationEnds(timeStep float32)
triggerStopping(msg string, verbose bool) bool
updateParams(grads []float32)
}
func addIntercepts32(a blas32General, b []float32) {
for arow, apos := 0, 0; arow < a.Rows; arow, apos = arow+1, apos+a.Stride {
for c := 0; c < a.Cols; c++ {
a.Data[apos+c] += b[c]
}
}
}
func matRowMean32(a blas32General, b []float32) {
for c := 0; c < a.Cols; c++ {
b[c] = 0
}
for arow, apos := 0, 0; arow < a.Rows; arow, apos = arow+1, apos+a.Stride {
for c := 0; c < a.Cols; c++ {
b[c] += a.Data[apos+c]
}
}
for c := 0; c < a.Cols; c++ {
b[c] /= float32(a.Rows)
}
}
// NewBaseMultilayerPerceptron32 returns a BaseMultilayerPerceptron32 with defaults
func NewBaseMultilayerPerceptron32() *BaseMultilayerPerceptron32 {
return &BaseMultilayerPerceptron32{
Activation: "relu",
Solver: "adam",
Alpha: 0.0001,
BatchSize: 200,
LearningRate: "constant",
LearningRateInit: 0.001,
PowerT: .5,
MaxIter: 200,
//LossFuncName string
HiddenLayerSizes: []int{100},
Shuffle: true,
//RandomState base.Source,
Tol: 1e-4,
Verbose: false,
WarmStart: false,
Momentum: .9,
NesterovsMomentum: true,
EarlyStopping: false,
ValidationFraction: .1,
Beta1: .9,
Beta2: .999,
Epsilon: 1e-8,
NIterNoChange: 10,
}
}
// forwardPass Perform a forward pass on the network by computing the values
// of the neurons in the hidden layers and the output layer.
// activations : []blas32General, length = nLayers - 1
func (mlp *BaseMultilayerPerceptron32) forwardPass(activations []blas32General) {
hiddenActivation := Activations32[mlp.Activation]
var i int
for i = 0; i < mlp.NLayers-1; i++ {
gemm32(blas.NoTrans, blas.NoTrans, 1, activations[i], mlp.Coefs[i], 0, activations[i+1])
addIntercepts32(activations[i+1], mlp.Intercepts[i])
// For the hidden layers
if (i + 1) != (mlp.NLayers - 1) {
hiddenActivation(activations[i+1])
}
}
i = mlp.NLayers - 2
// # For the last layer
outputActivation := Activations32[mlp.OutActivation]
outputActivation(activations[i+1])
}
// batchNormalize computes norms of activations and divides activations
func (mlp *BaseMultilayerPerceptron32) batchNormalize(activations []blas32General) {
for i := 0; i < mlp.NLayers-2; i++ {
activation := activations[i+1]
batchNorm := mlp.batchNorm[i]
for o := 0; o < activation.Cols; o++ {
M := float32(0)
// compute max for layer i, output o
for r, rpos := 0, 0; r < activation.Rows; r, rpos = r+1, rpos+activation.Stride {
a := M32.Abs(activation.Data[rpos+o])
if M < a {
M = a
}
}
// divide activation by max
if M > 0 {
for r, rpos := 0, 0; r < activation.Rows; r, rpos = r+1, rpos+activation.Stride {
activation.Data[rpos+o] /= M
}
}
batchNorm[o] = M
}
}
}
// batchNormalizeDeltas divides deltas by batchNorm
func (mlp *BaseMultilayerPerceptron32) batchNormalizeDeltas(deltas blas32General, batchNorm []float32) {
for r, rpos := 0, 0; r < deltas.Rows; r, rpos = r+1, rpos+deltas.Stride {
for o := 0; o < deltas.Cols; o++ {
deltas.Data[rpos+o] /= batchNorm[o]
}
}
}
func (mlp *BaseMultilayerPerceptron32) sumCoefSquares() float32 {
s := float32(0)
for _, c := range mlp.Coefs {
for _, co := range c.Data {
s += co * co
}
}
return s
}
// computeLossGrad Compute the gradient of loss with respect to coefs and intercept for specified layer.
// This function does backpropagation for the specified one layer.
func (mlp *BaseMultilayerPerceptron32) computeLossGrad(layer, NSamples int, activations []blas32General, deltas []blas32General, coefGrads []blas32General, interceptGrads [][]float32) {
// coefGrads[layer] = safeSparseDot(activations[layer].T, deltas[layer])
// coefGrads[layer] += (self.alpha * self.coefs_[layer])
// coefGrads[layer] /= nSamples
gemm32(blas.Trans, blas.NoTrans, 1/float32(NSamples), activations[layer], deltas[layer], 0, coefGrads[layer])
axpy32(len(coefGrads[layer].Data), mlp.Alpha/float32(NSamples), mlp.Coefs[layer].Data, coefGrads[layer].Data)
// interceptGrads[layer] = np.mean(deltas[layer], 0)
matRowMean32(deltas[layer], interceptGrads[layer])
}
// backprop Compute the MLP loss function and its corresponding derivatives with respect to each parameter: weights and bias vectors.
// X : blas32General shape (nSamples, nFeatures)
// Y : blas32General shape (nSamples, nOutputs)
// activations : []blas32General, length=NLayers-1
// deltas : []blas32General, length=NLayers-1
// coefGrads : []blas32General, length=NLayers-1
// interceptGrads : [][]float32, length=NLayers-1
func (mlp *BaseMultilayerPerceptron32) backprop(X, y blas32General, activations, deltas, coefGrads []blas32General, interceptGrads [][]float32) float32 {
nSamples := X.Rows
if mlp.WeightDecay > 0 {
for iw := range mlp.packedParameters {
mlp.packedParameters[iw] *= (1 - mlp.WeightDecay)
}
}
mlp.forwardPass(activations)
if mlp.BatchNormalize {
// compute norm of activations for non-terminal layers
mlp.batchNormalize(activations)
}
//# Get loss
lossFuncName := mlp.LossFuncName
if strings.EqualFold(lossFuncName, "log_loss") && strings.EqualFold(mlp.OutActivation, "logistic") {
lossFuncName = "binary_log_loss"
}
// y may have less rows than activations il last batch
loss := LossFunctions32[lossFuncName](y, activations[len(activations)-1])
// # Add L2 regularization term to loss
loss += (0.5 * mlp.Alpha) * mlp.sumCoefSquares() / float32(nSamples)
//# Backward propagate
last := mlp.NLayers - 2
// # The calculation of delta[last] here works with following
// # combinations of output activation and loss function:
// # sigmoid and binary cross entropy, softmax and categorical cross
// # entropy, and identity with squared loss
//deltas[last] = activations[len(activations)-1] - y
// y may have less rows than activations il last batch
{
H := activations[len(activations)-1]
D := deltas[last]
for r, pos := 0, 0; r < y.Rows; r, pos = r+1, pos+y.Stride {
for o, posc := 0, pos; o < y.Cols; o, posc = o+1, posc+1 {
D.Data[posc] = H.Data[posc] - y.Data[posc]
}
}
}
//# Compute gradient for the last layer
mlp.computeLossGrad(
last, nSamples, activations, deltas, coefGrads, interceptGrads)
//# Iterate over the hidden layers
for i := mlp.NLayers - 2; i >= 1; i-- {
//deltas[i - 1] = safeSparseDot(deltas[i], self.coefs_[i].T)
gemm32(blas.NoTrans, blas.Trans, 1, deltas[i], mlp.Coefs[i], 0, deltas[i-1])
inplaceDerivative := Derivatives32[mlp.Activation]
// inplaceDerivative multiplies deltas[i-1] by activation derivative
inplaceDerivative(activations[i], deltas[i-1])
if mlp.BatchNormalize {
// divide deltas by batchNorm
mlp.batchNormalizeDeltas(deltas[i-1], mlp.batchNorm[i-1])
}
mlp.computeLossGrad(
i-1, nSamples, activations, deltas, coefGrads,
interceptGrads)
}
return loss
}
func (mlp *BaseMultilayerPerceptron32) initialize(yCols int, layerUnits []int, isClassifier, isMultiClass bool) {
// # set all attributes, allocate weights etc for first call
// # Initialize parameters
mlp.NIter = 0
mlp.t = 0
mlp.NOutputs = yCols
//# Compute the number of layers
mlp.NLayers = len(layerUnits)
//# Output for regression
if !isClassifier {
mlp.OutActivation = "identity"
mlp.LossFuncName = "square_loss"
//# Output for multi class
} else if isMultiClass {
mlp.OutActivation = "softmax"
mlp.LossFuncName = "log_loss"
//# Output for binary class and multi-label
} else {
mlp.OutActivation = "logistic"
mlp.LossFuncName = "binary_log_loss"
}
//# Initialize coefficient and intercept layers
mlp.Coefs = make([]blas32General, mlp.NLayers-1)
mlp.Intercepts = make([][]float32, mlp.NLayers-1)
off := 0
for i := 0; i < mlp.NLayers-1; i++ {
off += (1 + layerUnits[i]) * layerUnits[i+1]
}
mem := make([]float32, off)
mlp.packedParameters = mem[0:off]
if mlp.BatchNormalize {
// allocate batchNorm for non-terminal layers
mlp.batchNorm = make([][]float32, mlp.NLayers-2)
}
off = 0
if mlp.RandomState == (base.RandomState)(nil) {
mlp.RandomState = base.NewLockedSource(uint64(time.Now().UnixNano()))
}
type Float32er interface {
Float32() float32
}
var rndFloat32 func() float32
if float32er, ok := mlp.RandomState.(Float32er); ok {
rndFloat32 = float32er.Float32
} else {
rndFloat32 = rand.New(mlp.RandomState).Float32
}
for i := 0; i < mlp.NLayers-1; i++ {
prevOff := off
mlp.Intercepts[i] = mem[off : off+layerUnits[i+1]]
off += layerUnits[i+1]
mlp.Coefs[i] = blas32General{Rows: layerUnits[i], Cols: layerUnits[i+1], Stride: layerUnits[i+1], Data: mem[off : off+layerUnits[i]*layerUnits[i+1]]}
off += layerUnits[i] * layerUnits[i+1]
// # Use the initialization method recommended by
// # Glorot et al.
factor := float32(6.)
fanIn, fanOut := layerUnits[i], layerUnits[i+1]
if strings.EqualFold(mlp.Activation, "logistic") {
factor = 2.
}
initBound := M32.Sqrt(factor / float32(fanIn+fanOut))
for pos := prevOff; pos < off; pos++ {
mem[pos] = rndFloat32() * initBound
}
if mlp.BatchNormalize && i < mlp.NLayers-2 {
mlp.batchNorm[i] = make([]float32, layerUnits[i+1])
}
}
mlp.BestLoss = M32.Inf(1)
}
func (mlp *BaseMultilayerPerceptron32) fit(X, y blas32General, incremental bool) {
// # Validate input parameters.
mlp.validateHyperparameters()
for _, s := range mlp.HiddenLayerSizes {
if s < 0 {
log.Panicf("hiddenLayerSizes must be > 0, got %v.", mlp.HiddenLayerSizes)
}
}
X, y = mlp.validateInput(X, y, incremental)
nSamples, nFeatures := X.Rows, X.Cols
mlp.NOutputs = y.Cols
layerUnits := append([]int{nFeatures}, mlp.HiddenLayerSizes...)
layerUnits = append(layerUnits, mlp.NOutputs)
if mlp.RandomState == nil {
mlp.RandomState = rand.New(base.NewLockedSource(uint64(time.Now().UnixNano())))
}
if !mlp.WarmStart && !incremental {
//# First time training the model
var isClassifier, isMulticlass = true, y.Cols > 1
for _, yval := range y.Data {
if yval != 0 && yval != 1 {
isClassifier = false
break
}
}
mlp.initialize(y.Cols, layerUnits, isClassifier, isMulticlass)
}
// # lbfgs does not support mini-batches
if strings.EqualFold(mlp.Solver, "lbfgs") {
mlp.BatchSize = nSamples
} else if mlp.BatchSize <= 0 {
mlp.BatchSize = nSamples
if mlp.BatchSize > 200 {
mlp.BatchSize = 200
}
} else {
if mlp.BatchSize > nSamples {
log.Printf("Got batchsize larger than sample size. It is going to be clipped.\n")
mlp.BatchSize = nSamples
}
}
// # Initialize lists
activations := make([]blas32.General, 1, len(layerUnits))
activations[0] = X
deltas := make([]blas32.General, 0, len(layerUnits)-1)
// compute size of activations and deltas
off := 0
for _, nFanOut := range layerUnits[1:] {
size := mlp.BatchSize * nFanOut
off += size + size
}
mem := make([]float32, off)
off = 0
for _, nFanOut := range layerUnits[1:] {
size := mlp.BatchSize * nFanOut
activations = append(activations, blas32General{Rows: mlp.BatchSize, Cols: nFanOut, Stride: nFanOut, Data: mem[off : off+size]})
off += size
deltas = append(deltas, blas32General{Rows: mlp.BatchSize, Cols: nFanOut, Stride: nFanOut, Data: mem[off : off+size]})
off += size
}
off = len(mlp.packedParameters)
packedGrads := make([]float32, off)
CoefsGrads := make([]blas32General, mlp.NLayers-1)
InterceptsGrads := make([][]float32, mlp.NLayers-1)
off = 0
for i := 0; i < mlp.NLayers-1; i++ {
InterceptsGrads[i] = packedGrads[off : off+layerUnits[i+1]]
off += layerUnits[i+1]
CoefsGrads[i] = blas32General{Rows: layerUnits[i], Cols: layerUnits[i+1], Stride: layerUnits[i+1], Data: packedGrads[off : off+layerUnits[i]*layerUnits[i+1]]}
off += layerUnits[i] * layerUnits[i+1]
}
if strings.EqualFold(mlp.Solver, "lbfgs") {
// # Run the LBFGS solver
mlp.fitLbfgs(X, y, activations, deltas, CoefsGrads,
InterceptsGrads, packedGrads, layerUnits)
} else {
// # Run the Stochastic optimization solver
mlp.fitStochastic(X, y, activations, deltas, CoefsGrads,
InterceptsGrads, packedGrads, layerUnits, incremental)
}
mlp.packedGrads = packedGrads
}
// IsClassifier return true if LossFuncName is not square_loss
func (mlp *BaseMultilayerPerceptron32) IsClassifier() bool {
return mlp.LossFuncName != "square_loss"
}
// Fit compute Coefs and Intercepts
func (mlp *BaseMultilayerPerceptron32) Fit(X, Y Matrix) {
var xb, yb blas32.General
if xg, ok := X.(RawMatrixer32); ok && !mlp.Shuffle {
if yg, ok := Y.(RawMatrixer32); ok {
xb, yb = xg.RawMatrix(), yg.RawMatrix()
}
} else {
var tmp General32
tmp = General32(xb)
tmp.Copy(X)
xb = tmp.RawMatrix()
tmp = General32(yb)
tmp.Copy(Y)
yb = tmp.RawMatrix()
}
if mlp.IsClassifier() && !isBinarized32(yb) {
mlp.lb = NewLabelBinarizer32(0, 1)
xbin, ybin := mlp.lb.FitTransform(General32(xb), General32(yb))
xb, yb = blas32.General(xbin), blas32.General(ybin)
}
mlp.fit(xb, yb, false)
}
// GetNOutputs returns output columns number for Y to pass to predict
func (mlp *BaseMultilayerPerceptron32) GetNOutputs() int {
if mlp.lb != nil {
return len(mlp.lb.Classes)
}
return mlp.NOutputs
}
// Predict do forward pass and fills Y (Y must be Mutable)
func (mlp *BaseMultilayerPerceptron32) Predict(X mat.Matrix, Y Mutable) {
var xb, yb General32
if xg, ok := X.(RawMatrixer32); ok {
if yg, ok := Y.(RawMatrixer32); ok {
xb, yb = General32(xg.RawMatrix()), General32(yg.RawMatrix())
}
} else {
xb.Copy(X)
yb.Copy(Y)
}
mlp.predict(xb.RawMatrix(), yb.RawMatrix())
FromDense32(Y, yb)
}
func (mlp *BaseMultilayerPerceptron32) validateHyperparameters() {
if mlp.MaxIter <= 0 {
log.Panicf("maxIter must be > 0, got %d.", mlp.MaxIter)
}
if mlp.Alpha < 0.0 {
log.Panicf("alpha must be >= 0, got %g.", mlp.Alpha)
}
if mlp.LearningRateInit <= 0.0 {
log.Panicf("learningRateInit must be > 0, got %g.", mlp.LearningRateInit)
}
if mlp.Momentum > 1 || mlp.Momentum < 0 {
log.Panicf("momentum must be >= 0 and <= 1, got %g", mlp.Momentum)
}
if mlp.ValidationFraction < 0 || mlp.ValidationFraction >= 1 {
log.Panicf("validationFraction must be >= 0 and < 1, got %g", mlp.ValidationFraction)
}
if mlp.Beta1 < 0 || mlp.Beta1 >= 1 {
log.Panicf("beta_1 must be >= 0 and < 1, got %g", mlp.Beta1)
}
if mlp.Beta2 < 0 || mlp.Beta2 >= 1 {
log.Panicf("beta_2 must be >= 0 and < 1, got %g", mlp.Beta2)
}
if mlp.Epsilon <= 0.0 {
log.Panicf("epsilon must be > 0, got %g.", mlp.Epsilon)
}
if mlp.NIterNoChange <= 0 {
log.Panicf("nIterNoChange must be > 0, got %d.", mlp.NIterNoChange)
}
//# raise ValueError if not registered
supportedActivations := []string{}
for k := range Activations32 {
supportedActivations = append(supportedActivations, k)
}
if _, ok := Activations32[mlp.Activation]; !ok {
log.Panicf("The activation \"%s\" is not supported. Supported activations are %s.", mlp.Activation, supportedActivations)
}
switch mlp.LearningRate {
case "constant", "invscaling", "adaptive":
default:
log.Panicf("learning rate %s is not supported.", mlp.LearningRate)
}
switch mlp.Solver {
case "sgd", "adam", "lbfgs":
default:
log.Panicf("The solver %s is not supported.", mlp.Solver)
}
}
func (mlp *BaseMultilayerPerceptron32) fitLbfgs(X, y blas32General, activations, deltas, coefGrads []blas32General,
interceptGrads [][]float32, packedGrads []float32, layerUnits []int) {
method := &optimize.LBFGS{}
settings := &optimize.Settings{
FuncEvaluations: mlp.MaxIter,
Converger: &optimize.FunctionConverge{
Relative: float64(mlp.Tol),
Iterations: mlp.NIterNoChange,
},
Concurrent: runtime.GOMAXPROCS(0),
}
var mu sync.Mutex // sync access to mlp.Loss on LossCurve
problem := optimize.Problem{
Func: func(w []float64) float64 {
for i := range w {
mlp.packedParameters[i] = float32(w[i])
}
loss := float64(mlp.backprop(X, y, activations, deltas, coefGrads, interceptGrads))
mu.Lock()
mlp.Loss = float32(loss)
mlp.LossCurve = append(mlp.LossCurve, mlp.Loss)
if mlp.BestLoss > mlp.Loss {
mlp.BestLoss = mlp.Loss
}
mu.Unlock()
return loss
},
Grad: func(g, w []float64) {
// Grad is called just after Func with same w
if g == nil { // g is nil at first call
g = make([]float64, len(w))
}
for i := range w {
g[i] = float64(packedGrads[i])
}
},
}
w := make([]float64, len(mlp.packedParameters))
for i := range w {
w[i] = float64(mlp.packedParameters[i])
}
if mlp.beforeMinimize != nil {
mlp.beforeMinimize(problem, w)
}
res, err := optimize.Minimize(problem, w, settings, method)
if err != nil {
log.Panic(err)
}
if res.Status != optimize.GradientThreshold && res.Status != optimize.FunctionConvergence {
log.Printf("lbfgs optimizer: Maximum iterations (%d) reached and the optimization hasn't converged yet.\n", mlp.MaxIter)
}
}
func (mlp *BaseMultilayerPerceptron32) fitStochastic(X, y blas32General, activations, deltas, coefGrads []blas32General,
interceptGrads [][]float32, packedGrads []float32, layerUnits []int, incremental bool) {
if !incremental || mlp.optimizer == Optimizer32(nil) {
params := mlp.packedParameters
switch mlp.Solver {
case "sgd":
mlp.optimizer = &SGDOptimizer32{
Params: params,
LearningRateInit: mlp.LearningRateInit,
LearningRate: mlp.LearningRateInit,
LRSchedule: mlp.LearningRate,
PowerT: mlp.PowerT,
Momentum: mlp.Momentum,
Nesterov: mlp.NesterovsMomentum}
case "adam":
mlp.optimizer = &AdamOptimizer32{
Params: params,
LearningRateInit: mlp.LearningRateInit,
LearningRate: mlp.LearningRateInit,
Beta1: mlp.Beta1, Beta2: mlp.Beta2, Epsilon: mlp.Epsilon,
}
}
}
// # earlyStopping in partialFit doesn"t make sense
earlyStopping := mlp.EarlyStopping && !incremental
var XVal, yVal blas32General
nSamples := X.Rows
testSize := 0
if earlyStopping {
testSize = int(M32.Ceil(mlp.ValidationFraction * float32(nSamples)))
XVal = blas32General(General32(X).RowSlice(nSamples-testSize, nSamples))
yVal = blas32General(General32(y).RowSlice(nSamples-testSize, nSamples))
mlp.bestParameters = make([]float32, len(mlp.packedParameters))
// if isClassifier(self):
// yVal = self.LabelBinarizer32.inverseTransform(yVal)
}
batchSize := mlp.BatchSize
idx := make([]int, nSamples)
for i := range idx {
idx[i] = i
}
type Shuffler interface {
Shuffle(n int, swap func(i, j int))
}
var rndShuffle func(n int, swap func(i, j int))
if shuffler, ok := mlp.RandomState.(Shuffler); ok {
rndShuffle = shuffler.Shuffle
} else {
rndShuffle = rand.New(mlp.RandomState).Shuffle
}
func() {
if r := recover(); r != nil {
// ...
log.Panic(r)
}
for it := 0; it < mlp.MaxIter; it++ {
if mlp.Shuffle {
rndShuffle(nSamples, indexedXY{idx: sort.IntSlice(idx), X: general32FastSwap(X), Y: general32FastSwap(y)}.Swap)
}
accumulatedLoss := float32(0.0)
for batch := [2]int{0, batchSize}; batch[0] < nSamples-testSize; batch = [2]int{batch[1], batch[1] + batchSize} {
if batch[1] > nSamples-testSize {
batch[1] = nSamples - testSize
}
// activations[0] = X[batchSlice]
Xbatch := blas32General(General32(X).RowSlice(batch[0], batch[1]))
Ybatch := blas32General(General32(y).RowSlice(batch[0], batch[1]))
activations[0] = Xbatch
for _, a := range activations {
a.Rows = Xbatch.Rows
}
//X, y blas32General, activations, deltas, coefGrads []blas32General, interceptGrads
batchLoss := mlp.backprop(Xbatch, Ybatch, activations, deltas, coefGrads, interceptGrads)
accumulatedLoss += batchLoss * float32(batch[1]-batch[0])
//# update weights
mlp.optimizer.updateParams(packedGrads)
}
mlp.NIter++
mlp.Loss = accumulatedLoss / float32(nSamples)
mlp.t += nSamples
mlp.LossCurve = append(mlp.LossCurve, mlp.Loss)
if mlp.Verbose {
fmt.Printf("Iteration %d, loss = %.8f\n", mlp.NIter, mlp.Loss)
}
// # update noImprovementCount based on training loss or
// # validation score according to earlyStopping
mlp.updateNoImprovementCount(earlyStopping, XVal, yVal)
// # for learning rate that needs to be updated at iteration end
mlp.optimizer.iterationEnds(float32(mlp.t))
if mlp.NoImprovementCount > mlp.NIterNoChange {
// # not better than last `nIterNoChange` iterations by tol
// # stop or decrease learning rate
var msg string
if earlyStopping {
msg = fmt.Sprintf("Validation score did not improve more than tol=%f for %d consecutive epochs.", mlp.Tol, mlp.NIterNoChange)
} else {
msg = fmt.Sprintf("Training loss did not improve more than tol=%f for %d consecutive epochs.", mlp.Tol, mlp.NIterNoChange)
}
isStopping := mlp.optimizer.triggerStopping(msg, mlp.Verbose)
if isStopping {
break
}
mlp.NoImprovementCount = 0
}
if incremental {
break
}
if mlp.NIter == mlp.MaxIter && mlp.MaxIter > 1 {
log.Printf("Stochastic Optimizer: Maximum iterations (%d) reached and the optimization hasn't converged yet.\n", mlp.MaxIter)
}
}
}()
if earlyStopping {
// # restore best weights
copy(mlp.packedParameters, mlp.bestParameters)
}
if mlp.Shuffle {
sort.Sort(indexedXY{idx: sort.IntSlice(idx), X: general32FastSwap(X), Y: general32FastSwap(y)})
}
}
func (mlp *BaseMultilayerPerceptron32) updateNoImprovementCount(earlyStopping bool, XVal, yVal blas32General) {
if earlyStopping {
//# compute validation score, use that for stopping
lastValidScore := mlp.score(XVal, yVal)
mlp.ValidationScores = append(mlp.ValidationScores, lastValidScore)
if mlp.Verbose {
fmt.Printf("Validation score: %g\n", lastValidScore)
}
// # update best parameters
// # use validationScores_, not lossCurve_
// # let's hope no-one overloads .score with mse
if lastValidScore < (mlp.BestValidationScore + mlp.Tol) {
mlp.NoImprovementCount++
} else {
mlp.NoImprovementCount = 0
}
if lastValidScore > mlp.BestValidationScore {
mlp.BestValidationScore = lastValidScore
copy(mlp.bestParameters, mlp.packedParameters)
}
}
lastLoss := mlp.LossCurve[len(mlp.LossCurve)-1]
if !earlyStopping {
if lastLoss > mlp.BestLoss-mlp.Tol {
mlp.NoImprovementCount++
} else {
mlp.NoImprovementCount = 0
}
}
if lastLoss < mlp.BestLoss {
mlp.BestLoss = lastLoss
}
}
func (mlp *BaseMultilayerPerceptron32) predictProbas(X, Y blas32General) {
_, nFeatures := X.Rows, X.Cols
layerUnits := append([]int{nFeatures}, mlp.HiddenLayerSizes...)
layerUnits = append(layerUnits, mlp.NOutputs)
// # Initialize layers
activations := []blas32General{X}
for i, nFanOut := range layerUnits[1:] {
var activation blas32General
if i == len(layerUnits)-2 {
activation = Y
} else {
activation = blas32General{Rows: X.Rows, Cols: nFanOut, Stride: nFanOut, Data: make([]float32, X.Rows*nFanOut)}
}
activations = append(activations, activation)
}
// # forward propagate
mlp.forwardPass(activations)
}
func (mlp *BaseMultilayerPerceptron32) predict(X, Y blas32General) {
var ybin General32
if mlp.lb == nil {
ybin = General32(Y)
} else {
_, ybin = mlp.lb.Transform(General32(X), General32(Y))
}
mlp.predictProbas(X, ybin.RawMatrix())
if mlp.lb != nil {
_, Yclasses := mlp.lb.InverseTransform(General32(X), ybin)
var tmp = General32(Y)
tmp.Copy(Yclasses)
Y = tmp.RawMatrix()
} else if mlp.IsClassifier() {
toLogits32(Y)
}
}
func (mlp *BaseMultilayerPerceptron32) score(X, Y blas32General) float32 {
H := blas32General{Rows: Y.Rows, Cols: Y.Cols, Stride: Y.Stride, Data: make([]float32, len(Y.Data))}
mlp.predict(X, H)
if mlp.LossFuncName != "square_loss" {
// accuracy
return accuracyScore32(Y, H)
}
// R2Score
return r2Score32(Y, H)
}
func (mlp *BaseMultilayerPerceptron32) validateInput(X, y blas32General, incremental bool) (Xout, youy blas32General) {
/*
X, y = check_X_y(X, y, accept_sparse=['csr', 'csc', 'coo'],
multi_output=True)
if y.ndim == 2 and y.shape[1] == 1:
y = column_or_1d(y, warn=True)
if not incremental:
self._label_binarizer = LabelBinarizer32()
self._label_binarizer.fit(y)
self.classes_ = self._label_binarizer.classes_
elif self.warm_start:
classes = unique_labels(y)
if set(classes) != set(self.classes_):
raise ValueError("warm_start can only be used where `y` has "
"the same classes as in the previous "
"call to fit. Previously got %s, `y` has %s" %
(self.classes_, classes))
else:
classes = unique_labels(y)
if len(np.setdiff1d(classes, self.classes_, assume_unique=True)):
raise ValueError("`y` has classes not in `self.classes_`."
" `self.classes_` has %s. 'y' has %s." %
(self.classes_, classes))
y = self._label_binarizer.transform(y)
return X, y
*/
return X, y
}
// Score for BaseMultiLayerPerceptron32 is R2Score or Accuracy depending on LossFuncName
func (mlp *BaseMultilayerPerceptron32) Score(Xmatrix, Ymatrix mat.Matrix) float64 {
X, Y := ToDense32(Xmatrix), ToDense32(Ymatrix)
nSamples, nOutputs := X.RawMatrix().Rows, mlp.GetNOutputs()
Ypred := blas32.General{Rows: nSamples, Cols: nOutputs, Stride: nOutputs, Data: make([]float32, nSamples*nOutputs)}
mlp.Predict(X, General32(Ypred))
if mlp.LossFuncName == "square_loss" {
return float64(r2Score32(blas32.General(Y), Ypred))
}
return float64(accuracyScore32(blas32.General(Y), Ypred))
}
// SGDOptimizer32 is the stochastic gradient descent optimizer
type SGDOptimizer32 struct {
Params []float32
LearningRateInit float32
LearningRate float32
PowerT float32
LRSchedule string
Momentum float32
Nesterov bool
velocities []float32
}