idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
9,800
def getUnionTemporalPoolerInput ( self ) : activeCells = numpy . zeros ( self . tm . numberOfCells ( ) ) . astype ( realDType ) activeCells [ list ( self . tm . activeCellsIndices ( ) ) ] = 1 predictedActiveCells = numpy . zeros ( self . tm . numberOfCells ( ) ) . astype ( realDType ) predictedActiveCells [ list ( self...
Gets the Union Temporal Pooler input from the Temporal Memory
9,801
def compute ( self , inputVector , learn , activeArray ) : x = inputVector y = self . encode ( x ) active_units = np . where ( y == 1. ) [ 0 ] if learn : self . update_statistics ( [ y ] ) self . update_weights ( [ x ] , [ y ] ) activeArray [ active_units ] = 1. return active_units
This method resembles the primary public method of the SpatialPooler class . It takes a input vector and outputs the indices of the active columns . If learn is set to True this method also performs weight updates and updates to the activity statistics according to the respective methods implemented below .
9,802
def encode_batch ( self , inputBatch ) : X = inputBatch encode = self . encode Y = np . array ( [ encode ( x ) for x in X ] ) return Y
Encodes a whole batch of input arrays without learning .
9,803
def learn ( self , x ) : y = self . encode ( x ) self . update_statistics ( [ y ] ) self . update_weights ( [ x ] , [ y ] ) return y
Encodes an input array and performs weight updates and updates to the activity statistics according to the respective methods implemented below .
9,804
def learn_batch ( self , inputBatch ) : X = inputBatch Y = self . encode_batch ( X ) self . update_statistics ( Y ) self . update_weights ( X , Y ) return Y
Encodes a whole batch of input arrays and performs weight updates and updates to the activity statistics according to the respective methods implemented below .
9,805
def update_statistics ( self , activityVectors ) : Y = activityVectors n = self . output_size A = np . zeros ( ( n , n ) ) batchSize = len ( Y ) for y in Y : active_units = np . where ( y == 1 ) [ 0 ] for i in active_units : for j in active_units : A [ i , j ] += 1. A = A / batchSize self . average_activity = self . ex...
Updates the variable that maintains exponential moving averages of individual and pairwise unit activiy
9,806
def getSparseWeights ( weightSparsity , inputSize , outputSize ) : w = torch . Tensor ( outputSize , inputSize ) stdv = 1. / math . sqrt ( w . size ( 1 ) ) w . data . uniform_ ( - stdv , stdv ) numZeros = int ( round ( ( 1.0 - weightSparsity ) * inputSize ) ) outputIndices = np . arange ( outputSize ) inputIndices = np...
Return a randomly initialized weight matrix Size is outputSize X inputSize with sparsity weightSparsity%
9,807
def plotOverlapHistogram ( v , w , title , base = "random" ) : overlaps = v . matmul ( w . t ( ) ) bins = np . linspace ( float ( overlaps . min ( ) ) , float ( overlaps . max ( ) ) , 28 ) plt . hist ( overlaps , bins , alpha = 0.5 , label = 'All cols' ) plt . legend ( loc = 'upper right' ) plt . xlabel ( "Overlap scor...
Given a vector v compute the overlap with the weight matrix w and save the histogram of overlaps .
9,808
def plotOverlaps ( vList , w , base = "random" , k = 20 ) : for i , v in enumerate ( vList ) : if i == 0 : col = "m" label = "Random vector" else : col = "c" label = "" if i == 1 : label = "Test images" overlaps = v . matmul ( w . t ( ) ) sortedOverlaps = overlaps . sort ( ) [ 0 ] . tolist ( ) [ 0 ] [ : : - 1 ] plt . p...
Given a list of vectors v compute the overlap of each with the weight matrix w and plot the overlap curves .
9,809
def random_mini_batches ( X , Y , minibatch_size , seed = None ) : d = X . shape [ 1 ] size = minibatch_size minibatches = [ ] if Y is None : Y = np . zeros ( ( 1 , d ) ) np . random . seed ( seed ) perm = np . random . permutation ( d ) for t in range ( 0 , d , size ) : subset = perm [ t : t + size ] minibatches . app...
Compute a list of minibatches from inputs X and targets Y . A datapoint is expected to be represented as a column in the data matrices X and Y .
9,810
def generateRandomSDR ( numSDR , numDims , numActiveInputBits , seed = 42 ) : randomSDRs = np . zeros ( ( numSDR , numDims ) , dtype = uintType ) indices = np . array ( range ( numDims ) ) np . random . seed ( seed ) for i in range ( numSDR ) : randomIndices = np . random . permutation ( indices ) activeBits = randomIn...
Generate a set of random SDR s
9,811
def percentOverlap ( x1 , x2 ) : nonZeroX1 = np . count_nonzero ( x1 ) nonZeroX2 = np . count_nonzero ( x2 ) percentOverlap = 0 minX1X2 = min ( nonZeroX1 , nonZeroX2 ) if minX1X2 > 0 : overlap = float ( np . dot ( x1 . T , x2 ) ) percentOverlap = overlap / minX1X2 return percentOverlap
Computes the percentage of overlap between vectors x1 and x2 .
9,812
def addNoiseToVector ( inputVector , noiseLevel , vectorType ) : if vectorType == 'sparse' : corruptSparseVector ( inputVector , noiseLevel ) elif vectorType == 'dense' : corruptDenseVector ( inputVector , noiseLevel ) else : raise ValueError ( "vectorType must be 'sparse' or 'dense' " )
Add noise to SDRs
9,813
def corruptDenseVector ( vector , noiseLevel ) : size = len ( vector ) for i in range ( size ) : rnd = random . random ( ) if rnd < noiseLevel : if vector [ i ] == 1 : vector [ i ] = 0 else : vector [ i ] = 1
Corrupts a binary vector by inverting noiseLevel percent of its bits .
9,814
def corruptSparseVector ( sdr , noiseLevel ) : numNoiseBits = int ( noiseLevel * np . sum ( sdr ) ) if numNoiseBits <= 0 : return sdr activeBits = np . where ( sdr > 0 ) [ 0 ] inActiveBits = np . where ( sdr == 0 ) [ 0 ] turnOffBits = np . random . permutation ( activeBits ) turnOnBits = np . random . permutation ( inA...
Add noise to sdr by turning off numNoiseBits active bits and turning on numNoiseBits in active bits
9,815
def calculateOverlapCurve ( sp , inputVectors ) : columnNumber = np . prod ( sp . getColumnDimensions ( ) ) numInputVector , inputSize = inputVectors . shape outputColumns = np . zeros ( ( numInputVector , columnNumber ) , dtype = uintType ) outputColumnsCorrupted = np . zeros ( ( numInputVector , columnNumber ) , dtyp...
Evalulate noise robustness of SP for a given set of SDRs
9,816
def classifySPoutput ( targetOutputColumns , outputColumns ) : numTargets , numDims = targetOutputColumns . shape overlap = np . zeros ( ( numTargets , ) ) for i in range ( numTargets ) : overlap [ i ] = percentOverlap ( outputColumns , targetOutputColumns [ i , : ] ) classLabel = np . argmax ( overlap ) return classLa...
Classify the SP output
9,817
def classificationAccuracyVsNoise ( sp , inputVectors , noiseLevelList ) : numInputVector , inputSize = inputVectors . shape if sp is None : targetOutputColumns = copy . deepcopy ( inputVectors ) else : columnNumber = np . prod ( sp . getColumnDimensions ( ) ) targetOutputColumns = np . zeros ( ( numInputVector , colum...
Evaluate whether the SP output is classifiable with varying amount of noise
9,818
def plotExampleInputOutput ( sp , inputVectors , saveFigPrefix = None ) : numInputVector , inputSize = inputVectors . shape numColumns = np . prod ( sp . getColumnDimensions ( ) ) outputColumns = np . zeros ( ( numInputVector , numColumns ) , dtype = uintType ) inputOverlap = np . zeros ( ( numInputVector , numColumns ...
Plot example input & output
9,819
def inspectSpatialPoolerStats ( sp , inputVectors , saveFigPrefix = None ) : numInputVector , inputSize = inputVectors . shape numColumns = np . prod ( sp . getColumnDimensions ( ) ) outputColumns = np . zeros ( ( numInputVector , numColumns ) , dtype = uintType ) inputOverlap = np . zeros ( ( numInputVector , numColum...
Inspect the statistics of a spatial pooler given a set of input vectors
9,820
def calculateEntropy ( activeColumns , type = 'binary' ) : activationProb = np . mean ( activeColumns , 0 ) if type == 'binary' : totalEntropy = np . sum ( binaryEntropyVectorized ( activationProb ) ) elif type == 'renyi' : totalEntropy = np . sum ( renyiEntropyVectorized ( activationProb ) ) else : raise ValueError ( ...
calculate the mean entropy given activation history
9,821
def meanMutualInformation ( sp , activeColumnsCurrentEpoch , columnsUnderInvestigation = [ ] ) : if len ( columnsUnderInvestigation ) == 0 : columns = range ( np . prod ( sp . getColumnDimensions ( ) ) ) else : columns = columnsUnderInvestigation numCols = len ( columns ) sumMutualInfo = 0 normalizingConst = numCols * ...
Computes the mean of the mutual information of pairs taken from a list of columns .
9,822
def learnL6Pattern ( self , l6Pattern , cellsToLearnOn ) : cellIndices = [ self . trnCellIndex ( x ) for x in cellsToLearnOn ] newSegments = self . trnConnections . createSegments ( cellIndices ) self . trnConnections . growSynapses ( newSegments , l6Pattern , 1.0 )
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 .
9,823
def computeFeedForwardActivity ( self , feedForwardInput ) : ff = feedForwardInput . copy ( ) 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 [ x , y ] = 1.0 continue ff2 = ff *...
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 .
9,824
def reset ( self ) : self . trnOverlaps = [ ] self . activeTRNSegments = [ ] self . activeTRNCellIndices = [ ] self . relayOverlaps = [ ] self . activeRelaySegments = [ ] self . burstReadyCellIndices = [ ] self . burstReadyCells = np . zeros ( ( self . relayWidth , self . relayHeight ) )
Set everything back to zero
9,825
def _initializeTRNToRelayCellConnections ( self ) : for x in range ( self . relayWidth ) : for y in range ( self . relayHeight ) : relayCellIndex = self . relayCellIndex ( ( x , y ) ) trnCells = self . _preSynapticTRNCells ( x , y ) for trnCell in trnCells : newSegment = self . relayConnections . createSegments ( [ rel...
Initialize TRN to relay cell connectivity . For each relay cell create a dendritic segment for each TRN cell it connects to .
9,826
def countWordOverlapFrequencies ( filename = "goodOverlapPairs.pkl" ) : 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 ) wordFrequencies = { } for w1 , w2 , overlap in goodOverlapPairs : wordFrequenci...
Count how many high overlaps each word has and print it out
9,827
def activateCells ( self , activeColumns , basalReinforceCandidates , apicalReinforceCandidates , basalGrowthCandidates , apicalGrowthCandidates , learn = True ) : ( correctPredictedCells , burstingColumns ) = np2 . setCompare ( self . predictedCells , activeColumns , self . predictedCells / self . cellsPerColumn , rig...
Activate cells in the specified columns using the result of the previous depolarizeCells as predictions . Then learn .
9,828
def _calculateLearning ( self , activeColumns , burstingColumns , correctPredictedCells , activeBasalSegments , activeApicalSegments , matchingBasalSegments , matchingApicalSegments , basalPotentialOverlaps , apicalPotentialOverlaps ) : learningActiveBasalSegments = self . basalConnections . filterSegmentsByCell ( acti...
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 .
9,829
def _learnOnNewSegments ( connections , rng , newSegmentCells , growthCandidates , initialPermanence , sampleSize , maxSynapsesPerSegment ) : numNewSynapses = len ( growthCandidates ) if sampleSize != - 1 : numNewSynapses = min ( numNewSynapses , sampleSize ) if maxSynapsesPerSegment != - 1 : numNewSynapses = min ( num...
Create new segments and grow synapses on them .
9,830
def _chooseBestSegmentPairPerColumn ( self , matchingCellsInBurstingColumns , matchingBasalSegments , matchingApicalSegments , basalPotentialOverlaps , apicalPotentialOverlaps ) : basalCandidateSegments = self . basalConnections . filterSegmentsByCell ( matchingBasalSegments , matchingCellsInBurstingColumns ) apicalCan...
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 .
9,831
def compute ( self , activeColumns , basalInput , apicalInput = ( ) , basalGrowthCandidates = None , apicalGrowthCandidates = None , learn = True ) : activeColumns = np . asarray ( activeColumns ) basalInput = np . asarray ( basalInput ) apicalInput = np . asarray ( apicalInput ) if basalGrowthCandidates is None : basa...
Perform one timestep . Use the basal and apical input to form a set of predictions then activate the specified columns then learn .
9,832
def compute ( self , activeColumns , apicalInput = ( ) , apicalGrowthCandidates = None , learn = True ) : activeColumns = np . asarray ( activeColumns ) apicalInput = np . asarray ( apicalInput ) if apicalGrowthCandidates is None : apicalGrowthCandidates = apicalInput apicalGrowthCandidates = np . asarray ( apicalGrowt...
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 .
9,833
def createLocationEncoder ( t , w = 15 ) : encoder = CoordinateEncoder ( name = "positionEncoder" , n = t . l6CellCount , w = w ) return encoder
A default coordinate encoder for encoding locations into sparse distributed representations .
9,834
def getUnionLocations ( encoder , x , y , r , step = 1 ) : 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 )...
Return a union of location encodings that correspond to the union of all locations within the specified circle .
9,835
def _calculateBasalLearning ( self , activeColumns , burstingColumns , correctPredictedCells , activeBasalSegments , matchingBasalSegments , basalPotentialOverlaps ) : learningActiveBasalSegments = self . basalConnections . filterSegmentsByCell ( activeBasalSegments , correctPredictedCells ) cellsForMatchingBasal = sel...
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 .
9,836
def _calculateApicalLearning ( self , learningCells , activeColumns , activeApicalSegments , matchingApicalSegments , apicalPotentialOverlaps ) : learningActiveApicalSegments = self . apicalConnections . filterSegmentsByCell ( activeApicalSegments , learningCells ) learningCellsWithoutActiveApical = np . setdiff1d ( le...
Calculate apical learning for each learning cell .
9,837
def _calculateApicalSegmentActivity ( connections , activeInput , connectedPermanence , activationThreshold , minThreshold ) : overlaps = connections . computeActivity ( activeInput , connectedPermanence ) activeSegments = np . flatnonzero ( overlaps >= activationThreshold ) potentialOverlaps = connections . computeAct...
Calculate the active and matching apical segments for this timestep .
9,838
def _calculatePredictedCells ( self , activeBasalSegments , activeApicalSegments ) : cellsForBasalSegments = self . basalConnections . mapSegmentsToCells ( activeBasalSegments ) cellsForApicalSegments = self . apicalConnections . mapSegmentsToCells ( activeApicalSegments ) fullyDepolarizedCells = np . intersect1d ( cel...
Calculate the predicted cells given the set of active segments .
9,839
def _chooseBestSegmentPerCell ( cls , connections , cells , allMatchingSegments , potentialOverlaps ) : candidateSegments = connections . filterSegmentsByCell ( allMatchingSegments , cells ) onePerCellFilter = np2 . argmaxMulti ( potentialOverlaps [ candidateSegments ] , connections . mapSegmentsToCells ( candidateSegm...
For each specified cell choose its matching segment with largest number of active potential synapses . When there s a tie the first segment wins .
9,840
def _chooseBestSegmentPerColumn ( cls , connections , matchingCells , allMatchingSegments , potentialOverlaps , cellsPerColumn ) : candidateSegments = connections . filterSegmentsByCell ( allMatchingSegments , matchingCells ) cellScores = potentialOverlaps [ candidateSegments ] columnsForCandidates = ( connections . ma...
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 .
9,841
def infer ( self , sensationList , reset = True , objectName = None ) : self . _unsetLearningMode ( ) statistics = collections . defaultdict ( list ) for sensations in sensationList : for col in xrange ( self . numColumns ) : location , feature = sensations [ col ] self . sensorInputs [ col ] . addDataToQueue ( list ( ...
Infer on given sensations .
9,842
def _saveL2Representation ( self , objectName ) : self . objectL2Representations [ objectName ] = self . getL2Representations ( ) try : objectIndex = self . objectNameToIndex [ objectName ] except KeyError : if self . objectNamesAreIndices : objectIndex = objectName if objectIndex >= self . objectL2RepresentationsMatri...
Record the current active L2 cells as the representation for objectName .
9,843
def plotInferenceStats ( self , fields , plotDir = "plots" , experimentID = 0 , onePlot = True ) : 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 . ...
Plots and saves the desired inference statistics .
9,844
def averageConvergencePoint ( self , prefix , minOverlap , maxOverlap , settlingTime = 1 , firstStat = 0 , lastStat = None ) : convergenceSum = 0.0 numCorrect = 0.0 inferenceLength = 1000000 for stats in self . statistics [ firstStat : lastStat ] : convergencePoint = 0.0 for key in stats . iterkeys ( ) : if prefix in k...
For each object compute the convergence time - the first point when all L2 columns have converged .
9,845
def getAlgorithmInstance ( self , layer = "L2" , column = 0 ) : 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 ] . getAlgorith...
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 .
9,846
def getCurrentObjectOverlaps ( self ) : 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 , : ] = r...
Get every L2 s current overlap with each L2 object representation that has been learned .
9,847
def isObjectClassified ( self , objectName , minOverlap = None , maxL2Size = None ) : L2Representation = self . getL2Representations ( ) objectRepresentation = self . objectL2Representations [ objectName ] sdrSize = self . config [ "L2Params" ] [ "sdrSize" ] if minOverlap is None : minOverlap = sdrSize / 2 if maxL2Size...
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
9,848
def getDefaultL4Params ( self , inputSize , numInputBits ) : 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 = activationThres...
Returns a good default set of parameters to use in the L4 region .
9,849
def getDefaultL2Params ( self , inputSize , numInputBits ) : if numInputBits == 20 : sampleSizeProximal = 10 minThresholdProximal = 5 elif numInputBits == 10 : sampleSizeProximal = 6 minThresholdProximal = 3 else : sampleSizeProximal = int ( numInputBits * .6 ) minThresholdProximal = int ( sampleSizeProximal * .6 ) ret...
Returns a good default set of parameters to use in the L2 region .
9,850
def generateFeatures ( numFeatures ) : 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 candidates return c...
Return string features .
9,851
def addMonitor ( self , monitor ) : token = self . nextMonitorToken self . nextMonitorToken += 1 self . monitors [ token ] = monitor return token
Subscribe to SingleLayer2DExperiment events .
9,852
def doTimestep ( self , locationSDR , transitionSDR , featureSDR , egocentricLocation , learn ) : for monitor in self . monitors . values ( ) : monitor . beforeTimestep ( locationSDR , transitionSDR , featureSDR , egocentricLocation , learn ) params = { "newLocation" : locationSDR , "deltaLocation" : transitionSDR , "f...
Run one timestep .
9,853
def learnTransitions ( self ) : 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 ) : for _ i...
Train the location layer to do path integration . For every location teach it each previous - location + motor command pair .
9,854
def learnObjects ( self , objectPlacements ) : 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 . ...
Learn each provided object in egocentric space . Touch every location on each object .
9,855
def _selectTransition ( self , allocentricLocation , objectDict , visitCounts ) : candidates = list ( transition for transition in self . transitions . keys ( ) if ( allocentricLocation [ 0 ] + transition [ 0 ] , allocentricLocation [ 1 ] + transition [ 1 ] ) in objectDict ) random . shuffle ( candidates ) selectedVisi...
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 .
9,856
def reset ( self ) : 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 . _minOve...
Reset the state of the temporal pooler
9,857
def compute ( self , inputVector , learn , activeArray , burstingColumns , predictedCells ) : assert ( numpy . size ( inputVector ) == self . _numInputs ) assert ( numpy . size ( predictedCells ) == self . _numInputs ) self . _updateBookeepingVars ( learn ) inputVector = numpy . array ( inputVector , dtype = realDType ...
This is the primary public method of the class . This function takes an input vector and outputs the indices of the active columns .
9,858
def printParameters ( self ) : print "------------PY TemporalPooler Parameters ------------------" print "numInputs = " , self . getNumInputs ( ) print "numColumns = " , self . getNumColumns ( ) print "columnDimensions = " , self . _columnDimensions print "numActiveColumnsPer...
Useful for debugging .
9,859
def train ( self , inputData , numIterations , reset = False ) : 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 ) if batch . shape [ 0 ] != self . filte...
Trains the SparseNet with the provided data .
9,860
def encode ( self , data , flatten = False ) : if not isinstance ( data , np . ndarray ) : data = np . array ( data ) if flatten : try : data = np . reshape ( data , ( self . filterDim , data . shape [ - 1 ] ) ) except ValueError : data = np . reshape ( data , ( self . filterDim , 1 ) ) if data . shape [ 0 ] != self . ...
Encodes the provided input data returning a sparse vector of activations .
9,861
def plotLoss ( self , filename = None ) : 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 )
Plots the loss history .
9,862
def plotBasis ( self , filename = None ) : 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 ...
Plots the basis functions reshaped in 2 - dimensional arrays .
9,863
def _reset ( self ) : 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 = { }
Reinitializes basis functions iteration number and loss history .
9,864
def read ( cls , proto ) : 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 [ los...
Reads deserialized data from proto object
9,865
def write ( self , proto ) : 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 ...
Writes serialized data to proto object
9,866
def reset ( self ) : 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 (...
Reset the state of the Union Temporal Pooler .
9,867
def compute ( self , activeInput , predictedActiveInput , learn ) : assert numpy . size ( activeInput ) == self . getNumInputs ( ) assert numpy . size ( predictedActiveInput ) == self . getNumInputs ( ) self . _updateBookeepingVars ( learn ) overlapsActive = self . _calculateOverlap ( activeInput ) overlapsPredictedAct...
Computes one cycle of the Union Temporal Pooler algorithm .
9,868
def _decayPoolingActivation ( self ) : if self . _decayFunctionType == 'NoDecay' : self . _poolingActivation = self . _decayFunction . decay ( self . _poolingActivation ) elif self . _decayFunctionType == 'Exponential' : self . _poolingActivation = self . _decayFunction . decay ( self . _poolingActivationInitLevel , se...
Decrements pooling activation of all cells
9,869
def _addToPoolingActivation ( self , activeCells , overlaps ) : self . _poolingActivation [ activeCells ] = self . _exciteFunction . excite ( self . _poolingActivation [ activeCells ] , overlaps [ activeCells ] ) self . _poolingTimer [ self . _poolingTimer >= 0 ] += 1 self . _poolingTimer [ activeCells ] = 0 self . _po...
Adds overlaps from specified active cells to cells pooling activation .
9,870
def _getMostActiveCells ( self ) : poolingActivation = self . _poolingActivation nonZeroCells = numpy . argwhere ( poolingActivation > 0 ) [ : , 0 ] poolingActivationSubset = poolingActivation [ nonZeroCells ] + self . _poolingActivation_tieBreaker [ nonZeroCells ] potentialUnionSDR = nonZeroCells [ numpy . argsort ( p...
Gets the most active cells in the Union SDR having at least non - zero activation in sorted order .
9,871
def createNetwork ( networkConfig ) : registerAllResearchRegions ( ) network = Network ( ) if networkConfig [ "networkType" ] == "L4L2Column" : return createL4L2Column ( network , networkConfig , "_0" ) elif networkConfig [ "networkType" ] == "MultipleL4L2Columns" : return createMultipleL4L2Columns ( network , networkC...
Create and initialize the specified network instance .
9,872
def printNetwork ( network ) : 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
Given a network print out regions sorted by phase
9,873
def fit_params_to_1d_data ( logX ) : 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
Fit skewed normal distributions to 1 - D capactity data and return the distribution parameters .
9,874
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 . p...
Get parameters describing a 1 - D capactity distribution for fractional number of modules .
9,875
def rerunExperimentFromLogfile ( logFilename ) : callLog = LoggingDecorator . load ( logFilename ) exp = L246aNetwork ( * callLog [ 0 ] [ 1 ] [ "args" ] , ** callLog [ 0 ] [ 1 ] [ "kwargs" ] ) for call in callLog [ 1 : ] : method = getattr ( exp , call [ 0 ] ) method ( * call [ 1 ] [ "args" ] , ** call [ 1 ] [ "kwargs"...
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
9,876
def learn ( self , objects ) : 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 ( ...
Learns all provided objects
9,877
def getL2Representations ( self ) : return [ set ( L2 . getSelf ( ) . _pooler . getActiveCells ( ) ) for L2 in self . L2Regions ]
Returns the active representation in L2 .
9,878
def excite ( self , currentActivation , inputs ) : currentActivation += self . _minValue + ( self . _maxValue - self . _minValue ) / ( 1 + numpy . exp ( - self . _steepness * ( inputs - self . _xMidpoint ) ) ) return currentActivation
Increases current activation by amount .
9,879
def plot ( self ) : plt . ion ( ) plt . show ( ) x = numpy . linspace ( 0 , 15 , 100 ) y = numpy . zeros ( x . shape ) y = self . excite ( y , x ) plt . plot ( x , y ) plt . xlabel ( 'Input' ) plt . ylabel ( 'Persistence' ) plt . title ( 'Sigmoid Activation Function' )
plot the activation function
9,880
def computeAccuracyEnding ( predictions , truths , iterations , resets = None , randoms = None , num = None , sequenceCounter = None ) : accuracy = [ ] numIteration = [ ] numSequences = [ ] for i in xrange ( len ( predictions ) - 1 ) : if num is not None and i > num : continue if truths [ i ] is None : continue if rese...
Compute accuracy on the sequence ending
9,881
def createValidationDataSampler ( dataset , ratio ) : indices = np . random . permutation ( len ( dataset ) ) training_count = int ( len ( indices ) * ratio ) train = torch . utils . data . SubsetRandomSampler ( indices = indices [ : training_count ] ) validate = torch . utils . data . SubsetRandomSampler ( indices = i...
Create torch . utils . data . Sampler s used to split the dataset into 2 ramdom sampled subsets . The first should used for training and the second for validation .
9,882
def register_nonzero_counter ( network , stats ) : if hasattr ( network , "__counter_nonzero__" ) : raise ValueError ( "nonzero counter was already registered for this network" ) if not isinstance ( stats , dict ) : raise ValueError ( "stats must be a dictionary" ) network . __counter_nonzero__ = stats handles = [ ] fo...
Register forward hooks to count the number of nonzero floating points values from all the tensors used by the given network during inference .
9,883
def initialize ( self , params , repetition ) : super ( TinyCIFARExperiment , self ) . initialize ( params , repetition ) self . network_type = params . get ( "network_type" , "sparse" )
Initialize experiment parameters and default values from configuration file . Called at the beginning of each experiment and each repetition .
9,884
def logger ( self , iteration , ret ) : print ( "Learning rate: {:f}" . format ( self . lr_scheduler . get_lr ( ) [ 0 ] ) ) entropies = getEntropies ( self . model ) print ( "Entropy and max entropy: " , float ( entropies [ 0 ] ) , entropies [ 1 ] ) print ( "Training time for epoch=" , self . epoch_train_time ) for noi...
Print out relevant information at each epoch
9,885
def plotAccuracyAndMCsDuringDecrementChange ( results , title = "" , yaxis = "" ) : decrementRange = [ ] mcRange = [ ] for r in results : if r [ "basalPredictedSegmentDecrement" ] not in decrementRange : decrementRange . append ( r [ "basalPredictedSegmentDecrement" ] ) if r [ "inputSize" ] not in mcRange : mcRange . a...
Plot accuracy vs decrement value
9,886
def gen4 ( dirName ) : try : resultsFig4A = os . path . join ( dirName , "pure_sequences_example.pkl" ) with open ( resultsFig4A , "rb" ) as f : results = cPickle . load ( f ) for trialNum , stat in enumerate ( results [ "statistics" ] ) : plotOneInferenceRun ( stat , itemType = "a single sequence" , fields = [ ( "L4 P...
Plots 4A and 4B
9,887
def compute ( self , inputs , outputs ) : if len ( self . queue ) > 0 : data = self . queue . pop ( ) else : raise Exception ( "RawSensor: No data to encode: queue is empty " ) outputs [ "resetOut" ] [ 0 ] = data [ "reset" ] outputs [ "sequenceIdOut" ] [ 0 ] = data [ "sequenceId" ] outputs [ "dataOut" ] [ : ] = 0 outpu...
Get the next record from the queue and encode it . The fields for inputs and outputs are as defined in the spec above .
9,888
def convertSequenceMachineSequence ( generatedSequences ) : sequenceList = [ ] currentSequence = [ ] for s in generatedSequences : if s is None : sequenceList . append ( currentSequence ) currentSequence = [ ] else : currentSequence . append ( s ) return sequenceList
Convert a sequence from the SequenceMachine into a list of sequences such that each sequence is a list of set of SDRs .
9,889
def generateSequences ( n = 2048 , w = 40 , sequenceLength = 5 , sequenceCount = 2 , sharedRange = None , seed = 42 ) : patternAlphabetSize = 10 * ( sequenceLength * sequenceCount ) patternMachine = PatternMachine ( n , w , patternAlphabetSize , seed ) sequenceMachine = SequenceMachine ( patternMachine , seed ) numbers...
Generate high order sequences using SequenceMachine
9,890
def runInference ( exp , sequences , enableFeedback = True ) : if enableFeedback : print "Feedback enabled: " else : print "Feedback disabled: " error = 0 activityTraces = [ ] responses = [ ] for i , sequence in enumerate ( sequences ) : ( avgActiveCells , avgPredictedActiveCells , activityTrace , responsesThisSeq ) = ...
Run inference on this set of sequences and compute error
9,891
def runStretch ( noiseLevel = None , profile = False ) : exp = L4L2Experiment ( "stretch_L10_F10_C2" , numCorticalColumns = 2 , ) objects = createObjectMachine ( machineType = "simple" , numInputBits = 20 , sensorInputSize = 1024 , externalInputSize = 1024 , numCorticalColumns = 2 , ) objects . createRandomObjects ( 10...
Stretch test that learns a lot of objects .
9,892
def trainModel ( model , loader , optimizer , device , criterion = F . nll_loss , batches_in_epoch = sys . maxsize , batch_callback = None , progress_bar = None ) : model . train ( ) if progress_bar is not None : loader = tqdm ( loader , ** progress_bar ) if batches_in_epoch < len ( loader ) : loader . total = batches_...
Train the given model by iterating through mini batches . An epoch ends after one pass through the training set or if the number of mini batches exceeds the parameter batches_in_epoch .
9,893
def evaluateModel ( model , loader , device , batches_in_epoch = sys . maxsize , criterion = F . nll_loss , progress = None ) : model . eval ( ) loss = 0 correct = 0 dataset_len = len ( loader . sampler ) if progress is not None : loader = tqdm ( loader , ** progress ) with torch . no_grad ( ) : for batch_idx , ( data ...
Evaluate pre - trained model using given test dataset loader .
9,894
def run_false_positive_experiment_dim ( numActive = 128 , dim = 500 , numSamples = 1000 , numDendrites = 500 , synapses = 24 , numTrials = 10000 , seed = 42 , nonlinearity = sigmoid_nonlinearity ( 11.5 , 5 ) ) : numpy . random . seed ( seed ) fps = [ ] fns = [ ] totalUnclassified = 0 for trial in range ( numTrials ) : ...
Run an experiment to test the false positive rate based on number of synapses per dendrite dimension and sparsity . Uses two competing neurons along the P&M model .
9,895
def _getRadius ( self , location ) : return int ( math . sqrt ( sum ( [ coord ** 2 for coord in location ] ) ) )
Returns the radius associated with the given location .
9,896
def _addNoise ( self , pattern , noiseLevel ) : if pattern is None : return None newBits = [ ] for bit in pattern : if random . random ( ) < noiseLevel : newBits . append ( random . randint ( 0 , max ( pattern ) ) ) else : newBits . append ( bit ) return set ( newBits )
Adds noise the given list of patterns and returns a list of noisy copies .
9,897
def apicalCheck ( self , apicalInput ) : ( activeApicalSegments , matchingApicalSegments , apicalPotentialOverlaps ) = self . _calculateSegmentActivity ( self . apicalConnections , apicalInput , self . connectedPermanence , self . activationThreshold , self . minThreshold , self . reducedBasalThreshold ) apicallySuppor...
Return recent apically predicted cells for each tick of apical timer - finds active apical segments corresponding to predicted basal segment
9,898
def setupData ( self , dataPath , numLabels = 0 , ordered = False , stripCats = False , seed = 42 , ** kwargs ) : self . split ( dataPath , numLabels , ** kwargs ) if not ordered : self . randomizeData ( seed ) filename , ext = os . path . splitext ( dataPath ) classificationFileName = "{}_category.json" . format ( fil...
Main method of this class . Use for setting up a network data file .
9,899
def _formatSequence ( tokens , categories , seqID , uniqueID ) : record = { "_category" : categories , "_sequenceId" : seqID } data = [ ] reset = 1 for t in tokens : tokenRecord = record . copy ( ) tokenRecord [ "_token" ] = t tokenRecord [ "_reset" ] = reset tokenRecord [ "ID" ] = uniqueID reset = 0 data . append ( to...
Write the sequence of data records for this sample .