code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
assert len(sequenceSensations) == len(objectSensations) superimposedSensations = [] for i, objectSensation in enumerate(objectSensations): # print "sequence loc:", sequenceSensations[i][0][0] # print "object loc: ",objectSensation[0][0] # print # print "sequence feat:", sequenceSensations[i][0...
def createSuperimposedSensorySDRs(sequenceSensations, objectSensations)
Given two lists of sensations, create a new list where the sensory SDRs are union of the individual sensory SDRs. Keep the location SDRs from the object. A list of sensations has the following format: [ { 0: (set([1, 5, 10]), set([6, 12, 52]), # location, feature for CC0 }, { 0: (set([5,...
2.280909
2.072072
1.100787
# Create the (loc, feat) pairs for this sequence for column 0. objectSensations = { 0: [pair for pair in sequences[sequenceId]] } inferConfig = { "object": sequenceId, "numSteps": len(objectSensations[0]), "pairs": objectSensations, } inferenceSDRSequence = sequences.provideObjectToInfe...
def inferSuperimposedSequenceObjects(exp, sequenceId, objectId, sequences, objects)
Run inference on the given sequence.
5.139193
5.081115
1.01143
trainingSensations = {} objectSDRs = objects.provideObjectsToLearn() sequenceSDRs = sequences.provideObjectsToLearn() # Create the order of sequences we will show. Each sequence will be shown # exactly numRepetitions times. sequenceOrder = range(len(sequences)) * numRepetitions random.shuffle(sequence...
def trainSuperimposedSequenceObjects(exp, numRepetitions, sequences, objects)
Train the network on the given object and sequence simultaneously for N repetitions each. The total number of training inputs is N * seqLength = M (Ideally numPoints = seqLength) Create a list of M random training presentations of the object (To) Create a list of M=N*seqLength training presentations of the se...
4.864503
4.737384
1.026833
@functools.wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) except Exception, ex: ret = '#' * 60 ret += "\nException caught:" ret += "\n" + '-' * 60 ret += "\n" + traceback.format_exc() ret += "\n" + '-' * 60 ret += "\n" + "#" * 60 prin...
def get_traceback(f)
Multiprocessing doesn't forward exception traceback information. This does. From: http://pragmaticpython.com/2017/02/19/
2.417019
2.356581
1.025646
# Create function arguments for every possibility args = [] for bd in basalPredictedSegmentDecrement: for i in inputSize: for thresh in minThresholdProximalL2: for dec in synPermProximalDecL2: for s in sampleSizeProximalL2: for o in reversed(numSequences): ...
def runExperimentPool(numSequences, numFeatures, numLocations, numObjects, numWorkers=7, nTrials=1, seqLength=10, figure="", numRepetitions=1, ...
Run a bunch of experiments using a pool of numWorkers multiple processes. For numSequences, numFeatures, and numLocations pass in a list containing valid values for that parameter. The cross product of everything is run, and each combination is run nTrials times. Returns a list of dict containing detailed resu...
2.324264
2.399279
0.968734
# Results are put into a pkl file which can be used to generate the plots. # dirName is the absolute path where the pkl file will be placed. resultsName = os.path.join(dirName, "sequence_batch_high_dec_normal_features.pkl") numTrials = 10 featureRange = [10, 50, 100, 200] seqRange = [50] locationRange...
def runExperiment4B(dirName)
This runs the second experiment in the section "Simulations with Pure Temporal Sequences". Here we check accuracy of the L2/L4 networks in classifying the sequences. This experiment averages over many parameter combinations and could take several minutes.
6.09214
6.083618
1.001401
# Results are put into a pkl file which can be used to generate the plots. # dirName is the absolute path where the pkl file will be placed. resultsFilename = os.path.join(dirName, "sensorimotor_sequence_example.pkl") results = runExperiment( { "numSequences": 0, "seqLength": 10, "numFe...
def runExperiment5A(dirName)
This runs the first experiment in the section "Simulations with Sensorimotor Sequences", an example sensorimotor sequence.
5.389257
4.801216
1.122477
# Results are put into a pkl file which can be used to generate the plots. # dirName is the absolute path where the pkl file will be placed. resultsName = os.path.join(dirName, "sensorimotor_batch_results_more_objects.pkl") # We run 10 trials for each column number and then analyze results numTrials = 10 ...
def runExperiment5B(dirName)
This runs the second experiment in the section "Simulations with Sensorimotor Sequences". It averages over many parameter combinations. This experiment could take several hours. You can run faster versions by reducing the number of trials.
6.432254
6.217772
1.034495
# Results are put into a pkl file which can be used to generate the plots. # dirName is the absolute path where the pkl file will be placed. resultsFilename = os.path.join(dirName, "combined_results.pkl") results = runExperiment( { "numSequences": 50, "seqLength": 10, "numObjects": 50, ...
def runExperiment6(dirName)
This runs the experiment the section "Simulations with Combined Sequences", an example stream containing a mixture of temporal and sensorimotor sequences.
5.915819
5.874223
1.007081
# Results are put into a pkl file which can be used to generate the plots. # dirName is the absolute path where the pkl file will be placed. resultsFilename = os.path.join(dirName, "superimposed_training.pkl") results = runExperiment( { "numSequences": 50, "numObjects": 50, "seqLength":...
def runExperimentS(dirName)
This runs an experiment where the network is trained on stream containing a mixture of temporal and sensorimotor sequences.
4.95624
4.905188
1.010408
# Results are put into a pkl file which can be used to generate the plots. # dirName is the absolute path where the pkl file will be placed. resultsFilename = os.path.join(dirName, "superimposed_128mcs.pkl") # We run a bunch of trials with these combinations numTrials = 10 featureRange = [1000] object...
def runExperimentSP(dirName)
This runs a pool of experiments where the network is trained on stream containing a mixture of temporal and sensorimotor sequences.
5.62304
5.44078
1.033499
self.activeState['t-1'].fill(0) self.activeState['t'].fill(0) self.predictedState['t-1'].fill(0) self.predictedState['t'].fill(0) self.learnState['t-1'].fill(0) self.learnState['t'].fill(0) self.confidence['t-1'].fill(0) self.confidence['t'].fill(0) # Flush the segment update ...
def reset(self,)
Reset the state of all cells. This is normally used between sequences while training. All internal states are reset to 0.
4.623246
4.38697
1.053859
self._stats = dict() self._internalStats = dict() self._internalStats['nInfersSinceReset'] = 0 self._internalStats['nPredictions'] = 0 #New prediction score self._internalStats['curPredictionScore2'] = 0 self._internalStats['predictionScoreTotal2'] = 0 self._internalStats['c...
def resetStats(self)
Reset the learning and inference stats. This will usually be called by user code at the start of each inference run (for a particular data set).
4.12299
4.002809
1.030024
if not self.collectStats: return None self._stats['nPredictions'] = self._internalStats['nPredictions'] self._stats['curMissing'] = self._internalStats['curMissing'] self._stats['curExtra'] = self._internalStats['curExtra'] self._stats['totalMissing'] = self._internalStats['totalMissing...
def getStats(self)
Return the current learning and inference stats. This returns a dict containing all the learning and inference stats we have collected since the last resetStats(). If collectStats is False, then None is returned. The following keys are returned in the dict when collectStats is True: nPredictions: ...
2.493963
1.906995
1.307797
# Return if not collecting stats if not self.collectStats: return stats['nInfersSinceReset'] += 1 # Compute the prediction score, how well the prediction from the last # time step predicted the current bottom-up input patternsToCheck = [bottomUpNZ] (numExtra2, numMissing2, con...
def _updateStatsInferEnd(self, stats, bottomUpNZ, predictedState, confidence)
Called at the end of learning and inference, this routine will update a number of stats in our _internalStats dictionary, including: 1. Our computed prediction score 2. ... Parameters: ------------------------------------------------------------------ bottomUpNZ: list of the active bottom-u...
5.797707
5.542982
1.045954
(cols, cellIdxs) = state.nonzero() if len(cols) == 0: print "NONE" return prevCol = -1 for (col,cellIdx) in zip(cols, cellIdxs): if col != prevCol: if prevCol != -1: print "] ", print "Col %d: [" % (col), prevCol = col if andValues: ...
def printActiveIndices(self, state, andValues=False)
Print the list of [column, cellIdx] indices for each of the active cells in state.
3.443681
2.977144
1.156706
if self.verbosity >= 3: print "----- computeEnd summary: " print "numBurstingCols: %s, " % (self.activeState['t'].min(axis=1).sum()), print "curPredScore2: %s, " % (self._internalStats['curPredictionScore2']), print "curFalsePosScore: %s, " % (self._internalStats['curFalsePositiveScore'...
def printComputeEnd(self, output, learn=False)
Called at the end of inference to print out various diagnostic information based on the current verbosity level.
3.830663
3.769443
1.016241
return self.cells[c][i][segIdx]
def getSegmentOnCell(self, c, i, segIdx)
Return the segment on cell (c,i) with index sidx. Returns the segment as following list: [ [segmentID, sequenceSegmentFlag, frequency], [col1, idx1, perm1], [col2, idx2, perm2], ... ]
6.937711
7.734262
0.89701
# An updateInfo contains (creationDate, SegmentUpdate) (creationDate, segUpdate) = updateInfo # Key is stored in segUpdate itself... key = (segUpdate.columnIdx, segUpdate.cellIdx) self.segmentUpdates[key].remove(updateInfo)
def removeSegmentUpdate(self, updateInfo)
Remove a segment update (called when seg update expires or is processed) Parameters: -------------------------------------------------------------- updateInfo: (creationDate, SegmentUpdate)
13.119568
7.947829
1.650711
# todo: This operation can be sped up by: # 1.) Pre-allocating space for the currentOutput # 2.) Making predictedState and activeState of type 'float32' up front # 3.) Using logical_or(self.predictedState['t'], self.activeState['t'], # self.currentOutput) # self.current...
def computeOutput(self)
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.
8.798615
6.242446
1.409482
# Save the TP dynamic state, we will use to revert back in the end pristineTPDynamicState = self._getTPDynamicState() assert (nSteps>0) # multiStepColumnPredictions holds all the future prediction. multiStepColumnPredictions = numpy.zeros((nSteps, self.numberOfCols), ...
def predict(self, nSteps)
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. 1) We save the TP state. 2) Loop for nSteps a) Turn-on with lateral support from the current active cells b) Se...
7.076779
6.007869
1.177918
# Phase 2: compute predicted state for each cell # - if a segment has enough horizontal connections firing because of # bottomUpInput, it's set to be predicting, and we queue up the segment # for reinforcement, # - if pooling is on, try to find the best weakly activated segment to # ...
def computePhase2(self, doLearn=False)
This is the phase 2 of learning, inference and multistep prediction. During this phase, all the cell with lateral support have their predictedState turned on and the firing segments are queued up for updates. Parameters: -------------------------------------------- doLearn: Boolean flag to que...
11.27827
10.433368
1.080981
if enableLearn: self.learn(bottomUpInput) else: self.infer(bottomUpInput)
def compute(self, bottomUpInput, enableLearn, computeInfOutput=None)
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.
3.428381
3.241316
1.057713
self.iterationIdx = self.iterationIdx + 1 if self.verbosity >= 3: print "\n==== Iteration: %d =====" % (self.iterationIdx) print "Active cols:", bottomUpInput.nonzero()[0] # Copy t into t-1 # Don't need to copy learnState, which is not used in inference self.activeState['t-1'][:,...
def infer(self, bottomUpInput)
Parameters: -------------------------------------------- input: Current bottom-up input, dense retval: ?
5.786259
5.734599
1.009008
if cellConfidences is None: cellConfidences = self.confidence['t'] colConfidences = cellConfidences.sum(axis=1) # Make the max column confidence 1.0 #colConfidences /= colConfidences.max() return colConfidences
def columnConfidences(self, cellConfidences=None)
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. Parameters: ---------------------------- cellConfidencs : cell confidences to use, or None to use the the cu...
4.456267
4.422469
1.007642
# Fill in defaults if minPermanence is None: minPermanence = self.connectedPerm if minNumSyns is None: minNumSyns = self.activationThreshold # Loop through all cells totalSegsRemoved, totalSynsRemoved = 0, 0 for c,i in product(xrange(self.numberOfCols), xrange(self.cellsPerCol...
def trimSegments(self, minPermanence=None, minNumSyns=None)
This method deletes all synapses whose permanence is less than minPermanence and deletes any segments that have less than minNumSyns synapses remaining. Parameters: -------------------------------------------------------------- minPermanence: Any syn whose permamence is 0 or < minPermanence wi...
3.807093
2.752408
1.383187
for key, updateList in self.segmentUpdates.iteritems(): c,i = key[0], key[1] if c == col and i == cellIdx: for update in updateList: if update[1].segment == seg: self.removeSegmentUpdate(update)
def cleanUpdatesList(self, col, cellIdx, seg)
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 y...
4.192758
3.449882
1.215334
# todo: Computing in C, use function getSegmentActivityLevel return getSegmentActivityLevel(seg.syns, activeState, connectedSynapsesOnly, self.connectedPerm)
def getSegmentActivityLevel(self, seg, activeState, connectedSynapsesOnly =False)
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.
24.210516
16.831076
1.438441
# Computing in C - *much* faster return isSegmentActive(seg.syns, activeState, self.connectedPerm, self.activationThreshold)
def isSegmentActive(self, seg, activeState)
A segment is active if it has >= activationThreshold connected synapses that are active due to activeState. Notes: studied various cutoffs, none of which seem to be worthwhile list comprehension didn't help either
60.226307
26.995239
2.230997
activeSynapses = [] activeState = self.activeState[timeStep] if s is not None: # s can be None, if adding a new segment # Here we add *integers* to activeSynapses activeSynapses = [idx for idx, syn in enumerate(s.syns) \ if activeState[syn[0], syn[1]]] if ne...
def getSegmentActiveSynapses(self, c,i,s, timeStep, newSynapses =False)
Return a segmentUpdate data structure containing a list of proposed changes to segment s. Let activeSynapses be the list of active synapses where the originating cells have their activeState output = 1 at time step t. (This list is empty if s is None since the segment doesn't exist.) newSynapses is an o...
6.440321
5.25963
1.224482
# todo: put back preference for sequence segments. nSegments = len(self.cells[c][i]) bestActivation = self.activationThreshold which = -1 for j,s in enumerate(self.cells[c][i]): activity = self.getSegmentActivityLevel(s, self.activeState[timeStep], connectedSynapsesOnly = True) ...
def getActiveSegment(self, c, i, timeStep)
For a given cell, return the segment with the strongest _connected_ activation, i.e. sum up the activations of the connected synapses of the segments only. That is, a segment is active only if it has enough connected synapses.
6.4569
5.294332
1.219587
if n <= 0: return [] tmpCandidates = [] # tmp because we'll refine just below with activeSynapses if timeStep == 't-1': tmpCandidates = numpy.where(self.learnState['t-1'] == 1) else: tmpCandidates = numpy.where(self.learnState['t'] == 1) # Candidates can be empty at this p...
def chooseCellsToLearnFrom(self, c,i,s, n, timeStep)
Choose n random cells to learn from. Returns tuples of (column index, cell index).
6.007349
5.707552
1.052526
# Collect all cells in column c that have at least minThreshold in the most # activated segment bestActivityInCol = self.minThreshold bestSegIdxInCol = -1 bestCellInCol = -1 for i in xrange(self.cellsPerColumn): maxSegActivity = 0 maxSegIdx = 0 for j,s in enumerate(self...
def getBestMatchingCell(self, c, activeState)
Find weakly activated cell in column. Returns index and segment of most activated segment above minThreshold.
3.82306
3.408751
1.121543
maxActivity, which = self.minThreshold, -1 for j,s in enumerate(self.cells[c][i]): activity = self.getSegmentActivityLevel(s, activeState, connectedSynapsesOnly=False) if activity >= maxActivity: maxActivity, which = activity, j if wh...
def getBestMatchingSegment(self, c, i, activeState)
For the given cell, find the segment with the largest number of active synapses. This routine is aggressive in finding the best match. The permanence value of synapses is allowed to be below connectedPerm. The number of active synapses is allowed to be below activationThreshold, but must be above minThr...
5.236015
6.190425
0.845825
segmentsPerCell = numpy.zeros(self.cellsPerColumn, dtype='uint32') for i in range(self.cellsPerColumn): segmentsPerCell[i] = self.getNumSegmentsInCell(c,i) cellMinUsage = numpy.where(segmentsPerCell==segmentsPerCell.min())[0] # return cellMinUsage[0] # return the first cell with minimum usag...
def getLeastUsedCell(self, c)
For the least used cell in a column
4.33108
4.187675
1.034245
reached0 = False if delta > 0: for synapse in synapses: segment[synapse][2] = newValue = segment[synapse][2] + delta # Cap synapse permanence at permanenceMax if newValue > self.permanenceMax: segment[synapse][2] = self.permanenceMax else: for synapse i...
def updateSynapses(self, segment, synapses, delta)
Update a set of synapses of the given segment, delta can be permanenceInc, or permanenceDec. retval: True if synapse reached 0
4.029058
3.386152
1.189863
# ================================================================= # The segmentUpdates dict has keys which are the column,cellIdx of the # owner cell. The values are lists of segment updates for that cell removeKeys = [] trimSegments = [] for key, updateList in self.segmentUpdates.iteri...
def processSegmentUpdates(self)
Go through the list of accumulated segment updates and process them as follows: if the segment update is too old, remove the update elseif the cell that an update belongs to has it's learnState currently set to True (because it was predicted and just received bottom-up), then positively...
6.108827
5.285947
1.155673
# This will be set to True if detect that any syapses were decremented to # 0 trimSegment = False # segUpdate.segment is None when creating a new segment c, i, segment = segUpdate.columnIdx, segUpdate.cellIdx, segUpdate.segment # update.activeSynapses can be empty. # If not, it can ...
def adaptSegment(self, segUpdate, positiveReinforcement)
This function applies segment update information to a segment in a cell. If positiveReinforcement is true then synapses on the active list get their permanence counts incremented by permanenceInc. All other synapses get their permanence counts decremented by permanenceDec. If positiveReinforcement...
5.768489
5.254435
1.097833
nSegments, nSynapses = 0, 0 nActiveSegs, nActiveSynapses = 0, 0 distSegSizes, distNSegsPerCell = {}, {} distPermValues = {} # Num synapses with given permanence values numAgeBuckets = 20 distAges = [] ageBucketSize = int((self.lrnIterationIdx+20) / 20) for i in range(numAgeBucke...
def getSegmentInfo(self, collectActiveData = False)
Returns information about the distribution of segments, synapses and permanence values in the current TP. If requested, also returns information regarding the number of currently active segments and synapses. The method returns the following tuple: ( nSegments, # total number of segments ...
2.773916
2.235106
1.241067
# Segment ID print "ID:%-5d" % (self.segID), # Sequence segment or pooling segment if self.isSequenceSeg: print "True", else: print "False", # Duty cycle print "%9.7f" % (self.dutyCycle(readOnly=True)), # numPositive/totalActivations print "(%4d/%-4d)" % (self.pos...
def printSegment(self)
Print segment information for verbose messaging and debugging. This uses the following format: ID:54413 True 0.64801 (24/36) 101 [9,1]0.75 [10,1]0.75 [11,1]0.75 where: 54413 - is the unique segment id True - is sequence segment 0.64801 - moving average duty cycle (24/36) - (numPos...
10.05595
6.951961
1.446491
# Make sure numToFree isn't larger than the total number of syns we have assert (numToFree <= len(self.syns)) if (verbosity >= 4): print "\nIn PY freeNSynapses with numToFree =", numToFree, print "inactiveSynapseIndices =", for i in inactiveSynapseIndices: print self.syns[i][...
def freeNSynapses(self, numToFree, inactiveSynapseIndices, verbosity= 0)
Free up some synapses in this segment. We always free up inactive synapses (lowest permanence freed up first) before we start to free up active ones. @param numToFree number of synapses to free up @param inactiveSynapseIndices list of the inactive synapse indices.
2.986245
2.963512
1.007671
reached0 = False if delta > 0: for synapse in synapses: self.syns[synapse][2] = newValue = self.syns[synapse][2] + delta # Cap synapse permanence at permanenceMax if newValue > self.tp.permanenceMax: self.syns[synapse][2] = self.tp.permanenceMax else: fo...
def updateSynapses(self, synapses, delta)
Update a set of synapses in the segment. @param tp The owner TP @param synapses List of synapse indices to update @param delta How much to add to each permanence @returns True if synapse reached 0
3.682103
3.294472
1.117661
s = float(k)/n if s > 0.0 and s < 1.0: entropy = - s * math.log(s,2) - (1 - s) * math.log(1 - s,2) else: entropy = 0 return n*entropy
def maxEntropy(n,k)
The maximum enropy we could get with n units and k winners
3.017577
2.96577
1.017468
entropy = - x*x.log2() - (1-x)*(1-x).log2() entropy[x*(1 - x) == 0] = 0 return entropy, entropy.sum()
def binaryEntropy(x)
Calculate entropy for a list of binary random variables :param x: (torch tensor) the probability of the variable to be 1. :return: entropy: (torch tensor) entropy, sum(entropy)
4.460183
5.63765
0.791142
_,entropy = binaryEntropy(dutyCycle) bins = np.linspace(0.0, 0.3, 200) plt.hist(dutyCycle, bins, alpha=0.5, label='All cols') plt.title("Histogram of duty cycles, entropy=" + str(float(entropy))) plt.xlabel("Duty cycle") plt.ylabel("Number of units") plt.savefig(filePath) plt.close()
def plotDutyCycles(dutyCycle, filePath)
Create plot showing histogram of duty cycles :param dutyCycle: (torch tensor) the duty cycle of each unit :param filePath: (str) Full filename of image file
3.894588
3.792021
1.027048
super(SpatialPoolerWrapper, self).compute(inputVector, learn, activeArray) self._updateAvgActivityPairs(activeArray)
def compute(self, inputVector, learn, activeArray)
This method resembles the primary public method of the SpatialPooler class.
13.605549
8.821787
1.542267
wout = math.floor((input_width + 2 * PADDING - KERNEL_SIZE) / STRIDE + 1) return int(math.floor(wout / 2.0))
def computeMaxPool(input_width)
Compute CNN max pool width. see 'cnn_sdr.py'
3.918555
3.876898
1.010745
if objectNames is None: objectNames = self.objects.keys() objects = {} for name in objectNames: objects[name] = [self._getSDRPairs([pair] * self.numColumns) \ for pair in self.objects[name]] self._checkObjectsToLearn(objects) return objects
def provideObjectsToLearn(self, objectNames=None)
Returns the objects in a canonical format to be sent to an experiment. The returned format is a a dictionary where the keys are object names, and values are lists of sensations, each sensation being a mapping from cortical column index to a pair of SDR's (one location and one feature). returnDict = { ...
6.083921
5.750044
1.058065
numSteps = inferenceConfig.get("numSteps", len(inferenceConfig["pairs"][0])) # some checks if numSteps == 0: raise ValueError("No inference steps were provided") for col in xrange(self.numColumns): if len(inferenceConfig["pairs"][col]) != numSteps: ...
def provideObjectToInfer(self, inferenceConfig)
Returns the sensations in a canonical format to be sent to an experiment. The input inferenceConfig should be a dict with the following form: { "numSteps": 2 # number of sensations for each column "pairs": { 0: [(1, 2), (2, 2)] # sensations for cortical column 0 1: [(2, 2), (1, 1)...
4.299559
3.038681
1.414943
if name is None: name = len(self.objects) self.objects[name] = pairs
def addObject(self, pairs, name=None)
Adds an object to the Machine.
4.414496
3.606331
1.224096
if numObjects > 0: if numLocations is None: numLocations = numPoints if numFeatures is None: numFeatures = numPoints assert(numPoints <= numLocations), ("Number of points in object cannot be " "greater than number of locations") locationArray = numpy.array(...
def createRandomObjects(self, numObjects, numPoints, numLocations=None, numFeatures=None)
Creates a set of random objects and adds them to the machine. If numLocations and numFeatures and not specified, they will be set to the desired number of points.
3.688884
3.668063
1.005677
distinctPairs = set() for pairs in self.objects.itervalues(): distinctPairs = distinctPairs.union(set(pairs)) return distinctPairs
def getDistinctPairs(self)
Return a set consisting of unique feature/location pairs across all objects
4.930858
4.257605
1.15813
uniqueFeatures = set() uniqueLocations = set() for pair in self.objects[name]: uniqueLocations = uniqueLocations.union({pair[0]}) uniqueFeatures = uniqueFeatures.union({pair[1]}) return uniqueLocations, uniqueFeatures
def getUniqueFeaturesLocationsInObject(self, name)
Return two sets. The first set contains the unique locations Ids in the object. The second set contains the unique feature Ids in the object.
3.216343
2.701485
1.190583
sensations = {} numpy.random.seed(self.seed) for col in xrange(self.numColumns): locationID, featureID = pairs[col] # generate random location if requested if includeRandomLocation: location = self._generatePattern(self.numInputBits, s...
def _getSDRPairs(self, pairs, noise=None, locationNoise=None, includeRandomLocation=False, numAmbiguousLocations=0)
This method takes a list of (location, feature) index pairs (one pair per cortical column), and returns a sensation dict in the correct format, adding noise if necessary.
2.789546
2.695896
1.034738
size = self.externalInputSize bits = self.numInputBits random.seed(self.seed) self.locations = [] for _ in xrange(self.numColumns): self.locations.append( [self._generatePattern(bits, size) for _ in xrange(self.numLocations)] )
def _generateLocations(self)
Generates a pool of locations to be used for the experiments. For each index, numColumns SDR's are created, as locations for the same feature should be different for each column.
5.804521
4.80309
1.208497
detectorConstructors = { d : globals()[detectorNameToClass(d)] for d in detectors} return detectorConstructors
def getDetectorClassConstructors(detectors)
Takes in names of detectors. Collects class names that correspond to those detectors and returns them in a dict. The dict maps detector name to class names. Assumes the detectors have been imported.
9.019156
10.453466
0.862791
value = 0 if self.steps < self.min_steps: action = np.random.randint(self.actions) else: self.eps = max(self.eps_end, self.eps * self.eps_decay) if random.random() < self.eps: action = np.random.randint(self.actions) else: self.local.eval() with torch.no_...
def select_action(self, state)
Select the best action for the given state using e-greedy exploration to minimize overfitting :return: tuple(action, value)
2.394459
2.424302
0.98769
if self.steps % self.target_update == 0: self.target.load_state_dict(self.local.state_dict())
def hard_target_update(self)
Update model parameters every 'target_update' time steps See https://arxiv.org/abs/1312.5602 :param target_update: target update interval
3.457651
3.590159
0.963091
for target_param, local_param in zip(self.target.parameters(), self.local.parameters()): target_param.data.copy_(self.tau * local_param.data + (1.0 - self.tau) * target_param.data)
def soft_target_update(self)
Soft update model parameters: .. math:: \\theta_target = \\tau \\times \\theta_local + (1 - \\tau) \\times \\theta_target , with \\tau \\ll 1 See https://arxiv.org/pdf/1509.02971.pdf
1.907203
2.385393
0.799534
self.steps += 1 self.replay.append((state, action, reward, next_state, done)) if self.steps > self.min_steps and len(self.replay) > self.batch_size: batch = random.sample(self.replay, self.batch_size) return self.optimize(batch) return None
def learn(self, state, action, reward, next_state, done)
Update replay memory and learn from a batch of random experiences sampled from the replay buffer :return: optimization loss if enough experiences are available, None otherwise
2.399951
2.282708
1.051361
for monitor in self.monitors.itervalues(): monitor.afterBodyWorldLocationChanged(bodyPlacement) for objectName, objectFeatures in self.objects.iteritems(): self.reset() objectPlacement = self.objectPlacements[objectName] for module in self.bodyToSpecificObjectModules: mod...
def learnObjects(self, bodyPlacement)
Learn each provided object. This method simultaneously learns 4 sets of synapses: - sensor-to-specific-object -> input - input -> sensor-to-specific-object - input -> object - object -> input
4.493471
4.201797
1.069417
for monitor in self.monitors.itervalues(): monitor.afterBodyWorldLocationChanged(bodyPlacement) numTouchesRequired = collections.defaultdict(int) for objectName, objectFeatures in self.objects.iteritems(): self.reset() objectPlacement = self.objectPlacements[objectName] featu...
def inferObjects(self, bodyPlacement, maxTouches=2)
Touch each object with multiple sensors twice. :returns: dict mapping the number of touches required to the number of objects that took that many touches to be uniquely inferred. The 'None' key is reserved for objects not recognized after `maxTouches` touches
4.876812
4.802638
1.015445
objects = defaultdict(list) # Thing features are scalar values ranging from 1-25 inclusive encoder = ScalarEncoder(n=n, w=w, minval=1, maxval=25, forced=True) dataPath = os.path.dirname(os.path.realpath(__file__)) dataPath = os.path.join(dataPath, dataDir) objFiles = glob.glob1(dataPath, "*.log") fo...
def loadThingData(dataDir="data", n=150, w=11)
Load Thing sensation data. There is one file per object, each row contains one feature, location pairs. The format is as follows: [(-33.6705, 75.5003, 2.4207)/10] => [[list of active bits of location], [list of active bits of feature]] The content before "=>" is the true...
5.15976
4.081162
1.264287
path = suite.cfgparser.get(name, "path") path = os.path.join(path, name) accuracy = defaultdict(list) sensations = defaultdict(list) for exp in suite.get_exps(path=path): params = suite.get_params(exp) maxTouches = params["num_sensations"] cells = params["cells_per_axis"] res = suite.get...
def plotAccuracy(suite, name)
Plots classification accuracy
2.865294
2.841842
1.008252
print params["name"], ":", repetition self.debug = params.get("debug", False) self.numLearningPoints = params["num_learning_points"] self.numOfSensations = params["num_sensations"] L2Params = json.loads('{' + params["l2_params"] + '}') L4Params = json.loads('{' + params["l4_params"] + '}')...
def reset(self, params, repetition)
Take the steps necessary to reset the experiment before each repetition: - Make sure random seed is different for each repetition - Create the L2-L4-L6a network - Load objects used by the experiment - Learn all objects used by the experiment
4.175537
3.711524
1.12502
objname, sensations = self.objects.items()[iteration] # Select sensations to infer np.random.shuffle(sensations[0]) sensations = [sensations[0][:self.numOfSensations]] self.network.sendReset() # Collect all statistics for every inference. # See L246aNetwork._updateInferenceStats ...
def iterate(self, params, repetition, iteration)
For each iteration try to infer the object represented by the 'iteration' parameter returning Whether or not the object was unambiguously classified. :param params: Specific parameters for this iteration. See 'experiments.cfg' for list of parameters :param repetition: Current repetition ...
11.688911
11.823036
0.988656
num_correct = 0 num_false_positives = 0 num_false_negatives = 0 classifications = numpy.zeros(data.nRows()) for neuron in pos_neurons: classifications += neuron.calculate_on_entire_dataset(data) for neuron in neg_neurons: classifications -= neuron.calculate_on_entire_dataset(data) if add_noise:...
def get_error(data, labels, pos_neurons, neg_neurons = [], add_noise = True)
Calculates error, including number of false positives and false negatives. Written to allow the use of multiple neurons, in case we attempt to use a population in the future.
2.212542
2.106745
1.050218
# Create function arguments for every possibility args = [] for c in reversed(numColumns): for o in reversed(numObjects): for l in numLocations: for f in numFeatures: for p in longDistanceConnectionsRange: for t in range(nTrials): for locationNoise in loca...
def runExperimentPool(numObjects, numLocations, numFeatures, numColumns, longDistanceConnectionsRange = [0.0], numWorkers=7, nTrials=1, numPoints=10, ...
Allows you to run a number of experiments using multiple processes. For each parameter except numWorkers, pass in a list containing valid values for that parameter. The cross product of everything is run, and each combination is run nTrials times. Returns a list of dict containing detailed results from each ex...
2.574301
2.589196
0.994247
distance = 0 for x in considerDimensions: distance += pow((instance1[x] - instance2[x]), 2) return math.sqrt(distance)
def euclideanDistance(instance1, instance2, considerDimensions)
Calculate Euclidean Distance between two samples Example use: data1 = [2, 2, 2, 'class_a'] data2 = [4, 4, 4, 'class_b'] distance = euclideanDistance(data1, data2, 3) :param instance1: list of attributes :param instance2: list of attributes :param considerDimensions: a list of dimensions to consider :re...
2.395259
2.950529
0.811807
if considerDimensions is None: considerDimensions = len(testInstance) - 1 neighborList = [] for x in range(len(trainingSet)): dist = euclideanDistance(testInstance, trainingSet[x], considerDimensions) neighborList.append((trainingSet[x], dist)) neighborList.sort(key=operator.itemgetter(1)) ne...
def getNeighbors(trainingSet, testInstance, k, considerDimensions=None)
collect the k most similar instances in the trainingSet for a given test instance :param trainingSet: A list of data instances :param testInstance: a single data instance :param k: number of neighbors :param considerDimensions: a list of dimensions to consider :return: neighbors: a list of neighbor instance
1.731005
2.00205
0.864616
neighborResponse = [] for x in range(len(neighbors)): neighborResponse.append(neighbors[x][-1]) neighborResponse = np.array(neighborResponse).astype('float') if weights is None: weightedAvg = np.mean(neighborResponse) else: weightedAvg = np.sum(weights * neighborResponse) return weightedAvg
def getResponse(neighbors, weights=None)
Calculated weighted response based on a list of nearest neighbors :param neighbors: a list of neighbors, each entry is a data instance :param weights: a numpy array of the same length as the neighbors :return: weightedAvg: weighted average response
2.745002
2.77162
0.990396
seq = np.array(sequence).astype('float64') nSampleDim = seq.shape[1] if considerDimensions is None: considerDimensions = range(nSampleDim) for dim in considerDimensions: seq[:, dim] = (seq[:, dim] - np.mean(seq[:, dim])) / np.std(seq[:, dim]) sequence = seq.tolist() return sequence
def normalizeSequence(sequence, considerDimensions=None)
normalize sequence by subtracting the mean and :param sequence: a list of data samples :param considerDimensions: a list of dimensions to consider :return: normalized sequence
2.393774
2.579985
0.927825
r pooler = self W = pooler.connections.visible_to_hidden H = pooler.connections.hidden_to_hidden b = pooler.connections.hidden_bias n, m = pooler.output_size, pooler.input_size w = pooler.code_weight s = pooler.sparsity y = np.zeros(n) a = po...
def numenta_local_wmax_extended(self, x)
r""" New local w-max procedure (experimental). This `encode`-function extends the local w-max overlap procedure. See "Numenta’s local inhibition revisited" (Section 6) in `latex/notes.pdf`. Note that we the "activation probabilies" $a_{ij}$ are already encoded as $h_{ij}$.
5.276207
4.950193
1.065859
E = self.energy y_min = self.find_energy_minimum(E, x) return y_min
def energy_minimum(self, x)
Given an input array `x` it returns its associated encoding `y(x)`, that is, a stable configuration (local energy minimum) of the hidden units while the visible units are clampled to `x`.
7.43553
7.63426
0.973969
overlaps = None for source, connections in self.connectionsBySource.iteritems(): o = connections.computeActivity(activeInputsBySource[source], permanenceThreshold) if overlaps is None: overlaps = o else: overlaps += o return over...
def computeActivity(self, activeInputsBySource, permanenceThreshold=None)
Calculate the number of active synapses per segment. @param activeInputsBySource (dict) The active cells in each source. Example: {"customInputName1": np.array([42, 69])}
3.939713
4.511371
0.873285
segments = None for connections in self.connectionsBySource.itervalues(): created = connections.createSegments(cells) if segments is None: segments = created else: # Sanity-check that the segment numbers are the same. np.testing.assert_equal(segments, created) ...
def createSegments(self, cells)
Create a segment on each of the specified cells. @param cells (numpy array)
6.551017
7.538463
0.869012
for source, connections in self.connectionsBySource.iteritems(): connections.growSynapses(segments, activeInputsBySource[source], initialPermanence)
def growSynapses(self, segments, activeInputsBySource, initialPermanence)
Grow synapses to each of the specified inputs on each specified segment. @param segments (numpy array) The segments that should add synapses @param activeInputsBySource (dict) The active cells in each source. Example: {"customInputName1": np.array([42, 69])} @param initialPermanence (float)
4.467201
7.526645
0.593518
permanences = np.repeat(np.float32(permanence), len(segments)) for source, connections in self.connectionsBySource.iteritems(): if source in presynapticCellsBySource: connections.matrix.setElements(segments, presynapticCellsBySource[source], permanences...
def setPermanences(self, segments, presynapticCellsBySource, permanence)
Set the permanence of a specific set of synapses. Any synapses that don't exist will be initialized. Any existing synapses will be overwritten. Conceptually, this method takes a list of [segment, presynapticCell] pairs and initializes their permanence. For each segment, one synapse is added (although o...
4.557093
5.503639
0.828014
image = Image.open("cajal.jpg").convert("1") image.load() box = (0, 0, t.inputWidth, t.inputHeight) image = image.crop(box) # Here a will be a binary numpy array where True is white. Convert to floating # point numpy array where white is 0.0 a = np.asarray(image) im = np.ones((t.inputWidth, t.inputH...
def loadImage(t, filename="cajal.jpg")
Load the given gray scale image. Threshold it to black and white and crop it to be the dimensions of the FF input for the thalamus. Return a binary numpy matrix where 1 corresponds to black, and 0 corresponds to white.
5.593129
5.052731
1.106952
print("\n-----------") t.reset() t.deInactivateCells(l6Input) ffOutput = t.computeFeedForwardActivity(ffInput) # print("L6 input:", l6Input) # print("Active TRN cells: ", t.activeTRNCellIndices) # print("Burst ready relay cells: ", t.burstReadyCellIndices) return ffOutput
def inferThalamus(t, l6Input, ffInput)
Compute the effect of this feed forward input given the specific L6 input. :param t: instance of Thalamus :param l6Input: :param ffInput: a numpy array of 0's and 1's :return:
8.999148
8.842262
1.017743
# prepare filter bank kernels kernels = [] for theta in range(4): theta = theta / 4. * np.pi for sigma in (1, 3): for frequency in (0.05, 0.25): kernel = np.real(gabor_kernel(frequency, theta=theta, sigma_x=sigma, sigma_y=sigma)) kernels.appen...
def filtered(w=250)
In this example we filter the image into several channels using gabor filters. L6 activity is used to select one of those channels. Only activity selected by those channels burst.
4.350695
4.149413
1.048509
''' Parse a delimited protobuf message. This is done by first getting a protobuf varint from the stream that represents the length of the message, then reading that amount of from the message and then parse it. Since the int can be represented as max 4 bytes, first get 4 bytes and try to decode. The...
def get_delimited_message_bytes(byte_stream, nr=4)
Parse a delimited protobuf message. This is done by first getting a protobuf varint from the stream that represents the length of the message, then reading that amount of from the message and then parse it. Since the int can be represented as max 4 bytes, first get 4 bytes and try to decode. The decoder...
5.390869
2.106837
2.55875
'''Reads n bytes into the internal buffer''' bytes_wanted = n - self.buffer_length + self.pos + 1 if bytes_wanted > 0: self._buffer_bytes(bytes_wanted) end_pos = self.pos + n ret = self.buffer[self.pos + 1:end_pos + 1] self.pos = end_pos return ret
def read(self, n)
Reads n bytes into the internal buffer
3.727432
4.202323
0.886993
'''Rewinds the current buffer to a position. Needed for reading varints, because we might read bytes that belong to the stream after the varint. ''' log.debug("Rewinding pos %d with %d places" % (self.pos, places)) self.pos -= places log.debug("Reset buffer to pos %d" % s...
def rewind(self, places)
Rewinds the current buffer to a position. Needed for reading varints, because we might read bytes that belong to the stream after the varint.
7.582928
2.80215
2.706111
'''Open a socket connection to a given host and port and writes the Hadoop header The Hadoop RPC protocol looks like this when creating a connection: +---------------------------------------------------------------------+ | Header, 4 bytes ("hrpc") ...
def get_connection(self, host, port)
Open a socket connection to a given host and port and writes the Hadoop header The Hadoop RPC protocol looks like this when creating a connection: +---------------------------------------------------------------------+ | Header, 4 bytes ("hrpc") | ...
3.572571
2.120004
1.685172
'''Creates and serializes a delimited RpcRequestHeaderProto message.''' rpcheader = RpcRequestHeaderProto() rpcheader.rpcKind = 2 # rpcheaderproto.RpcKindProto.Value('RPC_PROTOCOL_BUFFER') rpcheader.rpcOp = 0 # rpcheaderproto.RpcPayloadOperationProto.Value('RPC_FINAL_PACKET') r...
def create_rpc_request_header(self)
Creates and serializes a delimited RpcRequestHeaderProto message.
4.644695
3.979939
1.167027
'''Creates and seriazlies a IpcConnectionContextProto (not delimited)''' context = IpcConnectionContextProto() context.userInfo.effectiveUser = self.effective_user context.protocol = "org.apache.hadoop.hdfs.protocol.ClientProtocol" s_context = context.SerializeToString() ...
def create_connection_context(self)
Creates and seriazlies a IpcConnectionContextProto (not delimited)
10.747753
5.464044
1.966996
'''Sends a Hadoop RPC request to the NameNode. The IpcConnectionContextProto, RpcPayloadHeaderProto and HadoopRpcRequestProto should already be serialized in the right way (delimited or not) before they are passed in this method. The Hadoop RPC protocol looks like this for send...
def send_rpc_message(self, method, request)
Sends a Hadoop RPC request to the NameNode. The IpcConnectionContextProto, RpcPayloadHeaderProto and HadoopRpcRequestProto should already be serialized in the right way (delimited or not) before they are passed in this method. The Hadoop RPC protocol looks like this for sending request...
3.915137
1.950468
2.007281
''' In Hadoop protobuf RPC, some parts of the stream are delimited with protobuf varint, while others are delimited with 4 byte integers. This reads 4 bytes from the byte stream and retruns the length of the delimited part that follows, by unpacking the 4 bytes and returning the first el...
def get_length(self, byte_stream)
In Hadoop protobuf RPC, some parts of the stream are delimited with protobuf varint, while others are delimited with 4 byte integers. This reads 4 bytes from the byte stream and retruns the length of the delimited part that follows, by unpacking the 4 bytes and returning the first element from a...
9.315589
1.867312
4.98877
'''Parses a Hadoop RPC response. The RpcResponseHeaderProto contains a status field that marks SUCCESS or ERROR. The Hadoop RPC protocol looks like the diagram below for receiving SUCCESS requests. +-----------------------------------------------------------+ | Length of the RP...
def parse_response(self, byte_stream, response_class)
Parses a Hadoop RPC response. The RpcResponseHeaderProto contains a status field that marks SUCCESS or ERROR. The Hadoop RPC protocol looks like the diagram below for receiving SUCCESS requests. +-----------------------------------------------------------+ | Length of the RPC resonse (...
3.990141
2.066074
1.931268
'''Closes the socket and resets the channel.''' log.debug("Closing socket") if self.sock: try: self.sock.close() except: pass self.sock = None
def close_socket(self)
Closes the socket and resets the channel.
4.540524
3.78463
1.199728
'''Call the RPC method. The naming doesn't confirm PEP8, since it's a method called by protobuf ''' try: self.validate_request(request) if not self.sock: self.get_connection(self.host, self.port) self.send_rpc_message(method, request)...
def CallMethod(self, method, controller, request, response_class, done)
Call the RPC method. The naming doesn't confirm PEP8, since it's a method called by protobuf
6.116678
3.621644
1.688923
''' Create and return a logger with the specified name. ''' # Create logger and add a default NULL handler log = logging.getLogger(name) log.addHandler(_NullHandler()) return log
def getLogger(name)
Create and return a logger with the specified name.
5.031554
5.525122
0.910668
''' Check if any directory arguments contain hdfs://''' dirs_to_check = self.__get_all_directories() hosts, ports = [], [] for path in dirs_to_check: if path.startswith('hdfs://'): parse_result = urlparse(path) hosts.append(parse_result.hostnam...
def _read_config_cl(self)
Check if any directory arguments contain hdfs://
3.942192
3.536181
1.114816
core_path = os.path.join(os.environ['HADOOP_HOME'], 'conf', 'core-site.xml') core_configs = cls.read_core_config(core_path) hdfs_path = os.path.join(os.environ['HADOOP_HOME'], 'conf', 'hdfs-site.xml') hdfs_configs = cls.read_hdfs_config(hdfs_path) if (not core_configs)...
def get_config_from_env(cls)
.. deprecated:: 2.5.3 Gets configuration out of environment. Returns list of dicts - list of namenode representations
2.21064
2.165276
1.020951
'''Upload a file to HDFS This will take a file from the ``testfiles_path`` supplied in the constuctor. ''' src = "%s%s" % (self._testfiles_path, src) return self._getStdOutCmd([self._hadoop_cmd, 'fs', '-put', src, self._full_hdfs_path(dst)], True)
def put(self, src, dst)
Upload a file to HDFS This will take a file from the ``testfiles_path`` supplied in the constuctor.
8.674157
3.77902
2.295346
return self._getReturnCodeCmd([self._hadoop_cmd, 'fs', '-test', '-d', self._full_hdfs_path(path)]) == 0
def is_directory(self, path)
Return True if <path> is a directory, False if it's NOT a directory
9.340904
8.363998
1.116799
return self._getReturnCodeCmd([self._hadoop_cmd, 'fs', '-test', '-f', self._full_hdfs_path(path)]) == 0
def is_files(self, path)
Return True if <path> is a file, False if it's NOT a file
10.578012
9.418344
1.123129
return self._getReturnCodeCmd([self._hadoop_cmd, 'fs', '-test', '-s', self._full_hdfs_path(path)]) == 0
def is_greater_then_zero_bytes(self, path)
Return True if file <path> is greater than zero bytes in size, False otherwise
12.485888
11.601006
1.076276
return self._getReturnCodeCmd([self._hadoop_cmd, 'fs', '-test', '-z', self._full_hdfs_path(path)]) == 0
def is_zero_bytes_file(self, path)
Return True if file <path> is zero bytes in size, else return False
11.720288
9.993132
1.172834