forked from MrBly/WalnutiQ
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SpatialPooler.java
493 lines (429 loc) · 21.4 KB
/
SpatialPooler.java
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
package model.MARK_II;
import java.awt.*;
import java.util.*;
import java.util.List;
/**
* Provides implementation for running the spatial learning algorithm on a
* Region. This class provides methods that simulate brain activity within
* Regions of the Neocortex.
*
* @author Quinn Liu ([email protected])
* @version July 29, 2013
*/
public class SpatialPooler extends Pooler {
private Set<Column> activeColumns;
private Set<ColumnPosition> activeColumnPositions;
public static float MINIMUM_COLUMN_FIRING_RATE = 0.01f;
public SpatialPooler(Region region) {
if (region == null) {
throw new IllegalArgumentException(
"region in SpatialPooler class constructor cannot be null");
}
super.region = region;
this.activeColumns = new HashSet<Column>();
this.activeColumnPositions = new HashSet<ColumnPosition>();
}
/**
* This method recomputes all Column states within this functional Region.
* Through local inhibition, only a sparse set of Columns become active to
* represent the current 2D array of sensory data or a lower Region's
* output.
*
* @return A sparse set of active Columns within this Region.
*/
public Set<Column> performPooling() {
/// for c in columns
Column[][] columns = this.region.getColumns();
for (int row = 0; row < columns.length; row++) {
for (int column = 0; column < columns[0].length; column++) {
this.computeColumnOverlapScore(columns[row][column]);
}
}
// a sparse set of Columns become active after local inhibition
this.computeActiveColumnsOfRegion();
// simulate learning by boosting specific Synapses
this.regionLearnOneTimeStep();
return this.activeColumns;
}
/**
* If only the column positions computed by spatial pooling are needed use
* this method to return a set of just the column positions that were active
* in the most recent iteration of spatial pooling. For example instead of
* using:
*
* Set<Column> columnActivity =
* spatialPooler.performPooling();
*
* Now use:
*
* spatialPooler.performPooling();
* Set<ColumnPosition> columnActivity = this.spatialPooler.getActiveColumnPositions();
*/
public Set<ColumnPosition> getActiveColumnPositions() {
return this.activeColumnPositions;
}
public Set<Column> getActiveColumns() {
return this.activeColumns;
}
/**
* The overlapScore for each Column is the number of Synapses connected to
* Cells with active inputs multiplied by that Columns's boostValue. If a
* Column's overlapScore is below minOverlap, that Column's overlapScore is
* set to 0.
*/
void computeColumnOverlapScore(Column column) {
if (column == null) {
throw new IllegalArgumentException(
"the Column in SpatialPooler method computeColumnOverlapScore cannot be null");
}
/// overlap(c) = 0
int newOverlapScore = column.getProximalSegment()
/// for s in connectedSynapses(c)
/// overlap(c) = overlap(c) + input(t, s.sourceInput)
.getNumberOfActiveSynapses();
// compute minimumOverlapScore assuming all proximalSegments are
// connected to the same number of synapses
Column[][] columns = this.region.getColumns();
int regionMinimumOverlapScore = this.region.getMinimumOverlapScore();
/// if overlap(c) < minOverlap then
if (newOverlapScore < regionMinimumOverlapScore) {
/// overlap(c) = 0
newOverlapScore = 0;
} else {
/// overlap(c) = overlap(c) * boost(c)
newOverlapScore = (int) (newOverlapScore * column.getBoostValue());
}
column.setOverlapScore(newOverlapScore);
}
/**
* This method is called by performPooling and computes the
* activeColumns(t) = the list of Columns that win due to the bottom-up input
* at time t.
*/
void computeActiveColumnsOfRegion() {
// remove old active columns from last time spatial pooling was called
this.activeColumns.clear();
this.activeColumnPositions.clear();
Column[][] columns = this.region.getColumns();
/// for c in columns
for (int row = 0; row < columns.length; row++) {
for (int column = 0; column < columns[0].length; column++) {
columns[row][column].setActiveState(false);
this.updateNeighborColumns(row, column);
// necessary for calculating kthScoreOfColumns
List<ColumnPosition> neighborColumnPositions = new ArrayList<ColumnPosition>();
neighborColumnPositions = columns[row][column].getNeighborColumns();
List<Column> neighborColumns = new ArrayList<Column>();
for (ColumnPosition columnPosition : neighborColumnPositions) {
neighborColumns
.add(columns[columnPosition.getRow()][columnPosition
.getColumn()]);
}
/// minLocalActivity = kthScore(neighbors(c), desiredLocalActivity)
int minimumLocalOverlapScore = this.kthScoreOfColumns(
neighborColumns, this.region.getDesiredLocalActivity());
// more than (this.region.desiredLocalActivity) number of
// columns can become active since it is applied to each
// Column object's neighborColumns
/// if overlap(c) > 0 and overlap(c) >= minLocalActivity then
if (columns[row][column].getOverlapScore() > 0
&& columns[row][column].getOverlapScore() >= minimumLocalOverlapScore) {
/// activeColumns(t).append(c)
columns[row][column].setActiveState(true);
this.addActiveColumn(columns[row][column]);
this.activeColumnPositions.add(new ColumnPosition(row, column));
}
}
}
}
/**
* This method models spike-timing dependent plasticity. This is also known
* as Hebb's Rule. The inhibitionRadius for the Region is also computed and
* updated here.
*/
void regionLearnOneTimeStep() {
this.modelLongTermPotentiationAndDepression();
this.boostSynapsesBasedOnActiveAndOverlapDutyCycle();
/// inhibitionRadius = averageReceptiveFieldSize()
this.region
.setInhibitionRadius((int) averageReceptiveFieldSizeOfRegion());
}
void modelLongTermPotentiationAndDepression() {
Column[][] columns = this.region.getColumns();
if (super.getLearningState()) {
/// for c in activeColumns(t)
for (int x = 0; x < columns.length; x++) {
for (int y = 0; y < columns[0].length; y++) {
if (columns[x][y].getActiveState()) {
// increase and decrease of proximal segment synapses
// based on each Synapses's activeState
Set<Synapse<Cell>> synapses = columns[x][y]
.getProximalSegment().getSynapses();
/// for s in potentialSynapses(c)
for (Synapse<Cell> synapse : synapses) {
/// if active(s) then
if (synapse.getConnectedCell() != null
&& synapse.getConnectedCell()
.getActiveState()) {
// model long term potentiation
/// s.permanence += permanenceInc
/// s.permanence = min(1.0, s.permanence)
synapse.increasePermanence();
} else {
// model long term depression
/// s.permanence -= permanenceDec
/// s.permanence = max(0.0, s.permanence)
synapse.decreasePermanence();
}
}
}
}
}
}
}
void boostSynapsesBasedOnActiveAndOverlapDutyCycle() {
Column[][] columns = this.region.getColumns();
/// for c in columns
for (int row = 0; row < columns.length; row++) {
for (int column = 0; column < columns[0].length; column++) {
if (columns[row][column].getActiveState()) {
// increase and decrease of proximal Segment Synapses based
// on each Synapses's activeState
// columns[row][column].performBoosting();
// 2 methods to help a Column's proximal Segment
// Synapses learn connections:
//
// 1) If activeDutyCycle(measures winning rate) is too low.
// The overall boost value of the Columns is increased.
//
// 2) If overlapDutyCycle(measures connected Synapses with
// inputs) is too low, the permanence values of the
// Column's Synapses are boosted.
// neighborColumns are already up to date.
List<ColumnPosition> neighborColumnPositions = columns[row][column]
.getNeighborColumns();
List<Column> neighborColumns = new ArrayList<Column>();
for (ColumnPosition columnPosition : neighborColumnPositions) {
// add the Column object to neighborColumns
neighborColumns
.add(columns[columnPosition.getRow()][columnPosition
.getColumn()]);
}
float maximumActiveDutyCycle = this.region
.maximumActiveDutyCycle(neighborColumns);
if (maximumActiveDutyCycle == 0) {
maximumActiveDutyCycle = 0.1f;
}
// neighborColumns are no longer necessary for calculations
// in this time step
columns[row][column].clearNeighborColumns();
// minDutyCycle represents the minimum desired firing rate
// for a Column(number of times it becomes active over some
// number of iterations).
// If a Column's firing rate falls below this value, it will
// be boosted.
/// minDutyCycle(c) = 0.01 * maxDutyCycle(neighbors(c))
float minimumActiveDutyCycle = this.MINIMUM_COLUMN_FIRING_RATE
* maximumActiveDutyCycle;
// 1) boost if activeDutyCycle is too low
/// activeDutyCycle(c) = updateActiveDutyCycle(c)
columns[row][column].updateActiveDutyCycle();
/// boost(c) = boostFunction(activeDutyCycle(c), minDutyCycle(c))
columns[row][column].setBoostValue(columns[row][column]
.boostFunction(minimumActiveDutyCycle));
// 2) boost if overlapDutyCycle is too low
/// overlapDutyCycle(c) = updateOverlapDutyCycle(c)
this.updateOverlapDutyCycle(row, column);
/// if overlapDutyCycle(c) < minDutyCycle(c) then
if (columns[row][column].getOverlapDutyCycle() < minimumActiveDutyCycle
&& this.getLearningState()) {
/// increasePermanences(c, 0.1*connectedPerm)
columns[row][column]
.increaseProximalSegmentSynapsePermanences(1);
}
}
}
}
}
/**
* Adds all Columns within inhitionRadius of the parameter Column to the
* neighborColumns field within the parameter Column.
*
* @param columnRowPosition position of Column within Region along y-axis
* @param columnColumnPosition position of Column within Region along x-axis
*/
void updateNeighborColumns(int columnRowPosition, int columnColumnPosition) {
if (columnRowPosition < 0 || columnRowPosition > this.region.getNumberOfRowsAlongRegionYAxis()
|| columnColumnPosition < 0
|| columnColumnPosition > this.region.getNumberOfColumnsAlongRegionXAxis()) {
throw new IllegalArgumentException(
"the Column being updated by the updateNeighborColumns method"
+ "in SpatialPooler class does not exist within the Region");
}
int localInhibitionRadius = this.region.getInhibitionRadius();
assert (localInhibitionRadius >= 0);
// forced inhibition of adjacent Columns
int xInitial = Math.max(0, columnRowPosition - localInhibitionRadius);
int yInitial = Math.max(0, columnColumnPosition - localInhibitionRadius);
// System.out.println("xInitial, yInitial: " + xInitial + ", " +
// yInitial);
int xFinal = Math.min(this.region.getNumberOfRowsAlongRegionYAxis(), columnRowPosition
+ localInhibitionRadius);
int yFinal = Math.min(this.region.getNumberOfColumnsAlongRegionXAxis(), columnColumnPosition
+ localInhibitionRadius);
// to allow double for loop to reach end portion of this.allColumns
xFinal = Math.min(this.region.getNumberOfRowsAlongRegionYAxis(), xFinal + 1);
yFinal = Math.min(this.region.getNumberOfColumnsAlongRegionXAxis(), yFinal + 1);
// System.out.println("xFinal, yFinal: " + xFinal + ", " + yFinal);
Column[][] columns = this.region.getColumns();
if (columns[columnRowPosition][columnColumnPosition].getNeighborColumns().size() != 0) {
// remove neighbors of Column computed with old inhibitionRadius
columns[columnRowPosition][columnColumnPosition].clearNeighborColumns();
}
for (int columnIndex = xInitial; columnIndex < xFinal; columnIndex++) {
for (int rowIndex = yInitial; rowIndex < yFinal; rowIndex++) {
if (columnIndex == columnRowPosition && rowIndex == columnColumnPosition) {
} else {
Column newColumn = columns[columnIndex][rowIndex];
if (newColumn != null) {
columns[columnRowPosition][columnColumnPosition].addNeighborColumns(new ColumnPosition(columnIndex, rowIndex));
}
}
}
}
}
/**
* @param neighborColumns
* @param desiredLocalActivity
* @return the kth highest overlapScore value of a Column object within the
* neighborColumns list.
*/
int kthScoreOfColumns(List<Column> neighborColumns,
int desiredLocalActivity) {
if (neighborColumns == null) {
throw new IllegalArgumentException(
"neighborColumns in SpatialPooler method kthScoreOfColumns cannot be null");
}
// TreeSet data structures' elements are automatically sorted.
Set<Integer> overlapScores = new TreeSet<Integer>();
for (Column column : neighborColumns) {
overlapScores.add(column.getOverlapScore());
}
// if invalid or no local activity is desired, it is changed so that the
// highest overlapScore is returned.
if (desiredLocalActivity <= 0) {
throw new IllegalStateException(
"desiredLocalActivity cannot be <= 0");
}
// k is the index of the overlapScore to be returned. The overlapScore
// is the score at position k(counting from the top) of all
// overlapScores when arranged from smallest to greatest.
int k = Math.max(0, overlapScores.size() - desiredLocalActivity);
if (overlapScores.size() > k) {
return (Integer) overlapScores.toArray()[k];
} else {
return 0;
}
}
/**
* Returns the radius of the average connected receptive field size of all
* the Columns. The connected receptive field size of a Column includes only
* the Column's connected Synapses.
*
* @return The average connected receptive field size.
*/
double averageReceptiveFieldSizeOfRegion() {
double regionAverageReceptiveField = 0.0;
// for each column
Column[][] columns = this.region.getColumns();
for (int x = 0; x < columns.length; x++) {
for (int y = 0; y < columns[0].length; y++) {
// get the set of connected synapses
Set<Synapse<Cell>> connectedSynapes = columns[x][y]
.getProximalSegment().getConnectedSynapses();
Dimension bottomLayerDimensions = this.region
.getBottomLayerXYAxisLength();
// get the column position relative to the input layer
double rowRatio = bottomLayerDimensions.width
/ this.region.getNumberOfRowsAlongRegionYAxis();
double columnX = rowRatio / 2 + x * rowRatio;
double columnRatio = bottomLayerDimensions.height
/ this.region.getNumberOfColumnsAlongRegionXAxis();
double columnY = columnRatio / 2 + y * columnRatio;
double totalSynapseDistanceFromOriginColumn = 0.0;
// iterates over every connected Synapses and sums the
// distances from it's origin Column to determine the
// average receptive field for this Column
for (Synapse<?> connectedSynapse : connectedSynapes) {
double dx = Math.abs(columnX
- connectedSynapse.getCellColumn());
double dy = Math.abs(columnY
- connectedSynapse.getCellRow());
double connectedSynapseDistance = Math.sqrt(dx * dx + dy
* dy);
totalSynapseDistanceFromOriginColumn += connectedSynapseDistance;
}
double columnAverageReceptiveField = totalSynapseDistanceFromOriginColumn
/ connectedSynapes.size();
regionAverageReceptiveField += columnAverageReceptiveField;
}
}
regionAverageReceptiveField /= this.region.getNumberOfColumns();
return regionAverageReceptiveField;
}
void addActiveColumn(Column activeColumn) {
if (activeColumn == null) {
throw new IllegalArgumentException(
"activeColumn in SpatialPooler class method addActiveColumn cannot be null");
}
this.activeColumns.add(activeColumn);
}
/**
* Compute a moving average of how often this Column has overlap greater
* than minimumDutyOverlap. Exponential Moving Average(EMA): St = a * Yt +
* (1 - a) * St - 1.
*/
void updateOverlapDutyCycle(int columnRowPosition, int columnColumnPosition) {
if (columnRowPosition < 0 || columnRowPosition > this.region.getNumberOfRowsAlongRegionYAxis()
|| columnColumnPosition < 0
|| columnColumnPosition > this.region.getNumberOfColumnsAlongRegionXAxis()) {
throw new IllegalArgumentException(
"the Column being updated by the updateOverlapDutyCycle method"
+ "in SpatialPooler does not exist within the Region");
}
// Note whenever updateOverlapDutyCycle() is called, the
// overlapDutyCycle
// is always decremented less and less but only incremented if the
// Column's
// overlapScore was greater than the Region's minimumOverlapScore.
// Furthermore, the increment applied to overlapDutyCycle is a constant
// representing the maximum decrement of overlapDutyCycle from initial
// value 1. Because of this a Column's overlapDutyCycle has a upper
// bound of 1.
Column[][] columns = this.region.getColumns();
float newOverlapDutyCycle = (1.0f - Column.EXPONENTIAL_MOVING_AVERAGE_AlPHA)
* columns[columnRowPosition][columnColumnPosition].getOverlapDutyCycle();
if (columns[columnRowPosition][columnColumnPosition].getOverlapScore() > this.region
.getMinimumOverlapScore()) {
newOverlapDutyCycle += Column.EXPONENTIAL_MOVING_AVERAGE_AlPHA;
}
columns[columnRowPosition][columnColumnPosition]
.setOverlapDutyCycle(newOverlapDutyCycle);
}
public Region getRegion() {
return this.region;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("\n===============================");
stringBuilder.append("\n---SpatialPooler Information---");
stringBuilder.append("\n biological region name: ");
stringBuilder.append(this.region.getBiologicalName());
stringBuilder.append("\n# of activeColumns produced: ");
stringBuilder.append(this.activeColumnPositions.size());
stringBuilder.append("\n===============================");
String spatialPoolerInformation = stringBuilder.toString();
return spatialPoolerInformation;
}
}