-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathtemporalPooler.go
2148 lines (1774 loc) · 67.7 KB
/
temporalPooler.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 htm
import (
"fmt"
"github.com/cznic/mathutil"
"github.com/nupic-community/htm/utils"
"github.com/zacg/floats"
"github.com/zacg/go.matrix"
//"math"
"math/rand"
//"sort"
)
type TpOutputType int
const (
Normal TpOutputType = 0
ActiveState TpOutputType = 1
ActiveState1CellPerCol TpOutputType = 2
)
type ProcessAction int
const (
Update ProcessAction = 0
Keep ProcessAction = 1
Remove ProcessAction = 2
)
type TemporalPoolerParams struct {
NumberOfCols int
CellsPerColumn int
InitialPerm float64
ConnectedPerm float64
MinThreshold int
NewSynapseCount int
PermanenceInc float64
PermanenceDec float64
PermanenceMax float64
GlobalDecay float64
ActivationThreshold int
DoPooling bool
SegUpdateValidDuration int
BurnIn int
CollectStats bool
//Seed int
Verbosity int
//checkSynapseConsistency=False, # for cpp only -- ignored
TrivialPredictionMethods []PredictorMethod
PamLength int
MaxInfBacktrack int
MaxLrnBacktrack int
MaxAge int
MaxSeqLength int
MaxSegmentsPerCell int
MaxSynapsesPerSegment int
outputType TpOutputType
}
type DynamicState struct {
//orginally dynamic vars
LrnActiveState *SparseBinaryMatrix // t
LrnActiveStateLast *SparseBinaryMatrix // t-1
LrnPredictedState *SparseBinaryMatrix
LrnPredictedStateLast *SparseBinaryMatrix
InfActiveState *SparseBinaryMatrix
InfActiveStateLast *SparseBinaryMatrix
InfActiveStateBackup *SparseBinaryMatrix
InfActiveStateCandidate *SparseBinaryMatrix
InfPredictedState *SparseBinaryMatrix
InfPredictedStateLast *SparseBinaryMatrix
InfPredictedStateBackup *SparseBinaryMatrix
InfPredictedStateCandidate *SparseBinaryMatrix
CellConfidence *matrix.DenseMatrix
CellConfidenceLast *matrix.DenseMatrix
CellConfidenceCandidate *matrix.DenseMatrix
ColConfidence []float64
ColConfidenceLast []float64
ColConfidenceCandidate []float64
}
func (ds *DynamicState) Copy() *DynamicState {
result := new(DynamicState)
result.LrnActiveState = ds.LrnActiveState.Copy()
result.LrnActiveStateLast = ds.LrnActiveStateLast.Copy()
result.LrnPredictedState = ds.LrnPredictedState.Copy()
result.LrnPredictedStateLast = ds.LrnPredictedStateLast.Copy()
result.InfActiveState = ds.InfActiveState.Copy()
result.InfActiveStateLast = ds.InfActiveStateLast.Copy()
result.InfActiveStateBackup = ds.InfActiveStateBackup.Copy()
result.InfActiveStateCandidate = ds.InfActiveStateCandidate.Copy()
result.InfPredictedState = ds.InfPredictedState.Copy()
result.InfPredictedStateLast = ds.InfPredictedStateLast.Copy()
result.InfPredictedStateBackup = ds.InfPredictedStateBackup.Copy()
result.InfPredictedStateCandidate = ds.InfPredictedStateCandidate.Copy()
result.CellConfidence = ds.CellConfidence.Copy()
if ds.CellConfidenceCandidate != nil {
result.CellConfidenceCandidate = ds.CellConfidenceCandidate.Copy()
}
if ds.CellConfidenceLast != nil {
result.CellConfidenceLast = ds.CellConfidenceLast.Copy()
}
result.ColConfidence = make([]float64, len(ds.ColConfidence))
copy(result.ColConfidence, ds.ColConfidence)
result.ColConfidenceCandidate = make([]float64, len(ds.ColConfidenceCandidate))
copy(result.ColConfidenceCandidate, ds.ColConfidenceCandidate)
result.ColConfidenceLast = make([]float64, len(ds.ColConfidenceLast))
copy(result.ColConfidenceLast, ds.ColConfidenceLast)
return result
}
type TemporalPooler struct {
params TemporalPoolerParams
numberOfCells int
activeColumns []int
cells [][][]Segment
lrnIterationIdx int
iterationIdx int
segId int
CurrentOutput *SparseBinaryMatrix
pamCounter int
avgInputDensity float64
// Keeps track of the moving average of all learned sequence length.
avgLearnedSeqLength float64
resetCalled bool
// Keeps track of the length of the sequence currently being learned.
learnedSeqLength int
trivialPredictor *TrivialPredictor
collectSequenceStats bool
internalStats *TpStats
//ephemeral state
segmentUpdates map[utils.TupleInt][]UpdateState
/*
NOTE: We don't use the same backtrack buffer for inference and learning
because learning has a different metric for determining if an input from
the past is potentially useful again for backtracking.
Our inference backtrack buffer. This keeps track of up to
maxInfBacktrack of previous input. Each entry is a list of active column
inputs.
*/
prevInfPatterns [][]int
/*
Our learning backtrack buffer. This keeps track of up to maxLrnBacktrack
of previous input. Each entry is a list of active column inputs
*/
prevLrnPatterns [][]int
DynamicState *DynamicState
}
//Initializes tp params with default values
func NewTemporalPoolerParams() *TemporalPoolerParams {
tps := new(TemporalPoolerParams)
tps.NumberOfCols = 500
tps.CellsPerColumn = 10
tps.InitialPerm = 0.11
tps.ConnectedPerm = 0.50
tps.MinThreshold = 8
tps.NewSynapseCount = 15
tps.PermanenceInc = 0.10
tps.PermanenceDec = 0.10
tps.PermanenceMax = 1.0
tps.GlobalDecay = 0.10
tps.ActivationThreshold = 12
tps.DoPooling = false
tps.SegUpdateValidDuration = 5
tps.BurnIn = 2
tps.CollectStats = false
tps.Verbosity = 3
//tps.TrivialPredictionMethods =
tps.PamLength = 1
tps.MaxInfBacktrack = 10
tps.MaxLrnBacktrack = 5
tps.MaxAge = 100000
tps.MaxSeqLength = 32
tps.MaxSegmentsPerCell = -1
tps.MaxSynapsesPerSegment = -1
tps.outputType = Normal
return tps
}
//Initializes a new temporal pooler
func NewTemporalPooler(tParams TemporalPoolerParams) *TemporalPooler {
tp := new(TemporalPooler)
tp.params = tParams
//validate args
if tParams.PamLength <= 0 {
panic("Pam length must be > 0")
}
//Fixed size CLA mode
if tParams.MaxSegmentsPerCell != -1 || tParams.MaxSynapsesPerSegment != -1 {
//validate args
if tParams.MaxSegmentsPerCell <= 0 {
panic("Maxsegs must be greater than 0")
}
if tParams.MaxSynapsesPerSegment <= 0 {
panic("Max syns per segment must be greater than 0")
}
if tParams.GlobalDecay != 0.0 {
panic("Global decay must be 0")
}
if tParams.MaxAge != 0 {
panic("Max age must be 0")
}
if !(tParams.MaxSynapsesPerSegment >= tParams.NewSynapseCount) {
panic("maxSynapsesPerSegment must be >= newSynapseCount")
}
}
tp.numberOfCells = tParams.NumberOfCols * tParams.CellsPerColumn
// No point having larger expiration if we are not doing pooling
if !tParams.DoPooling {
tParams.SegUpdateValidDuration = 1
}
//Cells are indexed by column and index in the column
// Every self.cells[column][index] contains a list of segments
// Each segment is a structure of class Segment
//TODO: initialize cells
tp.cells = make([][][]Segment, tParams.NumberOfCols)
for c := 0; c < tParams.NumberOfCols; c++ {
tp.cells[c] = make([][]Segment, tParams.CellsPerColumn)
// for i := 0; i < tParams.CellsPerColumn; i++ {
// }
}
tp.lrnIterationIdx = 0
tp.iterationIdx = 0
tp.segId = 0
tp.avgInputDensity = -1
// pamCounter gets reset to pamLength whenever we detect that the learning
// state is making good predictions (at least half the columns predicted).
// Whenever we do not make a good prediction, we decrement pamCounter.
// When pamCounter reaches 0, we start the learn state over again at start
// cells.
tp.pamCounter = tParams.PamLength
// Trivial prediction algorithms
if len(tParams.TrivialPredictionMethods) > 0 {
tp.trivialPredictor = MakeTrivialPredictor(tParams.NumberOfCols, tParams.TrivialPredictionMethods)
} else {
tp.trivialPredictor = nil
}
// If True, the TP will compute a signature for each sequence
tp.collectSequenceStats = false
// This gets set when we receive a reset and cleared on the first compute
// following a reset.
tp.resetCalled = false
tp.DynamicState = new(DynamicState)
tp.DynamicState.InfActiveState = NewSparseBinaryMatrix(tParams.NumberOfCols, tParams.CellsPerColumn)
tp.DynamicState.InfPredictedState = NewSparseBinaryMatrix(tParams.NumberOfCols, tParams.CellsPerColumn)
tp.DynamicState.LrnActiveState = NewSparseBinaryMatrix(tParams.NumberOfCols, tParams.CellsPerColumn)
tp.DynamicState.LrnPredictedState = NewSparseBinaryMatrix(tParams.NumberOfCols, tParams.CellsPerColumn)
tp.DynamicState.CellConfidence = matrix.Zeros(tParams.NumberOfCols, tParams.CellsPerColumn)
tp.DynamicState.ColConfidence = make([]float64, tParams.NumberOfCols)
tp.internalStats = new(TpStats)
return tp
}
//Returns new unique segment id
func (tp *TemporalPooler) GetSegId() int {
result := tp.segId
tp.segId++
return result
}
/*
Compute the column confidences given the cell confidences. If
None is passed in for CellConfidences, it uses the stored cell confidences
from the last compute.
param CellConfidences Cell confidences to use, or None to use the
the current cell confidences.
returns Column confidence scores
*/
func (tp *TemporalPooler) columnConfidences() []float64 {
//ignore cellconfidence param for now
return tp.DynamicState.ColConfidence
}
/*
Top-down compute - generate expected input given output of the TP
param topDownIn top down input from the level above us
returns best estimate of the TP input that would have generated bottomUpOut.
*/
func (tp *TemporalPooler) topDownCompute() []float64 {
/*
For now, we will assume there is no one above us and that bottomUpOut is
simply the output that corresponds to our currently stored column
confidences.
Simply return the column confidences
*/
return tp.columnConfidences()
}
/*
This function gives the future predictions for <nSteps> timesteps starting
from the current TP state. The TP is returned to its original state at the
end before returning.
- We save the TP state.
- Loop for nSteps
- Turn-on with lateral support from the current active cells
- Set the predicted cells as the next step's active cells. This step
in learn and infer methods use input here to correct the predictions.
We don't use any input here.
- Revert back the TP state to the time before prediction
param nSteps The number of future time steps to be predicted
returns all the future predictions - floating point matrix and
shape (nSteps, numberOfCols).
The ith row gives the tp prediction for each column at
a future timestep (t+i+1).
*/
func (tp *TemporalPooler) Predict(nSteps int) *matrix.DenseMatrix {
// Save the TP dynamic state, we will use to revert back in the end
pristineTPDynamicState := tp.DynamicState.Copy()
if nSteps <= 0 {
panic("nSteps must be greater than zero")
}
// multiStepColumnPredictions holds all the future prediction.
elements := make([]float64, nSteps*tp.params.NumberOfCols)
multiStepColumnPredictions := matrix.MakeDenseMatrix(elements, nSteps, tp.params.NumberOfCols)
// This is a (nSteps-1)+half loop. Phase 2 in both learn and infer methods
// already predicts for timestep (t+1). We use that prediction for free and
// save the half-a-loop of work.
step := 0
for {
multiStepColumnPredictions.FillRow(step, tp.topDownCompute())
if step == nSteps-1 {
break
}
step += 1
//Copy t-1 into t
tp.DynamicState.InfActiveState = tp.DynamicState.InfActiveStateLast
tp.DynamicState.InfPredictedState = tp.DynamicState.InfPredictedStateLast
tp.DynamicState.CellConfidence = tp.DynamicState.CellConfidenceLast
// Predicted state at "t-1" becomes the active state at "t"
tp.DynamicState.InfActiveState = tp.DynamicState.InfPredictedState
// Predicted state and confidence are set in phase2.
tp.DynamicState.InfPredictedState.Clear()
tp.DynamicState.CellConfidence.Fill(0.0)
tp.inferPhase2()
}
// Revert the dynamic state to the saved state
tp.DynamicState = pristineTPDynamicState
return multiStepColumnPredictions
}
/*
This routine computes the activity level of a segment given activeState.
It can tally up only connected synapses (permanence >= connectedPerm), or
all the synapses of the segment, at either t or t-1.
*/
func (tp *TemporalPooler) getSegmentActivityLevel(seg Segment, activeState *SparseBinaryMatrix,
connectedSynapsesOnly bool) int {
activity := 0
//fmt.Println("syn count", len(seg.syns))
if connectedSynapsesOnly {
for _, val := range seg.syns {
//fmt.Printf("***syn %v %v \n", val.Permanence, tp.params.ConnectedPerm)
if val.Permanence >= tp.params.ConnectedPerm {
if activeState.Get(val.SrcCellCol, val.SrcCellIdx) {
activity++
}
}
}
} else {
for _, val := range seg.syns {
if activeState.Get(val.SrcCellCol, val.SrcCellIdx) {
activity++
}
}
}
return activity
}
/*
A segment is active if it has >= activationThreshold connected
synapses that are active due to activeState.
*/
func (tp *TemporalPooler) isSegmentActive(seg Segment, activeState *SparseBinaryMatrix) bool {
if len(seg.syns) < tp.params.ActivationThreshold {
return false
}
activity := 0
for _, val := range seg.syns {
if val.Permanence >= tp.params.ConnectedPerm {
if activeState.Get(val.SrcCellCol, val.SrcCellIdx) {
activity++
if activity >= tp.params.ActivationThreshold {
return true
}
}
}
}
return false
}
/*
Phase 2 for the inference state. The computes the predicted state, then
checks to insure that the predicted state is not over-saturated, i.e.
look too close like a burst. This indicates that there were so many
separate paths learned from the current input columns to the predicted
input columns that bursting on the current input columns is most likely
generated mix and match errors on cells in the predicted columns. If
we detect this situation, we instead turn on only the start cells in the
current active columns and re-generate the predicted state from those.
returns True if we have a decent guess as to the next input.
Returing False from here indicates to the caller that we have
reached the end of a learned sequence.
This looks at:
- InfActiveState
This modifies:
- InfPredictedState
- ColConfidence
- CellConfidence
*/
func (tp *TemporalPooler) inferPhase2() bool {
// Init to zeros to start
tp.DynamicState.InfPredictedState.Clear()
tp.DynamicState.CellConfidence.Fill(0)
utils.FillSliceFloat64(tp.DynamicState.ColConfidence, 0)
// Phase 2 - Compute new predicted state and update cell and column
// confidences
for c := 0; c < tp.params.NumberOfCols; c++ {
for i := 0; i < tp.params.CellsPerColumn; i++ {
// For each segment in the cell
for _, seg := range tp.cells[c][i] {
// Check if it has the min number of active synapses
numActiveSyns := tp.getSegmentActivityLevel(seg, tp.DynamicState.InfActiveState, false)
//fmt.Println("active syns", numActiveSyns)
if numActiveSyns < tp.params.ActivationThreshold {
continue
}
//Incorporate the confidence into the owner cell and column
if tp.params.Verbosity >= 6 {
fmt.Printf("incorporating DC from cell[%v,%v]: \n", c, i)
}
dc := seg.dutyCycle(false, false)
tp.DynamicState.CellConfidence.Set(c, i, tp.DynamicState.CellConfidence.Get(c, i)+dc)
tp.DynamicState.ColConfidence[c] += dc
// If we reach threshold on the connected synapses, predict it
// If not active, skip over it
if tp.isSegmentActive(seg, tp.DynamicState.InfActiveState) {
tp.DynamicState.InfPredictedState.Set(c, i, true)
}
}
}
}
// Normalize column and cell confidences
sumConfidences := utils.SumSliceFloat64(tp.DynamicState.ColConfidence)
if sumConfidences > 0 {
floats.DivConst(sumConfidences, tp.DynamicState.ColConfidence)
tp.DynamicState.CellConfidence.DivScaler(sumConfidences)
}
// Are we predicting the required minimum number of columns?
numPredictedCols := float64(tp.DynamicState.InfPredictedState.TotalNonZeroCount())
return numPredictedCols >= (0.5 * tp.avgInputDensity)
}
/*
Computes output for both learning and inference. In both cases, the
output is the boolean OR of activeState and predictedState at t.
Stores currentOutput for checkPrediction.
*/
func (tp *TemporalPooler) computeOutput() []bool {
switch tp.params.outputType {
case ActiveState1CellPerCol:
// Fire only the most confident cell in columns that have 2 or more
// active cells
mostActiveCellPerCol := tp.DynamicState.CellConfidence.ArgMaxCols()
tp.CurrentOutput = NewSparseBinaryMatrix(tp.DynamicState.InfActiveState.Height, tp.DynamicState.InfActiveState.Width)
// Turn on the most confident cell in each column. Note here that
// Columns refers to TP columns, even though each TP column is a row
// in the matrix.
for i := 0; i < tp.CurrentOutput.Height; i++ {
//only on active cols
if len(tp.DynamicState.InfActiveState.GetRowIndices(i)) != 0 {
tp.CurrentOutput.Set(i, mostActiveCellPerCol[i], true)
}
}
break
case ActiveState:
tp.CurrentOutput = tp.DynamicState.InfActiveState.Copy()
break
case Normal:
tp.CurrentOutput = tp.DynamicState.InfPredictedState.Or(tp.DynamicState.InfActiveState)
break
default:
panic("Unknown output type")
}
return tp.CurrentOutput.Flatten()
}
/*
Update our moving average of learned sequence length.
*/
func (tp *TemporalPooler) updateAvgLearnedSeqLength(prevSeqLength float64) {
alpha := 0.0
if tp.lrnIterationIdx < 100 {
alpha = 0.5
} else {
alpha = 0.1
}
tp.avgLearnedSeqLength = ((1.0-alpha)*tp.avgLearnedSeqLength + (alpha * prevSeqLength))
}
/*
Update the inference active state from the last set of predictions
and the current bottom-up.
This looks at:
- InfPredictedState['t-1']
This modifies:
- InfActiveState['t']
param activeColumns list of active bottom-ups
param useStartCells If true, ignore previous predictions and simply turn on
the start cells in the active columns
returns True if the current input was sufficiently predicted, OR
if we started over on startCells.
False indicates that the current input was NOT predicted,
and we are now bursting on most columns.
*/
func (tp *TemporalPooler) inferPhase1(activeColumns []int, useStartCells bool) bool {
// Start with empty active state
tp.DynamicState.InfActiveState.Clear()
// Phase 1 - turn on predicted cells in each column receiving bottom-up
// If we are following a reset, activate only the start cell in each
// column that has bottom-up
numPredictedColumns := 0
if useStartCells {
for _, val := range activeColumns {
tp.DynamicState.InfActiveState.Set(val, 0, true)
}
} else {
// else, turn on any predicted cells in each column. If there are none, then
// turn on all cells (burst the column)
for _, val := range activeColumns {
predictingCells := tp.DynamicState.InfPredictedStateLast.GetRowIndices(val)
numPredictingCells := len(predictingCells)
if numPredictingCells > 0 {
//may have to set instead of replace
tp.DynamicState.InfActiveState.ReplaceRowByIndices(val, predictingCells)
numPredictedColumns++
} else {
tp.DynamicState.InfActiveState.FillRow(val, true) // whole column bursts
}
}
}
// Did we predict this input well enough?
return useStartCells || numPredictedColumns >= int(0.50*float64(len(activeColumns)))
}
/*
This "backtracks" our inference state, trying to see if we can lock onto
the current set of inputs by assuming the sequence started up to N steps
ago on start cells.
param activeColumns The list of active column indices
This will adjustInfActiveState['t'] if it does manage to lock on to a
sequence that started earlier. It will also compute InfPredictedState['t']
based on the possibly updatedInfActiveState['t'], so there is no need to
call inferPhase2() after calling inferBacktrack().
This looks at:
- InfActiveState['t']
This updates/modifies:
-InfActiveState['t']
-InfPredictedState['t']
-ColConfidence['t']
-CellConfidence['t']
How it works:
-------------------------------------------------------------------
This method gets called from updateInferenceState when we detect either of
the following two conditions:
- The current bottom-up input had too many un-expected columns
- We fail to generate a sufficient number of predicted columns for the
next time step.
Either of these two conditions indicate that we have fallen out of a
learned sequence.
Rather than simply "giving up" and bursting on the unexpected input
columns, a better approach is to see if perhaps we are in a sequence that
started a few steps ago. The real world analogy is that you are driving
along and suddenly hit a dead-end, you will typically go back a few turns
ago and pick up again from a familiar intersection.
This back-tracking goes hand in hand with our learning methodology, which
always tries to learn again from start cells after it loses context. This
results in a network that has learned multiple, overlapping paths through
the input data, each starting at different points. The lower the global
decay and the more repeatability in the data, the longer each of these
paths will end up being.
The goal of this function is to find out which starting point in the past
leads to the current input with the most context as possible. This gives us
the best chance of predicting accurately going forward. Consider the
following example, where you have learned the following sub-sequences which
have the given frequencies:
? - Q - C - D - E 10X seq 0
? - B - C - D - F 1X seq 1
? - B - C - H - I 2X seq 2
? - B - C - D - F 3X seq 3
? - Z - A - B - C - D - J 2X seq 4
? - Z - A - B - C - H - I 1X seq 5
? - Y - A - B - C - D - F 3X seq 6
----------------------------------------
W - X - Z - A - B - C - D <= input history
^
current time step
Suppose, in the current time step, the input pattern is D and you have not
predicted D, so you need to backtrack. Suppose we can backtrack up to 6
steps in the past, which path should we choose? From the table above, we can
see that the correct answer is to assume we are in seq 1. How do we
implement the backtrack to give us this right answer? The current
implementation takes the following approach:
- Start from the farthest point in the past.
- For each starting point S, calculate the confidence of the current
input, conf(startingPoint=S), assuming we followed that sequence.
Note that we must have learned at least one sequence that starts at
point S.
- If conf(startingPoint=S) is significantly different from
conf(startingPoint=S-1), then choose S-1 as the starting point.
The assumption here is that starting point S-1 is the starting point of
a learned sub-sequence that includes the current input in it's path and
that started the longest ago. It thus has the most context and will be
the best predictor going forward.
From the statistics in the above table, we can compute what the confidences
will be for each possible starting point:
startingPoint confidence of D
-----------------------------------------
B (t-2) 4/6 = 0.667 (seq 1,3)/(seq 1,2,3)
Z (t-4) 2/3 = 0.667 (seq 4)/(seq 4,5)
First of all, we do not compute any confidences at starting points t-1, t-3,
t-5, t-6 because there are no learned sequences that start at those points.
Notice here that Z is the starting point of the longest sub-sequence leading
up to the current input. Event though starting at t-2 and starting at t-4
give the same confidence value, we choose the sequence starting at t-4
because it gives the most context, and it mirrors the way that learning
extends sequences.
*/
func (tp *TemporalPooler) inferBacktrack(activeColumns []int) {
// How much input history have we accumulated?
// The current input is always at the end of self._prevInfPatterns (at
// index -1), but it is also evaluated as a potential starting point by
// turning on it's start cells and seeing if it generates sufficient
// predictions going forward.
numPrevPatterns := len(tp.prevInfPatterns)
if numPrevPatterns <= 0 {
return
}
// This is an easy to use label for the current time step
currentTimeStepsOffset := numPrevPatterns - 1
// Save our current active state in case we fail to find a place to restart
// todo: save InfActiveState['t-1'], InfPredictedState['t-1']?
tp.DynamicState.InfActiveStateBackup = tp.DynamicState.InfActiveState.Copy()
// Save our t-1 predicted state because we will write over it as as evaluate
// each potential starting point.
tp.DynamicState.InfPredictedStateBackup = tp.DynamicState.InfPredictedStateLast.Copy()
// We will record which previous input patterns did not generate predictions
// up to the current time step and remove all the ones at the head of the
// input history queue so that we don't waste time evaluating them again at
// a later time step.
var badPatterns []int
// Let's go back in time and replay the recent inputs from start cells and
// see if we can lock onto this current set of inputs that way.
// Start the farthest back and work our way forward. For each starting point,
// See if firing on start cells at that point would predict the current
// input as well as generate sufficient predictions for the next time step.
// We want to pick the point closest to the current time step that gives us
// the relevant confidence. Think of this example, where we are at D and need
// to
// A - B - C - D
// decide if we should backtrack to C, B, or A. Suppose B-C-D is a high order
// sequence and A is unrelated to it. If we backtrock to B would we get a
// certain confidence of D, but if went went farther back, to A, the
// confidence wouldn't change, since A has no impact on the B-C-D series.
// So, our strategy will be to pick the "B" point, since choosing the A point
// does not impact our confidences going forward at all.
inSequence := false
candConfidence := -1.0
candStartOffset := -1
//for startOffset in range(0, numPrevPatterns):
for startOffset := 0; startOffset < numPrevPatterns; startOffset++ {
// If we have a candidate already in the past, don't bother falling back
// to start cells on the current input.
if startOffset == currentTimeStepsOffset && candConfidence != -1 {
break
}
if tp.params.Verbosity >= 3 {
fmt.Printf("Trying to lock-on using startCell state from %v steps ago: %v \n",
(numPrevPatterns - 1 - startOffset), tp.prevInfPatterns[startOffset])
}
// Play through starting from starting point 'startOffset'
inSequence = false
totalConfidence := 0.0
//for offset in range(startOffset, numPrevPatterns):
for offset := startOffset; offset < numPrevPatterns; offset++ {
// If we are about to set the active columns for the current time step
// based on what we predicted, capture and save the total confidence of
// predicting the current input
if offset == currentTimeStepsOffset {
for _, val := range activeColumns {
totalConfidence += tp.DynamicState.ColConfidence[val]
}
}
// Compute activeState[t] given bottom-up and predictedState t-1
tp.DynamicState.InfPredictedStateLast = tp.DynamicState.InfPredictedState.Copy()
inSequence = tp.inferPhase1(tp.prevInfPatterns[offset], (offset == startOffset))
if !inSequence {
break
}
if tp.params.Verbosity >= 3 {
fmt.Println("Backtrack: computing predictions from", tp.prevInfPatterns[offset])
}
// Compute predictedState at t given activeState at t
inSequence = tp.inferPhase2()
if !inSequence {
break
}
}
// If starting from startOffset got lost along the way, mark it as an
// invalid start point.
if !inSequence {
badPatterns = append(badPatterns, startOffset)
continue
}
// If we got to here, startOffset is a candidate starting point.
// Save this state as a candidate state. It will become the chosen state if
// we detect a change in confidences starting at a later startOffset
candConfidence = totalConfidence
candStartOffset = startOffset
if tp.params.Verbosity >= 3 &&
startOffset != currentTimeStepsOffset {
fmt.Printf("Prediction confidence of current input after starting %v steps ago: %v \n", (numPrevPatterns - 1 - startOffset), totalConfidence)
}
if candStartOffset == currentTimeStepsOffset { // no more to try
break
}
tp.DynamicState.InfActiveStateCandidate = tp.DynamicState.InfActiveState.Copy()
tp.DynamicState.InfPredictedStateCandidate = tp.DynamicState.InfPredictedState.Copy()
tp.DynamicState.CellConfidenceCandidate = tp.DynamicState.CellConfidence.Copy()
tp.DynamicState.ColConfidenceCandidate = make([]float64, len(tp.DynamicState.ColConfidence))
copy(tp.DynamicState.ColConfidenceCandidate, tp.DynamicState.ColConfidence)
break
}
// If we failed to lock on at any starting point, fall back to the original
// active state that we had on entry
if candStartOffset == -1 {
if tp.params.Verbosity >= 3 {
fmt.Println("Failed to lock on. Falling back to bursting all unpredicted.")
}
tp.DynamicState.InfActiveState = tp.DynamicState.InfActiveStateBackup
tp.inferPhase2()
} else {
if tp.params.Verbosity >= 3 {
fmt.Printf("Locked on to current input by using start cells from %v steps ago: %v \n",
(numPrevPatterns - 1 - candStartOffset), tp.prevInfPatterns[candStartOffset])
}
fmt.Printf("candstart=%v currentTimeStepoff=%v \n", candStartOffset, currentTimeStepsOffset)
// Install the candidate state, if it wasn't the last one we evaluated.
if candStartOffset != currentTimeStepsOffset {
tp.DynamicState.InfActiveState = tp.DynamicState.InfActiveStateCandidate.Copy()
tp.DynamicState.InfPredictedState = tp.DynamicState.InfPredictedStateCandidate.Copy()
tp.DynamicState.CellConfidence = tp.DynamicState.CellConfidenceCandidate.Copy()
copy(tp.DynamicState.ColConfidence, tp.DynamicState.ColConfidenceCandidate)
}
}
// Remove any useless patterns at the head of the previous input pattern
// queue.
for i := 0; i < numPrevPatterns; i++ {
if utils.ContainsInt(i, badPatterns) || (candStartOffset != -1 && i <= candStartOffset) {
if tp.params.Verbosity >= 3 {
fmt.Printf("Removing useless pattern: 1 of: %v from history: %v \n", len(tp.prevInfPatterns), tp.prevInfPatterns[0])
}
//pop prev pattern
tp.prevInfPatterns = tp.prevInfPatterns[:len(tp.prevInfPatterns)-1]
} else {
break
}
}
// Restore the original predicted state.
tp.DynamicState.InfPredictedState = tp.DynamicState.InfPredictedStateBackup.Copy()
}
/*
Update the inference state. Called from compute() on every iteration.
param activeColumns The list of active column indices.
*/
func (tp *TemporalPooler) updateInferenceState(activeColumns []int) {
// Copy t to t-1
tp.DynamicState.InfActiveStateLast = tp.DynamicState.InfActiveState.Copy()
tp.DynamicState.InfPredictedStateLast = tp.DynamicState.InfPredictedState.Copy()
tp.DynamicState.CellConfidenceLast = tp.DynamicState.CellConfidence.Copy()
tp.DynamicState.ColConfidenceLast = make([]float64, len(tp.DynamicState.ColConfidence))
copy(tp.DynamicState.ColConfidenceLast, tp.DynamicState.ColConfidence)
// Each phase will zero/initilize the 't' states that it affects
// Update our inference input history
if tp.params.MaxInfBacktrack > 0 {
if len(tp.prevInfPatterns) > tp.params.MaxInfBacktrack {
//pop prev pattern
tp.prevInfPatterns = tp.prevInfPatterns[:len(tp.prevInfPatterns)-1]
}
tp.prevInfPatterns = append(tp.prevInfPatterns, activeColumns)
}
// Compute the active state given the predictions from last time step and
// the current bottom-up
inSequence := tp.inferPhase1(activeColumns, tp.resetCalled)
// If this input was considered unpredicted, let's go back in time and
// replay the recent inputs from start cells and see if we can lock onto
// this current set of inputs that way.
if !inSequence {
if tp.params.Verbosity >= 3 {
fmt.Println("Too much unpredicted input, re-tracing back to try and lock on at an earlier timestep.")
}
// inferBacktrack() will call inferPhase2() for us.
tp.inferBacktrack(activeColumns)
return
}
// Compute the predicted cells and the cell and column confidences
inSequence = tp.inferPhase2()
if !inSequence {
if tp.params.Verbosity >= 3 {
fmt.Println("Not enough predictions going forward, re-tracing back to try and lock on at an earlier timestep.")
}
// inferBacktrack() will call inferPhase2() for us.
tp.inferBacktrack(activeColumns)
}
}
/*
Remove a segment update (called when seg update expires or is processed)
*/
func (tp *TemporalPooler) removeSegmentUpdate(updateState UpdateState) {
// Key is stored in segUpdate itself...
key := utils.TupleInt{updateState.Update.columnIdx, updateState.Update.cellIdx}
delete(tp.segmentUpdates, key)
}
/*
Removes any update that would be for the given col, cellIdx, segIdx.
NOTE: logically, we need to do this when we delete segments, so that if
an update refers to a segment that was just deleted, we also remove
that update from the update list. However, I haven't seen it trigger
in any of the unit tests yet, so it might mean that it's not needed
and that situation doesn't occur, by construction.
*/
func (tp *TemporalPooler) cleanUpdatesList(col, cellIdx int, seg Segment) {
for idx, val := range tp.segmentUpdates {
if idx.A == col && idx.B == cellIdx {
for _, update := range val {
if update.Update.segment.Equals(&seg) {
tp.removeSegmentUpdate(update)
}
}
}
}
}
/*
This method goes through a list of segments for a given cell and
deletes all synapses whose permanence is less than minPermanence and deletes
any segments that have less than minNumSyns synapses remaining.
param colIdx Column index
param cellIdx Cell index within the column
param segList List of segment references
param minPermanence Any syn whose permamence is 0 or < minPermanence will
be deleted.
param minNumSyns Any segment with less than minNumSyns synapses remaining
in it will be deleted.
returns tuple (numSegsRemoved, numSynsRemoved)
*/