forked from goki/gotopy
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathra25.golden
1456 lines (1261 loc) · 59 KB
/
ra25.golden
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
# Copyright (c) 2019, The Emergent Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
#gofmt -gogi
# ra25 runs a simple random-associator four-layer leabra network
# that uses the standard supervised learning paradigm to learn
# mappings between 25 random input / output patterns
# defined over 5x5 input / output layers (i.e., 25 units)
package main
import "flag"
"fmt"
"log"
"math/rand"
"os"
"strconv"
"strings"
"time"
"github.com/emer/emergent/emer"
"github.com/emer/emergent/env"
"github.com/emer/emergent/netview"
"github.com/emer/emergent/params"
"github.com/emer/emergent/patgen"
"github.com/emer/emergent/prjn"
"github.com/emer/emergent/relpos"
"github.com/emer/etable/agg"
"github.com/emer/etable/eplot"
"github.com/emer/etable/etable"
"github.com/emer/etable/etensor"
_ "github.com/emer/etable/etview" # include to get gui views
"github.com/emer/etable/split"
"github.com/emer/leabra/leabra"
"github.com/goki/gi/gi"
"github.com/goki/gi/gimain"
"github.com/goki/gi/giv"
"github.com/goki/ki/ki"
"github.com/goki/ki/kit"
"github.com/goki/mat32"
def main():
TheSim.New()
TheSim.Config()
if len(os.Args) > 1:
TheSim.CmdArgs() # simple assumption is that any args = no gui -- could add explicit arg if you want
else:
gimain.Main(func: # this starts gui -- requires valid OpenGL display connection (e.g., X11)
guirun())
def guirun():
TheSim.Init()
win = TheSim.ConfigGui()
win.StartEventLoop()
# LogPrec is precision for saving float values in logs
LogPrec = 4
# ParamSets is the default set of parameters -- Base is always applied, and others can be optionally
# selected to apply on top of that
ParamSets = params.Sets(
(Name= "Base", Desc= "these are the best params", Sheets= params.Sheets(
"Network"= params.Sheet(
(Sel= "Prjn", Desc= "norm and momentum on works better, but wt bal is not better for smaller nets",
Params= params.Params(
"Prjn.Learn.Norm.On"= "true",
"Prjn.Learn.Momentum.On"= "true",
"Prjn.Learn.WtBal.On"= "false",
)),
(Sel= "Layer", Desc= "using default 1.8 inhib for all of network -- can explore",
Params= params.Params(
"Layer.Inhib.Layer.Gi"= "1.8",
"Layer.Act.Gbar.L"= "0.1", # set explictly, new default, a bit better vs 0.2
)),
(Sel= ".Back", Desc= "top-down back-projections MUST have lower relative weight scale, otherwise network hallucinates",
Params= params.Params(
"Prjn.WtScale.Rel"= "0.2",
)),
(Sel= "#Output", Desc= "output definitely needs lower inhib -- true for smaller layers in general",
Params= params.Params(
"Layer.Inhib.Layer.Gi"= "1.4",
)),
),
"Sim"= params.Sheet( # sim params apply to sim object
(Sel= "Sim", Desc= "best params always finish in this time",
Params= params.Params(
"Sim.MaxEpcs"= "50",
)),
),
)),
(Name= "DefaultInhib", Desc= "output uses default inhib instead of lower", Sheets= params.Sheets(
"Network"= params.Sheet(
(Sel= "#Output", Desc= "go back to default",
Params= params.Params(
"Layer.Inhib.Layer.Gi"= "1.8",
)),
),
"Sim"= params.Sheet( # sim params apply to sim object
(Sel= "Sim", Desc= "takes longer -- generally doesn't finish..",
Params= params.Params(
"Sim.MaxEpcs"= "100",
)),
),
)),
(Name= "NoMomentum", Desc= "no momentum or normalization", Sheets= params.Sheets(
"Network"= params.Sheet(
(Sel= "Prjn", Desc= "no norm or momentum",
Params= params.Params(
"Prjn.Learn.Norm.On"= "false",
"Prjn.Learn.Momentum.On"= "false",
)),
),
)),
(Name= "WtBalOn", Desc= "try with weight bal on", Sheets= params.Sheets(
"Network"= params.Sheet(
(Sel= "Prjn", Desc= "weight bal on",
Params= params.Params(
"Prjn.Learn.WtBal.On"= "true",
)),
),
)),
)
class Sim(pygiv.ClassViewObj):
# Sim encapsulates the entire simulation model, and we define all the
# functionality as methods on this struct. This structure keeps all relevant
# state information organized and available without having to pass everything around
# as arguments to methods, and provides the core GUI interface (note the view tags
# for the fields which provide hints to how things should be displayed).
"""
Sim encapsulates the entire simulation model, and we define all the
functionality as methods on this struct. This structure keeps all relevant
state information organized and available without having to pass everything around
as arguments to methods, and provides the core GUI interface (note the view tags
for the fields which provide hints to how things should be displayed).
"""
def __init__(self):
super(Sim, self).__init__()
self.Net = leabra.Network()
self.SetTags("Net", 'view:"no-inline" desc:"the network -- click to view / edit parameters for layers, prjns, etc"')
self.Pats = etable.Table()
self.SetTags("Pats", 'view:"no-inline" desc:"the training patterns to use"')
self.TrnEpcLog = etable.Table()
self.SetTags("TrnEpcLog", 'view:"no-inline" desc:"training epoch-level log data"')
self.TstEpcLog = etable.Table()
self.SetTags("TstEpcLog", 'view:"no-inline" desc:"testing epoch-level log data"')
self.TstTrlLog = etable.Table()
self.SetTags("TstTrlLog", 'view:"no-inline" desc:"testing trial-level log data"')
self.TstErrLog = etable.Table()
self.SetTags("TstErrLog", 'view:"no-inline" desc:"log of all test trials where errors were made"')
self.TstErrStats = etable.Table()
self.SetTags("TstErrStats", 'view:"no-inline" desc:"stats on test trials where errors were made"')
self.TstCycLog = etable.Table()
self.SetTags("TstCycLog", 'view:"no-inline" desc:"testing cycle-level log data"')
self.RunLog = etable.Table()
self.SetTags("RunLog", 'view:"no-inline" desc:"summary log of each run"')
self.RunStats = etable.Table()
self.SetTags("RunStats", 'view:"no-inline" desc:"aggregate stats on all runs"')
self.Params = params.Sets()
self.SetTags("Params", 'view:"no-inline" desc:"full collection of param sets"')
self.ParamSet = str()
self.SetTags("ParamSet", 'desc:"which set of *additional* parameters to use -- always applies Base and optionaly this next if set -- can use multiple names separated by spaces (don\'t put spaces in ParamSet names!)"')
self.Tag = str()
self.SetTags("Tag", 'desc:"extra tag string to add to any file names output from sim (e.g., weights files, log files, params for run)"')
self.MaxRuns = int()
self.SetTags("MaxRuns", 'desc:"maximum number of model runs to perform"')
self.MaxEpcs = int()
self.SetTags("MaxEpcs", 'desc:"maximum number of epochs to run per model run"')
self.NZeroStop = int()
self.SetTags("NZeroStop", 'desc:"if a positive number, training will stop after this many epochs with zero SSE"')
self.TrainEnv = env.FixedTable()
self.SetTags("TrainEnv", 'desc:"Training environment -- contains everything about iterating over input / output patterns over training"')
self.TestEnv = env.FixedTable()
self.SetTags("TestEnv", 'desc:"Testing environment -- manages iterating over testing"')
self.Time = leabra.Time()
self.SetTags("Time", 'desc:"leabra timing parameters and state"')
self.ViewOn = bool()
self.SetTags("ViewOn", 'desc:"whether to update the network view while running"')
self.TrainUpdt = leabra.TimeScales()
self.SetTags("TrainUpdt", 'desc:"at what time scale to update the display during training? Anything longer than Epoch updates at Epoch in this model"')
self.TestUpdt = leabra.TimeScales()
self.SetTags("TestUpdt", 'desc:"at what time scale to update the display during testing? Anything longer than Epoch updates at Epoch in this model"')
self.TestInterval = int()
self.SetTags("TestInterval", 'desc:"how often to run through all the test patterns, in terms of training epochs -- can use 0 or -1 for no testing"')
self.LayStatNms = []string
self.SetTags("LayStatNms", 'desc:"names of layers to collect more detailed stats on (avg act, etc)"')
# statistics: note use float64 as that is best for etable.Table
self.TrlErr = float()
self.SetTags("TrlErr", 'inactive:"+" desc:"1 if trial was error, 0 if correct -- based on SSE = 0 (subject to .5 unit-wise tolerance)"')
self.TrlSSE = float()
self.SetTags("TrlSSE", 'inactive:"+" desc:"current trial\'s sum squared error"')
self.TrlAvgSSE = float()
self.SetTags("TrlAvgSSE", 'inactive:"+" desc:"current trial\'s average sum squared error"')
self.TrlCosDiff = float()
self.SetTags("TrlCosDiff", 'inactive:"+" desc:"current trial\'s cosine difference"')
self.EpcSSE = float()
self.SetTags("EpcSSE", 'inactive:"+" desc:"last epoch\'s total sum squared error"')
self.EpcAvgSSE = float()
self.SetTags("EpcAvgSSE", 'inactive:"+" desc:"last epoch\'s average sum squared error (average over trials, and over units within layer)"')
self.EpcPctErr = float()
self.SetTags("EpcPctErr", 'inactive:"+" desc:"last epoch\'s average TrlErr"')
self.EpcPctCor = float()
self.SetTags("EpcPctCor", 'inactive:"+" desc:"1 - last epoch\'s average TrlErr"')
self.EpcCosDiff = float()
self.SetTags("EpcCosDiff", 'inactive:"+" desc:"last epoch\'s average cosine difference for output layer (a normalized error measure, maximum of 1 when the minus phase exactly matches the plus)"')
self.EpcPerTrlMSec = float()
self.SetTags("EpcPerTrlMSec", 'inactive:"+" desc:"how long did the epoch take per trial in wall-clock milliseconds"')
self.FirstZero = int()
self.SetTags("FirstZero", 'inactive:"+" desc:"epoch at when SSE first went to zero"')
self.NZero = int()
self.SetTags("NZero", 'inactive:"+" desc:"number of epochs in a row with zero SSE"')
# internal state - view:"-"
self.SumErr = float()
self.SetTags("SumErr", 'view:"-" inactive:"+" desc:"sum to increment as we go through epoch"')
self.SumSSE = float()
self.SetTags("SumSSE", 'view:"-" inactive:"+" desc:"sum to increment as we go through epoch"')
self.SumAvgSSE = float()
self.SetTags("SumAvgSSE", 'view:"-" inactive:"+" desc:"sum to increment as we go through epoch"')
self.SumCosDiff = float()
self.SetTags("SumCosDiff", 'view:"-" inactive:"+" desc:"sum to increment as we go through epoch"')
self.Win = gi.Window()
self.SetTags("Win", 'view:"-" desc:"main GUI window"')
self.NetView = netview.NetView()
self.SetTags("NetView", 'view:"-" desc:"the network viewer"')
self.ToolBar = gi.ToolBar()
self.SetTags("ToolBar", 'view:"-" desc:"the master toolbar"')
self.TrnEpcPlot = eplot.Plot2D()
self.SetTags("TrnEpcPlot", 'view:"-" desc:"the training epoch plot"')
self.TstEpcPlot = eplot.Plot2D()
self.SetTags("TstEpcPlot", 'view:"-" desc:"the testing epoch plot"')
self.TstTrlPlot = eplot.Plot2D()
self.SetTags("TstTrlPlot", 'view:"-" desc:"the test-trial plot"')
self.TstCycPlot = eplot.Plot2D()
self.SetTags("TstCycPlot", 'view:"-" desc:"the test-cycle plot"')
self.RunPlot = eplot.Plot2D()
self.SetTags("RunPlot", 'view:"-" desc:"the run plot"')
self.TrnEpcFile = os.File()
self.SetTags("TrnEpcFile", 'view:"-" desc:"log file"')
self.RunFile = os.File()
self.SetTags("RunFile", 'view:"-" desc:"log file"')
self.ValsTsrs = {}
self.SetTags("ValsTsrs", 'view:"-" desc:"for holding layer values"')
self.SaveWts = bool()
self.SetTags("SaveWts", 'view:"-" desc:"for command-line run only, auto-save final weights after each run"')
self.NoGui = bool()
self.SetTags("NoGui", 'view:"-" desc:"if true, runing in no GUI mode"')
self.LogSetParams = bool()
self.SetTags("LogSetParams", 'view:"-" desc:"if true, print message for all params that are set"')
self.IsRunning = bool()
self.SetTags("IsRunning", 'view:"-" desc:"true if sim is running"')
self.StopNow = bool()
self.SetTags("StopNow", 'view:"-" desc:"flag to stop running"')
self.NeedsNewRun = bool()
self.SetTags("NeedsNewRun", 'view:"-" desc:"flag to initialize NewRun if last one finished"')
self.RndSeed = int64()
self.SetTags("RndSeed", 'view:"-" desc:"the current random seed"')
self.LastEpcTime = time.Time()
self.SetTags("LastEpcTime", 'view:"-" desc:"timer for last epoch"')
def New(ss):
"""
New creates new blank elements and initializes defaults
"""
ss.Net = leabra.Network()
ss.Pats = etable.Table()
ss.TrnEpcLog = etable.Table()
ss.TstEpcLog = etable.Table()
ss.TstTrlLog = etable.Table()
ss.TstCycLog = etable.Table()
ss.RunLog = etable.Table()
ss.RunStats = etable.Table()
ss.Params = ParamSets
ss.RndSeed = 1
ss.ViewOn = True
ss.TrainUpdt = leabra.AlphaCycle
ss.TestUpdt = leabra.Cycle
ss.TestInterval = 5
ss.LayStatNms = go.Slice_string(["Hidden1", "Hidden2", "Output"])
def Config(ss):
"""
Config configures all the elements using the standard functions
"""
ss.OpenPats()
ss.ConfigEnv()
ss.ConfigNet(ss.Net)
ss.ConfigTrnEpcLog(ss.TrnEpcLog)
ss.ConfigTstEpcLog(ss.TstEpcLog)
ss.ConfigTstTrlLog(ss.TstTrlLog)
ss.ConfigTstCycLog(ss.TstCycLog)
ss.ConfigRunLog(ss.RunLog)
def ConfigEnv(ss):
if ss.MaxRuns == 0: # allow user override
ss.MaxRuns = 10
if ss.MaxEpcs == 0: # allow user override
ss.MaxEpcs = 50
ss.NZeroStop = 5
ss.TrainEnv.Nm = "TrainEnv"
ss.TrainEnv.Dsc = "training params and state"
ss.TrainEnv.Table = etable.NewIdxView(ss.Pats)
ss.TrainEnv.Validate()
ss.TrainEnv.Run.Max = ss.MaxRuns # note: we are not setting epoch max -- do that manually
ss.TestEnv.Nm = "TestEnv"
ss.TestEnv.Dsc = "testing params and state"
ss.TestEnv.Table = etable.NewIdxView(ss.Pats)
ss.TestEnv.Sequential = True
ss.TestEnv.Validate()
# note: to create a train / test split of pats, do this:
# all := etable.NewIdxView(ss.Pats)
# splits, _ := split.Permuted(all, []float64{.8, .2}, []string{"Train", "Test"})
# ss.TrainEnv.Table = splits.Splits[0]
# ss.TestEnv.Table = splits.Splits[1]
ss.TrainEnv.Init(0)
ss.TestEnv.Init(0)
def ConfigNet(ss, net):
net.InitName(net, "RA25")
inp = net.AddLayer2D("Input", 5, 5, emer.Input)
hid1 = net.AddLayer2D("Hidden1", 7, 7, emer.Hidden)
hid2 = net.AddLayer4D("Hidden2", 2, 4, 3, 2, emer.Hidden)
out = net.AddLayer2D("Output", 5, 5, emer.Target)
# use this to position layers relative to each other
# default is Above, YAlign = Front, XAlign = Center
hid2.SetRelPos(relpos.Rel(Rel= relpos.RightOf, Other= "Hidden1", YAlign= relpos.Front, Space= 2))
# note: see emergent/prjn module for all the options on how to connect
# NewFull returns a new prjn.Full connectivity pattern
full = prjn.NewFull()
net.ConnectLayers(inp, hid1, full, emer.Forward)
net.BidirConnectLayers(hid1, hid2, full)
net.BidirConnectLayers(hid2, out, full)
# note: can set these to do parallel threaded computation across multiple cpus
# not worth it for this small of a model, but definitely helps for larger ones
# if Thread {
# hid2.SetThread(1)
# out.SetThread(1)
# }
# note: if you wanted to change a layer type from e.g., Target to Compare, do this:
# out.SetType(emer.Compare)
# that would mean that the output layer doesn't reflect target values in plus phase
# and thus removes error-driven learning -- but stats are still computed.
net.Defaults()
ss.SetParams("Network", ss.LogSetParams) # only set Network params
err = net.Build()
if err != go.nil:
log.Println(err)
return
net.InitWts()
def Init(ss):
"""
Init restarts the run, and initializes everything, including network weights
# re-config env just in case a different set of patterns was
and resets the epoch log table
# selected or patterns have been modified etc
"""
rand.Seed(ss.RndSeed)
ss.ConfigEnv()
ss.StopNow = False
ss.SetParams("", ss.LogSetParams) # all sheets
ss.NewRun()
ss.UpdateView(True)
def NewRndSeed(ss):
"""
NewRndSeed gets a new random seed based on current time -- otherwise uses
the same random seed for every run
"""
ss.RndSeed = time.Now().UnixNano()
def Counters(ss, train):
"""
Counters returns a string of the current counter state
use tabs to achieve a reasonable formatting overall
and add a few tabs at the end to allow for expansion..
"""
if train:
return "Run:\t%d\tEpoch:\t%d\tTrial:\t%d\tCycle:\t%d\tName:\t%s\t\t\t" % (ss.TrainEnv.Run.Cur, ss.TrainEnv.Epoch.Cur, ss.TrainEnv.Trial.Cur, ss.Time.Cycle, ss.TrainEnv.TrialName.Cur)
else:
return "Run:\t%d\tEpoch:\t%d\tTrial:\t%d\tCycle:\t%d\tName:\t%s\t\t\t" % (ss.TrainEnv.Run.Cur, ss.TrainEnv.Epoch.Cur, ss.TestEnv.Trial.Cur, ss.Time.Cycle, ss.TestEnv.TrialName.Cur)
def UpdateView(ss, train):
if ss.NetView != go.nil and ss.NetView.IsVisible():
ss.NetView.Record(ss.Counters(train))
ss.NetView.GoUpdate()
def AlphaCyc(ss, train):
"""
# ss.Win.PollEvents() // this can be used instead of running in a separate goroutine
AlphaCyc runs one alpha-cycle (100 msec, 4 quarters) of processing.
External inputs must have already been applied prior to calling,
using ApplyExt method on relevant layers (see TrainTrial, TestTrial).
# update prior weight changes at start, so any DWt values remain visible at end
# you might want to do this less frequently to achieve a mini-batch update
# in which case, move it out to the TrainTrial method where the relevant
# counters are being dealt with.
If train is true, then learning DWt or WtFmDWt calls are made.
Handles netview updating within scope of AlphaCycle
"""
viewUpdt = ss.TrainUpdt
if not train:
viewUpdt = ss.TestUpdt
if train:
ss.Net.WtFmDWt()
ss.Net.AlphaCycInit()
ss.Time.AlphaCycStart()
for qtr in range(4):
for cyc in range(ss.Time.CycPerQtr):
ss.Net.Cycle(ss.Time)
if not train:
ss.LogTstCyc(ss.TstCycLog, ss.Time.Cycle)
ss.Time.CycleInc()
if ss.ViewOn:
switch viewUpdt:
if leabra.Cycle:
if cyc != ss.Time.CycPerQtr-1: # will be updated by quarter
ss.UpdateView(train)
if leabra.FastSpike:
if (cyc+1)%10 == 0:
ss.UpdateView(train)
ss.Net.QuarterFinal(ss.Time)
ss.Time.QuarterInc()
if ss.ViewOn:
switch :
if viewUpdt <= leabra.Quarter:
ss.UpdateView(train)
if viewUpdt == leabra.Phase:
if qtr >= 2:
ss.UpdateView(train)
if train:
ss.Net.DWt()
if ss.ViewOn and viewUpdt == leabra.AlphaCycle:
ss.UpdateView(train)
if not train:
ss.TstCycPlot.GoUpdate() # make sure up-to-date at end
def ApplyInputs(ss, en):
"""
ApplyInputs applies input patterns from given envirbonment.
It is good practice to have this be a separate method with appropriate
args so that it can be used for various different contexts
(training, testing, etc).
"""
lays = go.Slice_string(["Input", "Output"])
for lnm in lays :
ly = leabra.LeabraLayer(ss.Net.LayerByName(lnm)).AsLeabra()
pats = en.State(ly.Nm)
if pats != go.nil:
ly.ApplyExt(pats)
def TrainTrial(ss):
"""
TrainTrial runs one trial of training using TrainEnv
"""
if ss.NeedsNewRun:
ss.NewRun()
ss.TrainEnv.Step()
# Key to query counters FIRST because current state is in NEXT epoch
# if epoch counter has changed
epc, _, chg = ss.TrainEnv.Counter(env.Epoch)
if chg:
ss.LogTrnEpc(ss.TrnEpcLog)
if ss.ViewOn and ss.TrainUpdt > leabra.AlphaCycle:
ss.UpdateView(True)
if ss.TestInterval > 0 and epc%ss.TestInterval == 0: # note: epc is *next* so won't trigger first time
ss.TestAll()
if epc >= ss.MaxEpcs or (ss.NZeroStop > 0 and ss.NZero >= ss.NZeroStop):
# done with training..
ss.RunEnd()
if ss.TrainEnv.Run.Incr(): # we are done!
ss.StopNow = True
return
else:
ss.NeedsNewRun = True
return
ss.ApplyInputs(ss.TrainEnv)
ss.AlphaCyc(True) # train
ss.TrialStats(True) # accumulate
def RunEnd(ss):
"""
RunEnd is called at the end of a run -- save weights, record final log, etc here
"""
ss.LogRun(ss.RunLog)
if ss.SaveWts:
fnm = ss.WeightsFileName()
print("Saving Weights to: %s\n" % fnm)
ss.Net.SaveWtsJSON(gi.FileName(fnm))
def NewRun(ss):
"""
NewRun intializes a new run of the model, using the TrainEnv.Run counter
for the new run value
"""
run = ss.TrainEnv.Run.Cur
ss.TrainEnv.Init(run)
ss.TestEnv.Init(run)
ss.Time.Reset()
ss.Net.InitWts()
ss.InitStats()
ss.TrnEpcLog.SetNumRows(0)
ss.TstEpcLog.SetNumRows(0)
ss.NeedsNewRun = False
def InitStats(ss):
"""
InitStats initializes all the statistics, especially important for the
cumulative epoch stats -- called at start of new run
"""
ss.SumErr = 0
ss.SumSSE = 0
ss.SumAvgSSE = 0
ss.SumCosDiff = 0
ss.FirstZero = -1
ss.NZero = 0
ss.TrlErr = 0
ss.TrlSSE = 0
ss.TrlAvgSSE = 0
ss.EpcSSE = 0
ss.EpcAvgSSE = 0
ss.EpcPctErr = 0
ss.EpcCosDiff = 0
def TrialStats(ss, accum):
"""
TrialStats computes the trial-level statistics and adds them to the epoch accumulators if
accum is true. Note that we're accumulating stats here on the Sim side so the
core algorithm side remains as simple as possible, and doesn't need to worry about
different time-scales over which stats could be accumulated etc.
You can also aggregate directly from log data, as is done for testing stats
"""
out = leabra.LeabraLayer(ss.Net.LayerByName("Output")).AsLeabra()
ss.TrlCosDiff = float(out.CosDiff.Cos)
ss.TrlSSE, ss.TrlAvgSSE = out.MSE(0.5)
if ss.TrlSSE > 0:
ss.TrlErr = 1
else:
ss.TrlErr = 0
if accum:
ss.SumErr += ss.TrlErr
ss.SumSSE += ss.TrlSSE
ss.SumAvgSSE += ss.TrlAvgSSE
ss.SumCosDiff += ss.TrlCosDiff
def TrainEpoch(ss):
"""
TrainEpoch runs training trials for remainder of this epoch
"""
ss.StopNow = False
curEpc = ss.TrainEnv.Epoch.Cur
while True:
ss.TrainTrial()
if ss.StopNow or ss.TrainEnv.Epoch.Cur != curEpc:
break
ss.Stopped()
def TrainRun(ss):
"""
TrainRun runs training trials for remainder of run
"""
ss.StopNow = False
curRun = ss.TrainEnv.Run.Cur
while True:
ss.TrainTrial()
if ss.StopNow or ss.TrainEnv.Run.Cur != curRun:
break
ss.Stopped()
def Train(ss):
"""
Train runs the full training from this point onward
"""
ss.StopNow = False
while True:
ss.TrainTrial()
if ss.StopNow:
break
ss.Stopped()
def Stop(ss):
"""
Stop tells the sim to stop running
"""
ss.StopNow = True
def Stopped(ss):
"""
Stopped is called when a run method stops running -- updates the IsRunning flag and toolbar
"""
ss.IsRunning = False
if ss.Win != go.nil:
vp = ss.Win.WinViewport2D()
if ss.ToolBar != go.nil:
ss.ToolBar.UpdateActions()
vp.SetNeedsFullRender()
def SaveWeights(ss, filename):
"""
SaveWeights saves the network weights -- when called with giv.CallMethod
it will auto-prompt for filename
"""
ss.Net.SaveWtsJSON(filename)
def TestTrial(ss, returnOnChg):
"""
TestTrial runs one trial of testing -- always sequentially presented inputs
"""
ss.TestEnv.Step()
_, _, chg = ss.TestEnv.Counter(env.Epoch)
if chg:
if ss.ViewOn and ss.TestUpdt > leabra.AlphaCycle:
ss.UpdateView(False)
ss.LogTstEpc(ss.TstEpcLog)
if returnOnChg:
return
ss.ApplyInputs(ss.TestEnv)
ss.AlphaCyc(False)
ss.TrialStats(False)
ss.LogTstTrl(ss.TstTrlLog)
def TestItem(ss, idx):
"""
TestItem tests given item which is at given index in test item list
"""
cur = ss.TestEnv.Trial.Cur
ss.TestEnv.Trial.Cur = idx
ss.TestEnv.SetTrialName()
ss.ApplyInputs(ss.TestEnv)
ss.AlphaCyc(False)
ss.TrialStats(False)
ss.TestEnv.Trial.Cur = cur
def TestAll(ss):
"""
TestAll runs through the full set of testing items
"""
ss.TestEnv.Init(ss.TrainEnv.Run.Cur)
while True:
ss.TestTrial(True)
_, _, chg = ss.TestEnv.Counter(env.Epoch)
if chg or ss.StopNow:
break
def RunTestAll(ss):
"""
RunTestAll runs through the full set of testing items, has stop running = false at end -- for gui
"""
ss.StopNow = False
ss.TestAll()
ss.Stopped()
def ParamsName(ss):
"""
ParamsName returns name of current set of parameters
"""
if ss.ParamSet == "":
return "Base"
return ss.ParamSet
def SetParams(ss, sheet, setMsg):
"""
SetParams sets the params for "Base" and then current ParamSet.
If sheet is empty, then it applies all avail sheets (e.g., Network, Sim)
otherwise just the named sheet
if setMsg = true then we output a message for each param that was set.
"""
if sheet == "":
ss.Params.ValidateSheets(go.Slice_string(["Network", "Sim"]))
err = ss.SetParamsSet("Base", sheet, setMsg)
if ss.ParamSet != "" and ss.ParamSet != "Base":
sps = ss.ParamSet.split()
for ps in sps :
err = ss.SetParamsSet(ps, sheet, setMsg)
return err
def SetParamsSet(ss, setNm, sheet, setMsg):
"""
SetParamsSet sets the params for given params.Set name.
If sheet is empty, then it applies all avail sheets (e.g., Network, Sim)
otherwise just the named sheet
if setMsg = true then we output a message for each param that was set.
"""
pset, err = ss.Params.SetByNameTry(setNm)
if err != go.nil:
return err
if sheet == "" or sheet == "Network":
netp, ok = pset.Sheets["Network"]
if ok:
ss.Net.ApplyParams(netp, setMsg)
if sheet == "" or sheet == "Sim":
simp, ok = pset.Sheets["Sim"]
if ok:
simp.Apply(ss, setMsg)
return err
def ConfigPats(ss):
dt = ss.Pats
dt.SetMetaData("name", "TrainPats")
dt.SetMetaData("desc", "Training patterns")
dt.SetFromSchema(etable.Schema(
("Name", etensor.STRING, go.nil, go.nil),
("Input", etensor.FLOAT32, go.Slice_int([5, 5]]), go.Slice_string(["Y", "X")),
("Output", etensor.FLOAT32, go.Slice_int([5, 5]]), go.Slice_string(["Y", "X")),
), 25)
patgen.PermutedBinaryRows(dt.Cols[1], 6, 1, 0)
patgen.PermutedBinaryRows(dt.Cols[2], 6, 1, 0)
dt.SaveCSV("random_5x5_25_gen.csv", etable.Comma, etable.Headers)
def OpenPats(ss):
dt = ss.Pats
dt.SetMetaData("name", "TrainPats")
dt.SetMetaData("desc", "Training patterns")
err = dt.OpenCSV("random_5x5_25.tsv", etable.Tab)
if err != go.nil:
log.Println(err)
def ValsTsr(ss, name):
"""
ValsTsr gets value tensor of given name, creating if not yet made
"""
if ss.ValsTsrs == go.nil:
ss.ValsTsrs = make({})
tsr, ok = ss.ValsTsrs[name]
if not ok:
tsr = etensor.Float32()
ss.ValsTsrs[name] = tsr
return tsr
def RunName(ss):
"""
RunName returns a name for this run that combines Tag and Params -- add this to
any file names that are saved.
"""
if ss.Tag != "":
return ss.Tag + "_" + ss.ParamsName()
else:
return ss.ParamsName()
def RunEpochName(ss, run, epc):
"""
RunEpochName returns a string with the run and epoch numbers with leading zeros, suitable
for using in weights file names. Uses 3, 5 digits for each.
"""
return "%03d_%05d" % (run, epc)
def WeightsFileName(ss):
"""
WeightsFileName returns default current weights file name
"""
return ss.Net.Nm + "_" + ss.RunName() + "_" + ss.RunEpochName(ss.TrainEnv.Run.Cur, ss.TrainEnv.Epoch.Cur) + ".wts"
def LogFileName(ss, lognm):
"""
LogFileName returns default log file name
"""
return ss.Net.Nm + "_" + ss.RunName() + "_" + lognm + ".tsv"
def LogTrnEpc(ss, dt):
"""
LogTrnEpc adds data from current epoch to the TrnEpcLog table.
computes epoch averages prior to logging.
"""
row = dt.Rows
dt.SetNumRows(row + 1)
epc = ss.TrainEnv.Epoch.Prv
nt = float(len(ss.TrainEnv.Order))
ss.EpcSSE = ss.SumSSE / nt
ss.SumSSE = 0
ss.EpcAvgSSE = ss.SumAvgSSE / nt
ss.SumAvgSSE = 0
ss.EpcPctErr = float(ss.SumErr) / nt
ss.SumErr = 0
ss.EpcPctCor = 1 - ss.EpcPctErr
ss.EpcCosDiff = ss.SumCosDiff / nt
ss.SumCosDiff = 0
if ss.FirstZero < 0 and ss.EpcPctErr == 0:
ss.FirstZero = epc
if ss.EpcPctErr == 0:
ss.NZero += 1
else:
ss.NZero = 0
if ss.LastEpcTime.IsZero():
ss.EpcPerTrlMSec = 0
else:
iv = time.Now().Sub(ss.LastEpcTime)
ss.EpcPerTrlMSec = float(iv) / (nt * float(time.Millisecond))
ss.LastEpcTime = time.Now()
dt.SetCellFloat("Run", row, float(ss.TrainEnv.Run.Cur))
dt.SetCellFloat("Epoch", row, float(epc))
dt.SetCellFloat("SSE", row, ss.EpcSSE)
dt.SetCellFloat("AvgSSE", row, ss.EpcAvgSSE)
dt.SetCellFloat("PctErr", row, ss.EpcPctErr)
dt.SetCellFloat("PctCor", row, ss.EpcPctCor)
dt.SetCellFloat("CosDiff", row, ss.EpcCosDiff)
dt.SetCellFloat("PerTrlMSec", row, ss.EpcPerTrlMSec)
for lnm in ss.LayStatNms :
ly = leabra.LeabraLayer(ss.Net.LayerByName(lnm)).AsLeabra()
dt.SetCellFloat(ly.Nm+"_ActAvg", row, float(ly.Pools[0].ActAvg.ActPAvgEff))
ss.TrnEpcPlot.GoUpdate()
if ss.TrnEpcFile != go.nil:
if ss.TrainEnv.Run.Cur == 0 and epc == 0:
dt.WriteCSVHeaders(ss.TrnEpcFile, etable.Tab)
dt.WriteCSVRow(ss.TrnEpcFile, row, etable.Tab)
def ConfigTrnEpcLog(ss, dt):
dt.SetMetaData("name", "TrnEpcLog")
dt.SetMetaData("desc", "Record of performance over epochs of training")
dt.SetMetaData("read-only", "true")
dt.SetMetaData("precision", str(LogPrec))
sch = etable.Schema(
("Run", etensor.INT64, go.nil, go.nil),
("Epoch", etensor.INT64, go.nil, go.nil),
("SSE", etensor.FLOAT64, go.nil, go.nil),
("AvgSSE", etensor.FLOAT64, go.nil, go.nil),
("PctErr", etensor.FLOAT64, go.nil, go.nil),
("PctCor", etensor.FLOAT64, go.nil, go.nil),
("CosDiff", etensor.FLOAT64, go.nil, go.nil),
("PerTrlMSec", etensor.FLOAT64, go.nil, go.nil),
)
for lnm in ss.LayStatNms :
sch.append( etable.Column(lnm + "_ActAvg", etensor.FLOAT64, go.nil, go.nil))
dt.SetFromSchema(sch, 0)
def ConfigTrnEpcPlot(ss, plt, dt):
plt.Params.Title = "Leabra Random Associator 25 Epoch Plot"
plt.Params.XAxisCol = "Epoch"
plt.SetTable(dt)
plt.SetColParams("Run", eplot.Off, eplot.FixMin, 0, eplot.FloatMax, 0)
plt.SetColParams("Epoch", eplot.Off, eplot.FixMin, 0, eplot.FloatMax, 0)
plt.SetColParams("SSE", eplot.Off, eplot.FixMin, 0, eplot.FloatMax, 0)
plt.SetColParams("AvgSSE", eplot.Off, eplot.FixMin, 0, eplot.FloatMax, 0)
plt.SetColParams("PctErr", eplot.On, eplot.FixMin, 0, eplot.FixMax, 1)
plt.SetColParams("PctCor", eplot.On, eplot.FixMin, 0, eplot.FixMax, 1)
plt.SetColParams("CosDiff", eplot.Off, eplot.FixMin, 0, eplot.FixMax, 1)
plt.SetColParams("PerTrlMSec", eplot.Off, eplot.FixMin, 0, eplot.FloatMax, 0)
for lnm in ss.LayStatNms :
plt.SetColParams(lnm+"_ActAvg", eplot.Off, eplot.FixMin, 0, eplot.FixMax, .5)
return plt
def LogTstTrl(ss, dt):
"""
LogTstTrl adds data from current trial to the TstTrlLog table.
log always contains number of testing items
"""
epc = ss.TrainEnv.Epoch.Prv
inp = leabra.LeabraLayer(ss.Net.LayerByName("Input")).AsLeabra()
out = leabra.LeabraLayer(ss.Net.LayerByName("Output")).AsLeabra()
trl = ss.TestEnv.Trial.Cur
row = trl
if dt.Rows <= row:
dt.SetNumRows(row + 1)
dt.SetCellFloat("Run", row, float(ss.TrainEnv.Run.Cur))
dt.SetCellFloat("Epoch", row, float(epc))
dt.SetCellFloat("Trial", row, float(trl))
dt.SetCellString("TrialName", row, ss.TestEnv.TrialName.Cur)
dt.SetCellFloat("Err", row, ss.TrlErr)
dt.SetCellFloat("SSE", row, ss.TrlSSE)
dt.SetCellFloat("AvgSSE", row, ss.TrlAvgSSE)
dt.SetCellFloat("CosDiff", row, ss.TrlCosDiff)
for lnm in ss.LayStatNms :
ly = leabra.LeabraLayer(ss.Net.LayerByName(lnm)).AsLeabra()
dt.SetCellFloat(ly.Nm+" ActM.Avg", row, float(ly.Pools[0].ActM.Avg))
ivt = ss.ValsTsr("Input")
ovt = ss.ValsTsr("Output")
inp.UnitValsTensor(ivt, "Act")
dt.SetCellTensor("InAct", row, ivt)
out.UnitValsTensor(ovt, "ActM")
dt.SetCellTensor("OutActM", row, ovt)
out.UnitValsTensor(ovt, "ActP")
dt.SetCellTensor("OutActP", row, ovt)
ss.TstTrlPlot.GoUpdate()
def ConfigTstTrlLog(ss, dt):
inp = leabra.LeabraLayer(ss.Net.LayerByName("Input")).AsLeabra()
out = leabra.LeabraLayer(ss.Net.LayerByName("Output")).AsLeabra()
dt.SetMetaData("name", "TstTrlLog")
dt.SetMetaData("desc", "Record of testing per input pattern")
dt.SetMetaData("read-only", "true")
dt.SetMetaData("precision", str(LogPrec))
nt = ss.TestEnv.Table.Len() # number in view
sch = etable.Schema(
("Run", etensor.INT64, go.nil, go.nil),
("Epoch", etensor.INT64, go.nil, go.nil),
("Trial", etensor.INT64, go.nil, go.nil),
("TrialName", etensor.STRING, go.nil, go.nil),
("Err", etensor.FLOAT64, go.nil, go.nil),
("SSE", etensor.FLOAT64, go.nil, go.nil),
("AvgSSE", etensor.FLOAT64, go.nil, go.nil),
("CosDiff", etensor.FLOAT64, go.nil, go.nil),
)
for lnm in ss.LayStatNms :
sch.append( etable.Column(lnm + " ActM.Avg", etensor.FLOAT64, go.nil, go.nil))
sch.append( etable.Schema(
("InAct", etensor.FLOAT64, inp.Shp.Shp, go.nil),
("OutActM", etensor.FLOAT64, out.Shp.Shp, go.nil),
("OutActP", etensor.FLOAT64, out.Shp.Shp, go.nil),
)...)
dt.SetFromSchema(sch, nt)
def ConfigTstTrlPlot(ss, plt, dt):
plt.Params.Title = "Leabra Random Associator 25 Test Trial Plot"
plt.Params.XAxisCol = "Trial"
plt.SetTable(dt)
# order of params: on, fixMin, min, fixMax, max
plt.SetColParams("Run", eplot.Off, eplot.FixMin, 0, eplot.FloatMax, 0)
plt.SetColParams("Epoch", eplot.Off, eplot.FixMin, 0, eplot.FloatMax, 0)
plt.SetColParams("Trial", eplot.Off, eplot.FixMin, 0, eplot.FloatMax, 0)
plt.SetColParams("TrialName", eplot.Off, eplot.FixMin, 0, eplot.FloatMax, 0)
plt.SetColParams("Err", eplot.Off, eplot.FixMin, 0, eplot.FloatMax, 0)
plt.SetColParams("SSE", eplot.Off, eplot.FixMin, 0, eplot.FloatMax, 0)
plt.SetColParams("AvgSSE", eplot.On, eplot.FixMin, 0, eplot.FloatMax, 0)
plt.SetColParams("CosDiff", eplot.On, eplot.FixMin, 0, eplot.FixMax, 1)
for lnm in ss.LayStatNms :
plt.SetColParams(lnm+" ActM.Avg", eplot.Off, eplot.FixMin, 0, eplot.FixMax, .5)
plt.SetColParams("InAct", eplot.Off, eplot.FixMin, 0, eplot.FixMax, 1)
plt.SetColParams("OutActM", eplot.Off, eplot.FixMin, 0, eplot.FixMax, 1)
plt.SetColParams("OutActP", eplot.Off, eplot.FixMin, 0, eplot.FixMax, 1)
return plt
def LogTstEpc(ss, dt):
row = dt.Rows
dt.SetNumRows(row + 1)
trl = ss.TstTrlLog
tix = etable.NewIdxView(trl)
epc = ss.TrainEnv.Epoch.Prv # ?
# note: this shows how to use agg methods to compute summary data from another
# data table, instead of incrementing on the Sim
dt.SetCellFloat("Run", row, float(ss.TrainEnv.Run.Cur))
dt.SetCellFloat("Epoch", row, float(epc))
dt.SetCellFloat("SSE", row, agg.Sum(tix, "SSE")[0])
dt.SetCellFloat("AvgSSE", row, agg.Mean(tix, "AvgSSE")[0])
dt.SetCellFloat("PctErr", row, agg.Mean(tix, "Err")[0])
dt.SetCellFloat("PctCor", row, 1-agg.Mean(tix, "Err")[0])
dt.SetCellFloat("CosDiff", row, agg.Mean(tix, "CosDiff")[0])
trlix = etable.NewIdxView(trl)
trlix.Filter(funcet, row:
return et.CellFloat("SSE", row) > 0)# include error trials
ss.TstErrLog = trlix.NewTable()
allsp = split.All(trlix)
split.Agg(allsp, "SSE", agg.AggSum)