code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
batchSize = inputVectors.shape[0] connectionMatrix = getConnectedSyns(sp) reconstructionVectors = np.dot(activeColumnVectors, connectionMatrix) # numActiveColumns = np.sum(activeColumnVectors, 1)[0] numActiveColumns = int(sp._localAreaDensity * sp._numColumns) + 0.0 reconstructionVectors = r...
def reconstructionError(sp, inputVectors, activeColumnVectors, threshold=0.)
Computes a reconstruction error. The reconstuction $r(x)$ of an input vector $x$ is given by the sum of the active column's connected synapses vector of the SDR representation $sdr(x)$ of $x$ normalized by $1/numActiveColumns$. The error is the normalized sum over the "hamming distance" (i.e. distance induce...
5.299921
4.782322
1.108232
connectionMatrix = getConnectedSyns(sp) batchSize = inputVectors.shape[0] # 1st sum... over each input in batch Err = 0. for i in range(batchSize): activeColumns = np.where(activeColumnsCurrentEpoch[i] > 0.)[0] numActiveColumns = activeColumns.shape[0] # 2nd sum... over each active c...
def witnessError(sp, inputVectors, activeColumnsCurrentEpoch)
Computes a variation of a reconstruction error. It measures the average hamming distance of an active column's connected synapses vector and its witnesses. An input vector is called witness for a column, iff the column is among the active columns for the input computed by the spatial pooler. The error is gi...
4.915786
4.20412
1.169278
i, j = column_1, column_2 batchSize = activeColumnsCurrentEpoch.shape[0] # Activity Counts ci, cj, cij = 0., 0., dict([((0,0),0.), ((1,0),0.), ((0,1),0.), ((1,1),0.)]) for t in range(batchSize): ai = activeColumnsCurrentEpoch[t, i] aj = activeColumnsCurrentEpoch[t, j] cij[(ai, aj)] +=...
def mutualInformation(sp, activeColumnsCurrentEpoch, column_1, column_2)
Computes the mutual information of the binary variables that represent the activation probabilities of two columns. The mutual information I(X,Y) of two random variables is given by \[ I (X,Y) = \sum_{x,y} p(x,y) log( p(x,y) / ( p(x) p(y) ) ). \] (https://en.wikipedia.org/wiki/Mutual_information)
2.795676
2.907194
0.961641
if len(columnsUnderInvestigation) == 0: columns = range(np.prod(sp.getColumnDimensions())) else: columns = columnsUnderInvestigation numCols = len(columns) sumMutualInfo = 0 normalizingConst = numCols*(numCols - 1)/2 for i in range(numCols): for j in range(i+1, numCols): sumMutualInfo +...
def meanMutualInformation(sp, activeColumnsCurrentEpoch, columnsUnderInvestigation = [])
Computes the mean of the mutual information of pairs taken from a list of columns.
2.487772
2.456978
1.012534
cellIndices = [self.trnCellIndex(x) for x in cellsToLearnOn] newSegments = self.trnConnections.createSegments(cellIndices) self.trnConnections.growSynapses(newSegments, l6Pattern, 1.0)
def learnL6Pattern(self, l6Pattern, cellsToLearnOn)
Learn the given l6Pattern on TRN cell dendrites. The TRN cells to learn are given in cellsTeLearnOn. Each of these cells will learn this pattern on a single dendritic segment. :param l6Pattern: An SDR from L6. List of indices corresponding to L6 cells. :param cellsToLearnOn: Each cell inde...
8.439708
7.340849
1.149691
# Figure out which TRN cells recognize the L6 pattern. self.trnOverlaps = self.trnConnections.computeActivity(l6Input, 0.5) self.activeTRNSegments = np.flatnonzero( self.trnOverlaps >= self.trnActivationThreshold) self.activeTRNCellIndices = self.trnConnections.mapSegmentsToCells( self...
def deInactivateCells(self, l6Input)
Activate trnCells according to the l6Input. These in turn will impact bursting mode in relay cells that are connected to these trnCells. Given the feedForwardInput, compute which cells will be silent, tonic, or bursting. :param l6Input: :return: nothing
4.542978
4.186302
1.085201
ff = feedForwardInput.copy() # For each relay cell, see if any of its FF inputs are active. for x in range(self.relayWidth): for y in range(self.relayHeight): inputCells = self._preSynapticFFCells(x, y) for idx in inputCells: if feedForwardInput[idx] != 0: ff...
def computeFeedForwardActivity(self, feedForwardInput)
Activate trnCells according to the l6Input. These in turn will impact bursting mode in relay cells that are connected to these trnCells. Given the feedForwardInput, compute which cells will be silent, tonic, or bursting. :param feedForwardInput: a numpy matrix of shape relayCellShape containing 0...
8.191858
6.769131
1.210179
self.trnOverlaps = [] self.activeTRNSegments = [] self.activeTRNCellIndices = [] self.relayOverlaps = [] self.activeRelaySegments = [] self.burstReadyCellIndices = [] self.burstReadyCells = np.zeros((self.relayWidth, self.relayHeight))
def reset(self)
Set everything back to zero
9.300161
9.113866
1.020441
x = i % self.trnWidth y = i / self.trnWidth return x, y
def trnIndextoCoord(self, i)
Map 1D cell index to a 2D coordinate :param i: integer 1D cell index :return: (x, y), a 2D coordinate
5.452737
7.637932
0.713902
x = i % self.relayWidth y = i / self.relayWidth return x, y
def relayIndextoCoord(self, i)
Map 1D cell index to a 2D coordinate :param i: integer 1D cell index :return: (x, y), a 2D coordinate
5.62695
6.90148
0.815325
for x in range(self.relayWidth): for y in range(self.relayHeight): # Create one dendrite for each trn cell that projects to this relay cell # This dendrite contains one synapse corresponding to this TRN->relay # connection. relayCellIndex = self.relayCellIndex((x,y)) ...
def _initializeTRNToRelayCellConnections(self)
Initialize TRN to relay cell connectivity. For each relay cell, create a dendritic segment for each TRN cell it connects to.
6.694931
5.650876
1.18476
xmin = max(i - 1, 0) xmax = min(i + 2, self.trnWidth) ymin = max(j - 1, 0) ymax = min(j + 2, self.trnHeight) trnCells = [ (x, y) for x in range(xmin, xmax) for y in range(ymin, ymax) ] return trnCells
def _preSynapticTRNCells(self, i, j)
Given a relay cell at the given coordinate, return a list of the (x,y) coordinates of all TRN cells that project to it. This assumes a 3X3 fan-in. :param i, j: relay cell Coordinates :return:
2.315533
2.426072
0.954437
xmin = max(i - 1, 0) xmax = min(i + 2, self.inputWidth) ymin = max(j - 1, 0) ymax = min(j + 2, self.inputHeight) inputCells = [ (x, y) for x in range(xmin, xmax) for y in range(ymin, ymax) ] return inputCells
def _preSynapticFFCells(self, i, j)
Given a relay cell at the given coordinate, return a list of the (x,y) coordinates of all feed forward cells that project to it. This assumes a 3X3 fan-in. :param i, j: relay cell Coordinates :return:
2.355765
2.480098
0.949867
experiments = [{}] for key, values in kwargs.items(): if type(values) is list: newExperiments = [] for experiment in experiments: for val in values: newExperiment = copy(experiment) newExperiment[key] = val newExperiments.append(newExperiment) experimen...
def runMultiprocessNoiseExperiment(resultName, repeat, numWorkers, appendResults, **kwargs)
:param kwargs: Pass lists to distribute as lists, lists that should be passed intact as tuples. :return: results, in the format [(arguments, results)]. Also saved to json at resultName, in the same format.
2.405024
2.465007
0.975666
with open(filename,"rb") as f: goodOverlapPairs = pickle.load(f) with open("word_bitmaps_40_bits_minimum.pkl","rb") as f: bitmaps = pickle.load(f) # Count how often each word has a highly overlapping match with other words wordFrequencies = {} for w1, w2, overlap in goodOverlapPairs: wordFreq...
def countWordOverlapFrequencies(filename="goodOverlapPairs.pkl")
Count how many high overlaps each word has, and print it out
3.774089
3.541471
1.065684
self.activeCells = np.empty(0, dtype="uint32") self.winnerCells = np.empty(0, dtype="uint32") self.predictedCells = np.empty(0, dtype="uint32") self.predictedActiveCells = np.empty(0, dtype="uint32") self.activeBasalSegments = np.empty(0, dtype="uint32") self.activeApicalSegments = np.empty...
def reset(self)
Clear all cell and segment activity.
2.151346
2.011386
1.069584
# Calculate predictions for this timestep (activeApicalSegments, matchingApicalSegments, apicalPotentialOverlaps) = self._calculateSegmentActivity( self.apicalConnections, apicalInput, self.connectedPermanence, self.activationThreshold, self.minThreshold, self.reducedBasalThreshold)...
def depolarizeCells(self, basalInput, apicalInput, learn)
Calculate predictions. @param basalInput (numpy array) List of active input bits for the basal dendrite segments @param apicalInput (numpy array) List of active input bits for the apical dendrite segments @param learn (bool) Whether learning is enabled. Some TM implementations may depolarize ...
2.782885
2.767438
1.005581
# Calculate active cells (correctPredictedCells, burstingColumns) = np2.setCompare(self.predictedCells, activeColumns, self.predictedCells / self.cellsPerColumn, rightMinusLeft=True) newActiveCells = np.concatenate((co...
def activateCells(self, activeColumns, basalReinforceCandidates, apicalReinforceCandidates, basalGrowthCandidates, apicalGrowthCandidates, learn=True)
Activate cells in the specified columns, using the result of the previous 'depolarizeCells' as predictions. Then learn. @param activeColumns (numpy array) List of active columns @param basalReinforceCandidates (numpy array) List of bits that the active cells may reinforce basal synapses to. @...
2.790052
2.77311
1.006109
# Correctly predicted columns learningActiveBasalSegments = self.basalConnections.filterSegmentsByCell( activeBasalSegments, correctPredictedCells) learningActiveApicalSegments = self.apicalConnections.filterSegmentsByCell( activeApicalSegments, correctPredictedCells) # Bursting colum...
def _calculateLearning(self, activeColumns, burstingColumns, correctPredictedCells, activeBasalSegments, activeApicalSegments, matchingBasalSegments, ...
Learning occurs on pairs of segments. Correctly predicted cells always have active basal and apical segments, and we learn on these segments. In bursting columns, we either learn on an existing segment pair, or we grow a new pair of segments. @param activeColumns (numpy array) @param burstingColumn...
2.9169
2.537029
1.149731
# Active apical segments lower the activation threshold for basal segments overlaps = connections.computeActivity(activeInput, connectedPermanence) outrightActiveSegments = np.flatnonzero(overlaps >= activationThreshold) if (reducedThreshold != activationThreshold and len(reducedThresho...
def _calculateSegmentActivity(connections, activeInput, connectedPermanence, activationThreshold, minThreshold, reducedThreshold, reducedThresholdCells = ())
Calculate the active and matching basal segments for this timestep. @param connections (SparseMatrixConnections) @param activeInput (numpy array) @return (tuple) - activeSegments (numpy array) Dendrite segments with enough active connected synapses to cause a dendritic spike - matchin...
5.610567
5.363464
1.046071
numNewSynapses = len(growthCandidates) if sampleSize != -1: numNewSynapses = min(numNewSynapses, sampleSize) if maxSynapsesPerSegment != -1: numNewSynapses = min(numNewSynapses, maxSynapsesPerSegment) newSegments = connections.createSegments(newSegmentCells) connections.growSyna...
def _learnOnNewSegments(connections, rng, newSegmentCells, growthCandidates, initialPermanence, sampleSize, maxSynapsesPerSegment)
Create new segments, and grow synapses on them. @param connections (SparseMatrixConnections) @param rng (Random) @param newSegmentCells (numpy array) @param growthCandidates (numpy array)
2.497609
2.64337
0.944858
basalCandidateSegments = self.basalConnections.filterSegmentsByCell( matchingBasalSegments, matchingCellsInBurstingColumns) apicalCandidateSegments = self.apicalConnections.filterSegmentsByCell( matchingApicalSegments, matchingCellsInBurstingColumns) # Sort everything once rather than ins...
def _chooseBestSegmentPairPerColumn(self, matchingCellsInBurstingColumns, matchingBasalSegments, matchingApicalSegments, basalPotentialOverlaps, ...
Choose the best pair of matching segments - one basal and one apical - for each column. Pairs are ranked by the sum of their potential overlaps. When there's a tie, the first pair wins. @param matchingCellsInBurstingColumns (numpy array) Cells in bursting columns that have at least one matching basal s...
2.60952
2.457081
1.062041
candidateCells = np2.getAllCellsInColumns(columns, self.cellsPerColumn) # Arrange the segment counts into one row per minicolumn. segmentCounts = np.reshape( self.basalConnections.getSegmentCounts(candidateCells) + self.apicalConnections.getSegmentCounts(candidateCells), newshape=(le...
def _getCellsWithFewestSegments(self, columns)
For each column, get the cell that has the fewest total segments (basal or apical). Break ties randomly. @param columns (numpy array) Columns to check @return (numpy array) One cell for each of the provided columns
6.255291
6.053876
1.03327
activeColumns = np.asarray(activeColumns) basalInput = np.asarray(basalInput) apicalInput = np.asarray(apicalInput) if basalGrowthCandidates is None: basalGrowthCandidates = basalInput basalGrowthCandidates = np.asarray(basalGrowthCandidates) if apicalGrowthCandidates is None: ...
def compute(self, activeColumns, basalInput, apicalInput=(), basalGrowthCandidates=None, apicalGrowthCandidates=None, learn=True)
Perform one timestep. Use the basal and apical input to form a set of predictions, then activate the specified columns, then learn. @param activeColumns (numpy array) List of active columns @param basalInput (numpy array) List of active input bits for the basal dendrite segments @param apical...
1.777353
1.793865
0.990795
activeColumns = np.asarray(activeColumns) apicalInput = np.asarray(apicalInput) if apicalGrowthCandidates is None: apicalGrowthCandidates = apicalInput apicalGrowthCandidates = np.asarray(apicalGrowthCandidates) self.prevPredictedCells = self.predictedCells self.activateCells(activ...
def compute(self, activeColumns, apicalInput=(), apicalGrowthCandidates=None, learn=True)
Perform one timestep. Activate the specified columns, using the predictions from the previous timestep, then learn. Then form a new set of predictions using the new active cells and the apicalInput. @param activeColumns (numpy array) List of active columns @param apicalInput (numpy array) List...
2.734035
2.737582
0.998704
encoder = CoordinateEncoder(name="positionEncoder", n=t.l6CellCount, w=w) return encoder
def createLocationEncoder(t, w=15)
A default coordinate encoder for encoding locations into sparse distributed representations.
26.293467
23.521042
1.11787
output = np.zeros(encoder.getWidth(), dtype=defaultDtype) locations = set() for dx in range(-r, r+1, step): for dy in range(-r, r+1, step): if dx*dx + dy*dy <= r*r: e = encodeLocation(encoder, x+dx, y+dy, output) locations = locations.union(set(e)) return locations
def getUnionLocations(encoder, x, y, r, step=1)
Return a union of location encodings that correspond to the union of all locations within the specified circle.
3.271202
3.416384
0.957504
(activeApicalSegments, matchingApicalSegments, apicalPotentialOverlaps) = self._calculateApicalSegmentActivity( self.apicalConnections, apicalInput, self.connectedPermanence, self.activationThreshold, self.minThreshold) if learn or self.useApicalModulationBasalThreshold==False: ...
def depolarizeCells(self, basalInput, apicalInput, learn)
Calculate predictions. @param basalInput (numpy array) List of active input bits for the basal dendrite segments @param apicalInput (numpy array) List of active input bits for the apical dendrite segments @param learn (bool) Whether learning is enabled. Some TM implementations may depolarize ...
3.365126
3.475416
0.968266
# Correctly predicted columns learningActiveBasalSegments = self.basalConnections.filterSegmentsByCell( activeBasalSegments, correctPredictedCells) cellsForMatchingBasal = self.basalConnections.mapSegmentsToCells( matchingBasalSegments) matchingCells = np.unique(cellsForMatchingBasal)...
def _calculateBasalLearning(self, activeColumns, burstingColumns, correctPredictedCells, activeBasalSegments, matchingBasalSegments, basalPo...
Basic Temporal Memory learning. Correctly predicted cells always have active basal segments, and we learn on these segments. In bursting columns, we either learn on an existing basal segment, or we grow a new one. The only influence apical dendrites have on basal learning is: the apical dendrites influ...
4.308355
3.520842
1.223672
# Cells with active apical segments learningActiveApicalSegments = self.apicalConnections.filterSegmentsByCell( activeApicalSegments, learningCells) # Cells with matching apical segments learningCellsWithoutActiveApical = np.setdiff1d( learningCells, self.apicalConnections.mapSe...
def _calculateApicalLearning(self, learningCells, activeColumns, activeApicalSegments, matchingApicalSegments, apicalPotentialOverlaps)
Calculate apical learning for each learning cell. The set of learning cells was determined completely from basal segments. Do all apical learning on the same cells. Learn on any active segments on learning cells. For cells without active segments, learn on the best matching segment. For cells without ...
3.453294
2.658193
1.299113
# Active overlaps = connections.computeActivity(activeInput, connectedPermanence) activeSegments = np.flatnonzero(overlaps >= activationThreshold) # Matching potentialOverlaps = connections.computeActivity(activeInput) matchingSegments = np.flatnonzero(potentialOverlaps >= minThreshold) ...
def _calculateApicalSegmentActivity(connections, activeInput, connectedPermanence, activationThreshold, minThreshold)
Calculate the active and matching apical segments for this timestep. @param connections (SparseMatrixConnections) @param activeInput (numpy array) @return (tuple) - activeSegments (numpy array) Dendrite segments with enough active connected synapses to cause a dendritic spike - matchi...
4.290267
3.012466
1.424171
# Active apical segments lower the activation threshold for basal (lateral) segments overlaps = connections.computeActivity(activeInput, connectedPermanence) outrightActiveSegments = np.flatnonzero(overlaps >= activationThreshold) if reducedBasalThreshold != activationThreshold and len(reducedBasal...
def _calculateBasalSegmentActivity(connections, activeInput, reducedBasalThresholdCells, connectedPermanence, activationThreshold, minThreshold, reducedBasalThreshold)
Calculate the active and matching basal segments for this timestep. The difference with _calculateApicalSegmentActivity is that cells with active apical segments (collected in reducedBasalThresholdCells) have a lower activation threshold for their basal segments (set by reducedBasalThreshold parameter)...
6.014444
5.239409
1.147924
cellsForBasalSegments = self.basalConnections.mapSegmentsToCells( activeBasalSegments) cellsForApicalSegments = self.apicalConnections.mapSegmentsToCells( activeApicalSegments) fullyDepolarizedCells = np.intersect1d(cellsForBasalSegments, cellsFo...
def _calculatePredictedCells(self, activeBasalSegments, activeApicalSegments)
Calculate the predicted cells, given the set of active segments. An active basal segment is enough to predict a cell. An active apical segment is *not* enough to predict a cell. When a cell has both types of segments active, other cells in its minicolumn must also have both types of segments to be con...
3.7241
3.490764
1.066844
candidateSegments = connections.filterSegmentsByCell(allMatchingSegments, cells) # Narrow it down to one pair per cell. onePerCellFilter = np2.argmaxMulti(potentialOverlaps[candidateSegments], connections....
def _chooseBestSegmentPerCell(cls, connections, cells, allMatchingSegments, potentialOverlaps)
For each specified cell, choose its matching segment with largest number of active potential synapses. When there's a tie, the first segment wins. @param connections (SparseMatrixConnections) @param cells (numpy array) @param allMatchingSegments (numpy array) @param potentialOverlaps (numpy array) ...
11.870403
12.402149
0.957125
candidateSegments = connections.filterSegmentsByCell(allMatchingSegments, matchingCells) # Narrow it down to one segment per column. cellScores = potentialOverlaps[candidateSegments] columnsForCandidates = (connections.mapSegmentsToCells(ca...
def _chooseBestSegmentPerColumn(cls, connections, matchingCells, allMatchingSegments, potentialOverlaps, cellsPerColumn)
For all the columns covered by 'matchingCells', choose the column's matching segment with largest number of active potential synapses. When there's a tie, the first segment wins. @param connections (SparseMatrixConnections) @param matchingCells (numpy array) @param allMatchingSegments (numpy array)...
8.281673
8.825756
0.938353
super(ApicalTiebreakSequenceMemory, self).reset() self.prevApicalInput = np.empty(0, dtype="uint32") self.prevApicalGrowthCandidates = np.empty(0, dtype="uint32") self.prevPredictedCells = np.empty(0, dtype="uint32")
def reset(self)
Clear all cell and segment activity.
7.853379
7.488479
1.048728
self._setLearningMode() for objectName, sensationList in objects.iteritems(): # ignore empty sensation lists if len(sensationList) == 0: continue # keep track of numbers of iterations to run iterations = 0 for sensations in sensationList: # learn each patte...
def learnObjects(self, objects, reset=True)
Learns all provided objects, and optionally resets the network. The provided objects must have the canonical learning format, which is the following. objects should be a dict objectName: sensationList, where each sensationList is a list of sensations, and each sensation is a mapping from cortical c...
6.462502
5.759161
1.122126
self._unsetLearningMode() statistics = collections.defaultdict(list) for sensations in sensationList: # feed all columns with sensations for col in xrange(self.numColumns): location, feature = sensations[col] self.sensorInputs[col].addDataToQueue(list(feature), 0, 0) ...
def infer(self, sensationList, reset=True, objectName=None)
Infer on given sensations. The provided sensationList is a list of sensations, and each sensation is a mapping from cortical column to a tuple of two SDR's respectively corresponding to the location in object space and the feature. For example, the input can look as follows, if we are inferring a simp...
5.953445
6.167959
0.965221
self.objectL2Representations[objectName] = self.getL2Representations() try: objectIndex = self.objectNameToIndex[objectName] except KeyError: # Grow the matrices as needed. if self.objectNamesAreIndices: objectIndex = objectName if objectIndex >= self.objectL2Represen...
def _saveL2Representation(self, objectName)
Record the current active L2 cells as the representation for 'objectName'.
3.444312
3.338269
1.031766
for col in xrange(self.numColumns): self.sensorInputs[col].addResetToQueue(sequenceId) self.externalInputs[col].addResetToQueue(sequenceId) self.network.run(1)
def _sendReset(self, sequenceId=0)
Sends a reset signal to the network.
7.456587
6.87253
1.084984
if not os.path.exists(plotDir): os.makedirs(plotDir) plt.figure() stats = self.statistics[experimentID] objectName = stats["object"] for i in xrange(self.numColumns): if not onePlot: plt.figure() # plot request stats for field in fields: fieldKey = fie...
def plotInferenceStats(self, fields, plotDir="plots", experimentID=0, onePlot=True)
Plots and saves the desired inference statistics. Parameters: ---------------------------- @param fields (list(str)) List of fields to include in the plots @param experimentID (int) ID of the experiment (usually 0 if only one was conducted) @param onePlot (bool) ...
3.062594
3.290215
0.930819
convergenceSum = 0.0 numCorrect = 0.0 inferenceLength = 1000000 # For each object for stats in self.statistics[firstStat:lastStat]: # For each L2 column locate convergence time convergencePoint = 0.0 for key in stats.iterkeys(): if prefix in key: inference...
def averageConvergencePoint(self, prefix, minOverlap, maxOverlap, settlingTime=1, firstStat=0, lastStat=None)
For each object, compute the convergence time - the first point when all L2 columns have converged. Return the average convergence time and accuracy across all objects. Using inference statistics for a bunch of runs, locate all traces with the given prefix. For each trace locate the iteration where it...
4.003776
3.404244
1.176113
print "Profiling information for {}".format(type(self).__name__) totalTime = 0.000001 for region in self.network.regions.values(): timer = region.getComputeTimer() totalTime += timer.getElapsed() # Sort the region names regionNames = list(self.network.regions.keys()) regionName...
def printProfile(self, reset=False)
Prints profiling information. Parameters: ---------------------------- @param reset (bool) If set to True, the profiling will be reset.
3.078189
3.115542
0.988011
assert ( (column>=0) and (column<self.numColumns)), ("Column number not " "in valid range") if layer == "L2": return self.L2Columns[column].getAlgorithmInstance() elif layer == "L4": return self.L4Columns[column].getAlgorithmInstance() else: raise Except...
def getAlgorithmInstance(self, layer="L2", column=0)
Returns an instance of the underlying algorithm. For example, layer=L2 and column=1 could return the actual instance of ColumnPooler that is responsible for column 1.
3.86094
3.647498
1.058518
overlaps = np.zeros((self.numColumns, len(self.objectL2Representations)), dtype="uint32") for i, representations in enumerate(self.objectL2RepresentationsMatrices): activeCells = self.L2Columns[i]._pooler.getActiveCells() overlaps[i, :] = repres...
def getCurrentObjectOverlaps(self)
Get every L2's current overlap with each L2 object representation that has been learned. :return: 2D numpy array. Each row represents a cortical column. Each column represents an object. Each value represents the cortical column's current L2 overlap with the specified object.
14.979205
11.728788
1.277132
results = {} l2sdr = self.getL2Representations() sdrSize = self.config["L2Params"]["sdrSize"] if minOverlap is None: minOverlap = sdrSize / 2 for objectName, objectSdr in self.objectL2Representations.iteritems(): count = 0 score = 0.0 for col in xrange(self.numColumns):...
def getCurrentClassification(self, minOverlap=None, includeZeros=True)
Return the current classification for every object. Returns a dict with a score for each object. Score goes from 0 to 1. A 1 means every col (that has received input since the last reset) currently has overlap >= minOverlap with the representation for that object. :param minOverlap: min overlap to con...
4.158738
3.472282
1.197696
L2Representation = self.getL2Representations() objectRepresentation = self.objectL2Representations[objectName] sdrSize = self.config["L2Params"]["sdrSize"] if minOverlap is None: minOverlap = sdrSize / 2 if maxL2Size is None: maxL2Size = 1.5*sdrSize numCorrectClassifications = ...
def isObjectClassified(self, objectName, minOverlap=None, maxL2Size=None)
Return True if objectName is currently unambiguously classified by every L2 column. Classification is correct and unambiguous if the current L2 overlap with the true object is greater than minOverlap and if the size of the L2 representation is no more than maxL2Size :param minOverlap: min overlap to co...
4.005637
3.100659
1.291866
sampleSize = int(1.5 * numInputBits) if numInputBits == 20: activationThreshold = 13 minThreshold = 13 elif numInputBits == 10: activationThreshold = 8 minThreshold = 8 else: activationThreshold = int(numInputBits * .6) minThreshold = activationThreshold re...
def getDefaultL4Params(self, inputSize, numInputBits)
Returns a good default set of parameters to use in the L4 region.
4.631559
4.550639
1.017782
if numInputBits == 20: sampleSizeProximal = 10 minThresholdProximal = 5 elif numInputBits == 10: sampleSizeProximal = 6 minThresholdProximal = 3 else: sampleSizeProximal = int(numInputBits * .6) minThresholdProximal = int(sampleSizeProximal * .6) return { ...
def getDefaultL2Params(self, inputSize, numInputBits)
Returns a good default set of parameters to use in the L2 region.
3.256911
3.19763
1.018539
for i, v in enumerate(stats[::-1]): if not (v >= minOverlap and v <= maxOverlap): return len(stats) - i + 1 # Never differs - converged in one iteration return 1
def _locateConvergencePoint(stats, minOverlap, maxOverlap)
Walk backwards through stats until you locate the first point that diverges from target overlap values. We need this to handle cases where it might get to target values, diverge, and then get back again. We want the last convergence point.
6.508713
6.85808
0.949058
for region in self.L4Regions: region.setParameter("learn", False) for region in self.L2Regions: region.setParameter("learningMode", False)
def _unsetLearningMode(self)
Unsets the learning mode, to start inference.
7.723438
7.812527
0.988597
for region in self.L4Regions: region.setParameter("learn", True) for region in self.L2Regions: region.setParameter("learningMode", True)
def _setLearningMode(self)
Sets the learning mode.
7.669846
7.406756
1.03552
if not os.path.exists("traces"): os.makedirs("traces") if seed1 != -1: np.random.seed(seed1) if seed2 != -1: random.seed(seed2) features = [str(i) for i in xrange(numFeatures)] objects = generateObjects(numObjects, featuresPerObject, objectWidth, numFeatures, feat...
def doExperiment(numObjects, featuresPerObject, objectWidth, numFeatures, featureDistribution, useTrace, noiseFactor, moduleNoiseFactor, numModules, thresholds, ...
Learn a set of objects. Then try to recognize each object. Output an interactive visualization.
4.186432
4.201611
0.996387
experiments = [{}] for key, values in kwargs.items(): if type(values) is list: newExperiments = [] for experiment in experiments: for val in values: newExperiment = copy(experiment) newExperiment[key] = val newExperiments.append(newExperiment) experimen...
def runMultiprocessNoiseExperiment(resultName, repeat, numWorkers, appendResults, **kwargs)
:param kwargs: Pass lists to distribute as lists, lists that should be passed intact as tuples. :return: results, in the format [(arguments, results)]. Also saved to json at resultName, in the same format.
2.600349
2.537585
1.024733
# Capital letters, lowercase letters, numbers candidates = ([chr(i+65) for i in xrange(26)] + [chr(i+97) for i in xrange(26)] + [chr(i+48) for i in xrange(10)]) if numFeatures > len(candidates): candidates = ["F{}".format(i) for i in xrange(numFeatures)] return candidat...
def generateFeatures(numFeatures)
Return string features. If <=62 features are requested, output will be single character alphanumeric strings. Otherwise, output will be ["F1", "F2", ...]
3.268941
3.021903
1.081749
if not os.path.exists("traces"): os.makedirs("traces") features = generateFeatures(numFeatures) objects = generateObjects(numObjects, featuresPerObject, objectWidth, features) locationConfigs = [] scale = 5*cellDimensions[0] # One cell is about a quarter of a feature nu...
def doExperiment(cellDimensions, cellCoordinateOffsets, numObjects, featuresPerObject, objectWidth, numFeatures, useTrace, noiseFactor, moduleNoiseFactor, anchoringMet...
Learn a set of objects. Then try to recognize each object. Output an interactive visualization. @param cellDimensions (pair) The cell dimensions of each module @param cellCoordinateOffsets (sequence) The "cellCoordinateOffsets" parameter for each module
4.123379
4.248628
0.97052
if resultName is None: resultName = str(kwargs) + ".json" experiments = [{}] for key, values in kwargs.items(): if type(values) is list: newExperiments = [] for experiment in experiments: for val in values: newExperiment = copy(experiment) newExperiment[key] = ...
def runMultiprocessNoiseExperiment(resultName=None, numWorkers = 0, **kwargs)
:param kwargs: Pass lists to distribute as lists, lists that should be passed intact as tuples. :return: results, in the format [(arguments, results)]. Also saved to json at resultName, in the same format.
2.842236
2.704402
1.050966
token = self.nextMonitorToken self.nextMonitorToken += 1 self.monitors[token] = monitor return token
def addMonitor(self, monitor)
Subscribe to SingleLayer2DExperiment events. @param monitor (SingleLayer2DExperimentMonitor) An object that implements a set of monitor methods @return (object) An opaque object that can be used to refer to this monitor.
6.864055
5.330622
1.287665
for monitor in self.monitors.values(): monitor.beforeTimestep(locationSDR, transitionSDR, featureSDR, egocentricLocation, learn) params = { "newLocation": locationSDR, "deltaLocation": transitionSDR, "featureLocationInput": self.inputLayer.getActiveCel...
def doTimestep(self, locationSDR, transitionSDR, featureSDR, egocentricLocation, learn)
Run one timestep.
2.873856
2.878002
0.998559
print "Learning transitions" for (i, j), locationSDR in self.locations.iteritems(): print "i, j", (i, j) for (di, dj), transitionSDR in self.transitions.iteritems(): i2 = i + di j2 = j + dj if (0 <= i2 < self.diameter and 0 <= j2 < self.diameter): ...
def learnTransitions(self)
Train the location layer to do path integration. For every location, teach it each previous-location + motor command pair.
4.508661
4.086455
1.103318
for monitor in self.monitors.values(): monitor.afterPlaceObjects(objectPlacements) for objectName, objectDict in self.objects.iteritems(): self.reset() objectPlacement = objectPlacements[objectName] for locationName, featureName in objectDict.iteritems(): egocentricLocati...
def learnObjects(self, objectPlacements)
Learn each provided object in egocentric space. Touch every location on each object. This method doesn't try move the sensor along a path. Instead it just leaps the sensor to each object location, resetting the location layer with each leap. This method simultaneously learns 4 sets of synapses: ...
4.419935
4.251033
1.039732
candidates = list(transition for transition in self.transitions.keys() if (allocentricLocation[0] + transition[0], allocentricLocation[1] + transition[1]) in objectDict) random.shuffle(candidates) selectedVisitCount = None sele...
def _selectTransition(self, allocentricLocation, objectDict, visitCounts)
Choose the transition that lands us in the location we've touched the least often. Break ties randomly, i.e. choose the first candidate in a shuffled list.
2.456486
2.209426
1.111821
for monitor in self.monitors.values(): monitor.afterPlaceObjects(objectPlacements) for objectName, objectDict in self.objects.iteritems(): self.reset() visitCounts = defaultdict(int) learnedObjectPlacement = self.learnedObjectPlacements[objectName] allocentricLocation = r...
def inferObjectsWithRandomMovements(self, objectPlacements, maxTouches=20, settlingTime=2)
Infer each object without any location input.
4.537338
4.536323
1.000224
numColumns = self._numColumns numInputs = self._numInputs # The SP should be setup so that stimulusThreshold is reasonably high, # similar to a TP's activation threshold. The pct of connected cells may # need to be low to avoid false positives given the monosynaptic rule initConnectedPct ...
def initializeConnections(self)
Initialize connection matrix, including: _permanences : permanence of synaptic connections (sparse matrix) _potentialPools: potential pool of connections for each cell (sparse binary matrix) _connectedSynapses: connected synapses (binary sparse matrix) _connectedCounts: ...
5.773509
5.400955
1.068979
self._poolingActivation = numpy.zeros((self._numColumns), dtype="int32") self._poolingColumns = [] self._overlapDutyCycles = numpy.zeros(self._numColumns, dtype=realDType) self._activeDutyCycles = numpy.zeros(self._numColumns, dtype=realDType) self._minOverlapDutyCycles = numpy.zeros(self._numC...
def reset(self)
Reset the state of the temporal pooler
3.505808
3.223213
1.087675
if fractionUnpredicted > self._poolingThreshUnpredicted: # Reset pooling activation if the fraction of unpredicted input # is above the threshold if self._spVerbosity > 3: print " reset pooling state for all cells" self._poolingActivation = numpy.zeros(self._numColumns, dtype="i...
def _updatePoolingState(self, activeColWithPredictedInput, fractionUnpredicted)
This function updates the pooling state of TP cells. A cell will stop pooling if: (1) It hasn't received any predicted input in the last self._poolingLife steps or (2) the overall fraction of unpredicted input to the TP is above _poolingThreshUnpredicted
5.539578
4.477797
1.237121
overlaps = numpy.zeros(self._numColumns).astype(realDType) # If no pooling columns or no predicted active inputs, return all zeros if (sum(self._poolingActivation) == 0 or len(predictedActiveCells.nonzero()[0]) == 0): return overlaps if learn: # During learning, overlap is ca...
def _calculatePoolingActivity(self, predictedActiveCells, learn)
Determines each column's overlap with predicted active cell input. If learning, overlap is calculated between predicted active input cells and potential synapses. Otherwise, connected synapses are used. The overlap of a TP cell that was previously active and has one or more active synapse due to predict...
6.994021
5.563729
1.257074
inputIndices = numpy.where(inputVector > 0)[0] predictedIndices = numpy.where(predictedActiveCells > 0)[0] permChanges = numpy.zeros(self._numInputs) # Decrement inactive TM cell -> active TP cell connections permChanges.fill(-1 * self._synPermInactiveDec) # Increment active TM cell -> ac...
def _adaptSynapses(self, inputVector, activeColumns, predictedActiveCells)
This is the primary learning method. It updates synapses' permanence based on the bottom-up input to the TP and the TP's active cells. For each active cell, its synapses' permanences are updated as follows: 1. if pre-synaptic input is ON due to a correctly predicted cell, increase permanence by _syn...
5.660069
4.788122
1.182106
print "------------PY TemporalPooler Parameters ------------------" print "numInputs = ", self.getNumInputs() print "numColumns = ", self.getNumColumns() print "columnDimensions = ", self._columnDimensions print "numActiveColumnsPerInhArea = ", self.g...
def printParameters(self)
Useful for debugging.
4.445759
4.344791
1.023239
# bursting cells in layer 4 burstingColumns = tm.activeState["t"].sum(axis=1) burstingColumns[ burstingColumns < tm.cellsPerColumn ] = 0 burstingColumns[ burstingColumns == tm.cellsPerColumn ] = 1 # print "Bursting column indices=",burstingColumns.nonzero()[0] # correctly predicted cells ...
def extractInputForTP(self, tm)
Extract inputs for TP from the state of temporal memory three information are extracted 1. correctly predicted cells 2. all active cells 3. bursting cells (unpredicted input)
5.215133
4.202477
1.240966
if not isinstance(inputData, np.ndarray): inputData = np.array(inputData) if reset: self._reset() for _ in xrange(numIterations): self._iteration += 1 batch = self._getDataBatch(inputData) # check input dimension, change if necessary if batch.shape[0] != self.fil...
def train(self, inputData, numIterations, reset=False)
Trains the SparseNet, with the provided data. The reset parameter can be set to False if the network should not be reset before training (for example for continuing a previous started training). :param inputData: (array) Input data, of dimension (inputDim, numPoints) :param numIterations: (int)...
4.251604
4.394493
0.967485
if not isinstance(data, np.ndarray): data = np.array(data) # flatten if necessary if flatten: try: data = np.reshape(data, (self.filterDim, data.shape[-1])) except ValueError: # only one data point data = np.reshape(data, (self.filterDim, 1)) if data.shap...
def encode(self, data, flatten=False)
Encodes the provided input data, returning a sparse vector of activations. It solves a dynamic system to find optimal activations, as proposed by Rozell et al. (2008). :param data: (array) Data to be encoded (single point or multiple) :param flatten (bool) Whether or not the data needs...
3.369639
3.248422
1.037316
plt.figure() plt.plot(self.losses.keys(), self.losses.values()) plt.xlabel("Iteration") plt.ylabel("Loss") plt.title("Learning curve for {}".format(self)) if filename is not None: plt.savefig(filename)
def plotLoss(self, filename=None)
Plots the loss history. :param filename (string) Can be provided to save the figure
2.873563
3.16027
0.909278
if np.floor(np.sqrt(self.filterDim)) ** 2 != self.filterDim: print "Basis visualization is not available if filterDim is not a square." return dim = int(np.sqrt(self.filterDim)) if np.floor(np.sqrt(self.outputDim)) ** 2 != self.outputDim: outDimJ = np.sqrt(np.floor(self.outputDim / ...
def plotBasis(self, filename=None)
Plots the basis functions, reshaped in 2-dimensional arrays. This representation makes the most sense for visual input. :param: filename (string) Can be provided to save the figure
2.276057
2.292194
0.99296
self.basis = np.random.randn(self.filterDim, self.outputDim) self.basis /= np.sqrt(np.sum(self.basis ** 2, axis=0)) self._iteration = 0 self.losses = {}
def _reset(self)
Reinitializes basis functions, iteration number and loss history.
4.925028
3.673857
1.340561
batchResiduals = batch - self.basis.dot(activations) loss = np.mean(np.sqrt(np.sum(batchResiduals ** 2, axis=0))) self.losses[self._iteration] = loss if self.verbosity >= 2: if self._iteration % self.showEvery == 0: print "At iteration {0}, loss is {1:.3f}".format(self._iteration, lo...
def _learn(self, batch, activations)
Learns a single iteration on the provided batch and activations. :param batch: (array) Training batch, of dimension (filterDim, batchSize) :param activations:(array) Computed activations, of dimension (outputDim, batchSize)
3.003715
2.981306
1.007517
if thresholdType == None: thresholdType = self.thresholdType activation = np.copy(input) if thresholdType == 'soft': return np.maximum(np.abs(activation) - threshold, 0.) * np.sign(activation) if thresholdType == 'absoluteHard': activation[np.abs(activation) < threshold] = 0. ...
def _thresholdNonLinearity(self, input, threshold, thresholdType=None)
Non linearity function, to transform the activations during training and encoding. :param input: (array) Activations :param threshold: (array) Thresholds :param thresholdType: (string) 'soft', 'absoluteHard' or 'relativeHard'
2.768695
2.333591
1.186453
sparsenet = object.__new__(cls) sparsenet.filterDim = proto.filterDim sparsenet.outputDim = proto.outputDim sparsenet.batchSize = proto.batchSize lossHistoryProto = proto.losses sparsenet.losses = {} for i in xrange(len(lossHistoryProto)): sparsenet.losses[lossHistoryProto[i].it...
def read(cls, proto)
Reads deserialized data from proto object :param proto: (DynamicStructBuilder) Proto object :return (SparseNet) SparseNet instance
2.544033
2.547278
0.998726
proto.filterDim = self.filterDim proto.outputDim = self.outputDim proto.batchSize = self.batchSize lossHistoryProto = proto.init("losses", len(self.losses)) i = 0 for iteration, loss in self.losses.iteritems(): iterationLossHistoryProto = lossHistoryProto[i] iterationLossHistor...
def write(self, proto)
Writes serialized data to proto object :param proto: (DynamicStructBuilder) Proto object
3.726926
3.869237
0.96322
# Reset Union Temporal Pooler fields self._poolingActivation = numpy.zeros(self.getNumColumns(), dtype=REAL_DTYPE) self._unionSDR = numpy.array([], dtype=UINT_DTYPE) self._poolingTimer = numpy.ones(self.getNumColumns(), dtype=REAL_DTYPE) * 1000 self._poolingActivationInitLevel = numpy.zeros(se...
def reset(self)
Reset the state of the Union Temporal Pooler.
4.118699
3.603888
1.142849
assert numpy.size(activeInput) == self.getNumInputs() assert numpy.size(predictedActiveInput) == self.getNumInputs() self._updateBookeepingVars(learn) # Compute proximal dendrite overlaps with active and active-predicted inputs overlapsActive = self._calculateOverlap(activeInput) overlapsP...
def compute(self, activeInput, predictedActiveInput, learn)
Computes one cycle of the Union Temporal Pooler algorithm. @param activeInput (numpy array) A numpy array of 0's and 1's that comprises the input to the union pooler @param predictedActiveInput (numpy array) A numpy array of 0's and 1's that comprises the correctly predicted input to the union pool...
6.033996
5.863626
1.029055
if self._decayFunctionType == 'NoDecay': self._poolingActivation = self._decayFunction.decay(self._poolingActivation) elif self._decayFunctionType == 'Exponential': self._poolingActivation = self._decayFunction.decay(\ self._poolingActivationInitLevel, self._pool...
def _decayPoolingActivation(self)
Decrements pooling activation of all cells
4.979109
4.767397
1.044408
self._poolingActivation[activeCells] = self._exciteFunction.excite( self._poolingActivation[activeCells], overlaps[activeCells]) # increase pooling timers for all cells self._poolingTimer[self._poolingTimer >= 0] += 1 # reset pooling timer for active cells self._poolingTimer[activeCells...
def _addToPoolingActivation(self, activeCells, overlaps)
Adds overlaps from specified active cells to cells' pooling activation. @param activeCells: Indices of those cells winning the inhibition step @param overlaps: A current set of overlap values for each cell @return current pooling activation
3.926127
4.082403
0.96172
poolingActivation = self._poolingActivation nonZeroCells = numpy.argwhere(poolingActivation > 0)[:,0] # include a tie-breaker before sorting poolingActivationSubset = poolingActivation[nonZeroCells] + \ self._poolingActivation_tieBreaker[nonZeroCells] potentialUni...
def _getMostActiveCells(self)
Gets the most active cells in the Union SDR having at least non-zero activation in sorted order. @return: a list of cell indices
7.073382
6.077945
1.163779
inputIndices = numpy.where(inputVector > 0)[0] permChanges = numpy.zeros(self.getNumInputs(), dtype=REAL_DTYPE) permChanges.fill(-1 * synPermInactiveDec) permChanges[inputIndices] = synPermActiveInc perm = numpy.zeros(self.getNumInputs(), dtype=REAL_DTYPE) potential = numpy.zeros(self.getNu...
def _adaptSynapses(self, inputVector, activeColumns, synPermActiveInc, synPermInactiveDec)
The primary method in charge of learning. Adapts the permanence values of the synapses based on the input vector, and the chosen columns after inhibition round. Permanence values are increased for synapses connected to input bits that are turned on, and decreased for synapses connected to inputs bits th...
3.532686
3.575933
0.987906
registerAllResearchRegions() network = Network() if networkConfig["networkType"] == "L4L2Column": return createL4L2Column(network, networkConfig, "_0") elif networkConfig["networkType"] == "MultipleL4L2Columns": return createMultipleL4L2Columns(network, networkConfig) elif networkConfig["network...
def createNetwork(networkConfig)
Create and initialize the specified network instance. @param networkConfig: (dict) the configuration of this network. @return network: (Network) The actual network
2.939238
3.160138
0.930098
print "The network has",len(network.regions.values()),"regions" for p in range(network.getMaxPhase()): print "=== Phase",p for region in network.regions.values(): if network.getPhases(region.name)[0] == p: print " ",region.name
def printNetwork(network)
Given a network, print out regions sorted by phase
5.428108
4.440417
1.222432
m_max = logX.shape[0] p_max = logX.shape[1] params = np.zeros((m_max, p_max, 3)) for m_ in range(m_max): for p_ in range(p_max): params[m_,p_] = skewnorm.fit(logX[m_,p_]) return params
def fit_params_to_1d_data(logX)
Fit skewed normal distributions to 1-D capactity data, and return the distribution parameters. Args ---- logX: Logarithm of one-dimensional capacity data, indexed by module and phase resolution index
2.570821
2.67702
0.96033
def get_interpolated_params(m_frac, ph, params): slope, offset = np.polyfit(np.arange(1,4), params[:3,ph,0], deg=1) a = slope*m_frac + offset slope, offset = np.polyfit(np.arange(1,4), params[:3,ph,1], deg=1) loc = slope*m_frac + offset slope, offset = np.polyfit(np.arange(1,4...
Get parameters describing a 1-D capactity distribution for fractional number of modules.
null
null
null
callLog = LoggingDecorator.load(logFilename) # Assume first one is call to constructor exp = L246aNetwork(*callLog[0][1]["args"], **callLog[0][1]["kwargs"]) # Call subsequent methods, using stored parameters for call in callLog[1:]: method = getattr(exp, call[0]) method(*call[1]["...
def rerunExperimentFromLogfile(logFilename)
Create an experiment class according to the sequence of operations in logFile and return resulting experiment instance. The log file is created by setting the 'logCalls' constructor parameter to True
8.324614
6.959343
1.196178
self.setLearning(True) for objectName, sensationList in objects.iteritems(): self.sendReset() print "Learning :", objectName prevLoc = [None] * self.numColumns numFeatures = len(sensationList[0]) displacement = [0] * self.dimensions for sensation in xrange(numFeatures...
def learn(self, objects)
Learns all provided objects :param objects: dict mapping object name to array of sensations, where each sensation is composed of location and feature SDR for each column. For example: {'obj1' : [[[1,1,1],[101,205,523, ..., 1021]],...], ...} ...
5.757486
5.404587
1.065296
self.setLearning(False) prevLoc = [None] * self.numColumns numFeatures = len(sensations[0]) for sensation in xrange(numFeatures): for col in xrange(self.numColumns): assert numFeatures == len(sensations[col]) location, feature = sensations[col][sensation] # Compute d...
def infer(self, sensations, stats=None, objname=None)
Attempt to recognize the object given a list of sensations. You may use :meth:`getCurrentClassification` to extract the current object classification from the network :param sensations: Array of sensations, where each sensation is composed of displacement vector and feature SDR for e...
5.033484
4.273145
1.177934
return [set(L2.getSelf()._pooler.getActiveCells()) for L2 in self.L2Regions]
def getL2Representations(self)
Returns the active representation in L2.
35.693157
32.55711
1.096325
# Set up plotting if self.plotting: self.fig = plt.figure() self.ax1 = self.fig.add_subplot(211) self.ax2 = self.fig.add_subplot(212) plt.ion() self.ax1.set_xlabel("Excitatory population activity") self.ax2.set_xlabel("Inhibitory population activity") plt.tight_...
def simulate(self, time, feedforwardInputI, feedforwardInputE, v, recurrent=True, dt=None, envelope=False, inputNoise=None)
:param time: Amount of time to simulate. Divided into chunks of len dt. :param feedforwardInputI: feedforward input to inhibitory cells. Must have shape (numInhibitory,). Should be total input over period time. :param feedforwardInputE: feedforward input to excitatory cells. Must have ...
2.423844
2.405045
1.007817
self.instantaneousI.fill(0) self.instantaneousEL.fill(0) self.instantaneousER.fill(0) self.instantaneousI += feedforwardInputI self.instantaneousEL += feedforwardInputE self.instantaneousER += feedforwardInputE if enforceDale: weightsII = np.minimum(self.weightsII, 0) we...
def update(self, feedforwardInputI, feedforwardInputE, v, recurrent=True, envelope=False, iSpeedTuning=False, enforceDale=True)
Do one update of the CAN network, of length self.dt. :param feedforwardInputI: The feedforward input to inhibitory cells. :param feedforwardInputR: The feedforward input to excitatory cells. :param v: The current velocity. :param recurrent: Whether or not recurrent connections should be used. :param...
1.976665
1.975604
1.000537
self.weightsII -= self.weightsII*self.dt/decayConst self.weightsELI -= self.weightsELI*self.dt/decayConst self.weightsERI -= self.weightsERI*self.dt/decayConst self.weightsIEL -= self.weightsIEL*self.dt/decayConst self.weightsIER -= self.weightsIER*self.dt/decayConst
def decayWeights(self, decayConst=60)
Decay the network's weights. :param decayConst: The time constant (in seconds) to use for decay. Note: If applied, decay must be used extremely carefully, as it has a tendency to cause asymmetries in the network weights.
2.389483
2.54218
0.939935
weights = [self.weightsII, self.weightsIEL, self.weightsIER, self.weightsELI, self.weightsERI] norms = [IIMax, IEMax, IEMax, EIMax, EIMax] for w, n in zip(weights, norms): maximum = np.amax(np.abs(w)) w /= maximum w *= n
def normalize_weights(self, IIMax, IEMax, EIMax)
Rescale our weight matrices to have a certain maximum absolute value. :param IINorm: The target maximum for the II weights :param IENorm: The target maximum for both IE weight matrices :param EINorm: The target maximum for both EI weight matrices
3.762662
3.185461
1.181199
places = np.abs(placeCode - 0.5) envelope = [1 if p < 1 - self.envelopeWidth else np.exp(-1.*self.envelopeFactor * ((p - 1 + self.envelopeWidth)/self.envelopeWidth)**2) for p in places] return np.asarray(envelope)
def computeEnvelope(self, placeCode)
Compute an envelope for use in suppressing border cells. :param placeCode: The place code representing the population the envelope will be used for. :return: A numpy array that can be elementwise-multiplied with activations for the given cell population to apply the envelope.
7.114771
7.28768
0.976274
if clearBuffer: while len(self.activationBuffer) > 1: baseI, baseEL, baseER, t = self.activationBuffer.popleft() for (I, EL, ER, i) in self.activationBuffer: t = 1. * (i - t) * self.dt self.weightsII += self.stdpKernel(self.learningRate *\ ...
def stdpUpdate(self, time, clearBuffer=False)
Adds the current activations to the tracking queue, and then performs an STDP update if possible. :param time: The current time. Must be provided. :param clearBuffer: Set as True to clear the activation buffer. This should be done at the end of training.
1.569361
1.554906
1.009297
currentActivation += self._minValue + (self._maxValue - self._minValue) / ( 1 + numpy.exp(-self._steepness * (inputs - self._xMidpoint))) return currentActivation
def excite(self, currentActivation, inputs)
Increases current activation by amount. @param currentActivation (numpy array) Current activation levels for each cell @param inputs (numpy array) inputs for each cell
7.395063
7.305654
1.012238