idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
10,000 | def numberOfConnectedDistalSynapses ( self , cells = None ) : if cells is None : cells = xrange ( self . numberOfCells ( ) ) n = _countWhereGreaterEqualInRows ( self . internalDistalPermanences , cells , self . connectedPermanenceDistal ) for permanences in self . distalPermanences : n += _countWhereGreaterEqualInRows ... | Returns the number of connected distal synapses on these cells . |
10,001 | def _learn ( permanences , rng , activeCells , activeInput , growthCandidateInput , sampleSize , initialPermanence , permanenceIncrement , permanenceDecrement , connectedPermanence ) : permanences . incrementNonZerosOnOuter ( activeCells , activeInput , permanenceIncrement ) permanences . incrementNonZerosOnRowsExcludi... | For each active cell reinforce active synapses punish inactive synapses and grow new synapses to a subset of the active input bits that the cell isn t already connected to . |
10,002 | def runExperiment ( n , w , threshold , cellsPerColumn , folder , numTrials = 5 , cleverTMSDRs = False ) : if not os . path . exists ( folder ) : try : os . makedirs ( folder ) except OSError : pass filename = "{}/n_{}_w_{}_threshold_{}_cellsPerColumn_{}.json" . format ( folder , n , w , threshold , cellsPerColumn ) if... | Run a PoolOfPairsLocation1DExperiment various union sizes . |
10,003 | def train ( self ) : for iDriving , cDriving in enumerate ( self . drivingOperandSDRs ) : minicolumnSDR = self . minicolumnSDRs [ iDriving ] self . pairLayerProximalConnections . associate ( minicolumnSDR , cDriving ) for iContext , cContext in enumerate ( self . contextOperandSDRs ) : iResult = ( iContext + iDriving )... | Train the pair layer and pooling layer . |
10,004 | def run_noise_experiment ( num_neurons = 1 , a = 128 , dim = 6000 , test_noise_levels = range ( 15 , 100 , 5 ) , num_samples = 500 , num_dendrites = 500 , dendrite_length = 30 , theta = 8 , num_trials = 100 ) : nonlinearity = threshold_nonlinearity ( theta ) for noise in test_noise_levels : fps = [ ] fns = [ ] for tria... | Tests the impact of noise on a neuron using an HTM approach to a P&M model of a neuron . Nonlinearity is a simple threshold at theta as in the original version of this experiment and each dendrite is bound by the initialization to a single pattern . Only one neuron is used unlike in the P&M classification experiment an... |
10,005 | def reset ( self , params , repetition ) : pprint . pprint ( params ) self . initialize ( params , repetition ) dataDir = params . get ( 'dataDir' , 'data' ) self . transform_train = transforms . Compose ( [ transforms . RandomCrop ( 32 , padding = 4 ) , transforms . RandomHorizontalFlip ( ) , transforms . ToTensor ( )... | Called at the beginning of each experiment and each repetition |
10,006 | def killCellRegion ( self , centerColumn , radius ) : self . deadCols = topology . wrappingNeighborhood ( centerColumn , radius , self . _columnDimensions ) self . deadColumnInputSpan = self . getConnectedSpan ( self . deadCols ) self . removeDeadColumns ( ) | Kill cells around a centerColumn within radius |
10,007 | def compute ( self , inputVector , learn , activeArray ) : if not isinstance ( inputVector , numpy . ndarray ) : raise TypeError ( "Input vector must be a numpy array, not %s" % str ( type ( inputVector ) ) ) if inputVector . size != self . _numInputs : raise ValueError ( "Input vector dimensions don't match. Expecting... | This is the primary public method of the SpatialPooler class . This function takes a input vector and outputs the indices of the active columns . If learn is set to True this method also updates the permanences of the columns . |
10,008 | def getConstructorArguments ( ) : argspec = inspect . getargspec ( ColumnPooler . __init__ ) return argspec . args [ 1 : ] , argspec . defaults | Return constructor argument associated with ColumnPooler . |
10,009 | def initialize ( self ) : if self . _pooler is None : params = { "inputWidth" : self . inputWidth , "lateralInputWidths" : [ self . cellCount ] * self . numOtherCorticalColumns , "cellCount" : self . cellCount , "sdrSize" : self . sdrSize , "onlineLearning" : self . onlineLearning , "maxSdrSize" : self . maxSdrSize , "... | Initialize the internal objects . |
10,010 | def compute ( self , inputs , outputs ) : if "resetIn" in inputs : assert len ( inputs [ "resetIn" ] ) == 1 if inputs [ "resetIn" ] [ 0 ] != 0 : self . reset ( ) outputs [ "feedForwardOutput" ] [ : ] = 0 outputs [ "activeCells" ] [ : ] = 0 return feedforwardInput = numpy . asarray ( inputs [ "feedforwardInput" ] . nonz... | Run one iteration of compute . |
10,011 | def progress ( params , rep ) : name = params [ 'name' ] fullpath = os . path . join ( params [ 'path' ] , params [ 'name' ] ) logname = os . path . join ( fullpath , '%i.log' % rep ) if os . path . exists ( logname ) : logfile = open ( logname , 'r' ) lines = logfile . readlines ( ) logfile . close ( ) return int ( 10... | Helper function to calculate the progress made on one experiment . |
10,012 | def convert_param_to_dirname ( param ) : if type ( param ) == types . StringType : return param else : return re . sub ( "0+$" , '0' , '%f' % param ) | Helper function to convert a parameter value to a valid directory name . |
10,013 | def parse_opt ( self ) : optparser = optparse . OptionParser ( ) optparser . add_option ( '-c' , '--config' , action = 'store' , dest = 'config' , type = 'string' , default = 'experiments.cfg' , help = "your experiments config file" ) optparser . add_option ( '-n' , '--numcores' , action = 'store' , dest = 'ncores' , t... | parses the command line options for different settings . |
10,014 | def parse_cfg ( self ) : self . cfgparser = ConfigParser ( ) if not self . cfgparser . read ( self . options . config ) : raise SystemExit ( 'config file %s not found.' % self . options . config ) projectDir = os . path . dirname ( self . options . config ) projectDir = os . path . abspath ( projectDir ) os . chdir ( p... | parses the given config file for experiments . |
10,015 | def mkdir ( self , path ) : if not os . path . exists ( path ) : os . makedirs ( path ) | create a directory if it does not exist . |
10,016 | def write_config_file ( self , params , path ) : cfgp = ConfigParser ( ) cfgp . add_section ( params [ 'name' ] ) for p in params : if p == 'name' : continue cfgp . set ( params [ 'name' ] , p , params [ p ] ) f = open ( os . path . join ( path , 'experiment.cfg' ) , 'w' ) cfgp . write ( f ) f . close ( ) | write a config file for this single exp in the folder path . |
10,017 | def get_history ( self , exp , rep , tags ) : params = self . get_params ( exp ) if params == None : raise SystemExit ( 'experiment %s not found.' % exp ) if tags != 'all' and not hasattr ( tags , '__iter__' ) : tags = [ tags ] results = { } logfile = os . path . join ( exp , '%i.log' % rep ) try : f = open ( logfile )... | returns the whole history for one experiment and one repetition . tags can be a string or a list of strings . if tags is a string the history is returned as list of values if tags is a list of strings or all history is returned as a dictionary of lists of values . |
10,018 | def create_dir ( self , params , delete = False ) : fullpath = os . path . join ( params [ 'path' ] , params [ 'name' ] ) self . mkdir ( fullpath ) if delete and os . path . exists ( fullpath ) : os . system ( 'rm %s/*' % fullpath ) self . write_config_file ( params , fullpath ) | creates a subdirectory for the experiment and deletes existing files if the delete flag is true . then writes the current experiment . cfg file in the folder . |
10,019 | def start ( self ) : self . parse_opt ( ) self . parse_cfg ( ) if self . options . browse or self . options . browse_big or self . options . progress : self . browse ( ) raise SystemExit paramlist = [ ] for exp in self . cfgparser . sections ( ) : if not self . options . experiments or exp in self . options . experimen... | starts the experiments as given in the config file . |
10,020 | def run_rep ( self , params , rep ) : try : name = params [ 'name' ] fullpath = os . path . join ( params [ 'path' ] , params [ 'name' ] ) logname = os . path . join ( fullpath , '%i.log' % rep ) restore = 0 if os . path . exists ( logname ) : logfile = open ( logname , 'r' ) lines = logfile . readlines ( ) logfile . c... | run a single repetition including directory creation log files etc . |
10,021 | def getClusterPrototypes ( self , numClusters , numPrototypes = 1 ) : linkage = self . getLinkageMatrix ( ) linkage [ : , 2 ] -= linkage [ : , 2 ] . min ( ) clusters = scipy . cluster . hierarchy . fcluster ( linkage , numClusters , criterion = "maxclust" ) prototypes = [ ] clusterSizes = [ ] for cluster_id in numpy . ... | Create numClusters flat clusters and find approximately numPrototypes prototypes per flat cluster . Returns an array with each row containing the indices of the prototypes for a single flat cluster . |
10,022 | def _getPrototypes ( indices , overlaps , topNumber = 1 ) : n = numpy . roots ( [ 1 , - 1 , - 2 * len ( overlaps ) ] ) . max ( ) k = len ( indices ) indices = numpy . array ( indices , dtype = int ) rowIdxs = numpy . ndarray ( ( k , k - 1 ) , dtype = int ) colIdxs = numpy . ndarray ( ( k , k - 1 ) , dtype = int ) for i... | Given a compressed overlap array and a set of indices specifying a subset of those in that array return the set of topNumber indices of vectors that have maximum average overlap with other vectors in indices . |
10,023 | def analyzeParameters ( expName , suite ) : print ( "\n================" , expName , "=====================" ) try : expParams = suite . get_params ( expName ) pprint . pprint ( expParams ) for p in [ "boost_strength" , "k" , "learning_rate" , "weight_sparsity" , "k_inference_factor" , "boost_strength_factor" , "c1_out... | Analyze the impact of each list parameter in this experiment |
10,024 | def summarizeResults ( expName , suite ) : print ( "\n================" , expName , "=====================" ) try : values , params = suite . get_values_fix_params ( expName , 0 , "totalCorrect" , "last" ) v = np . array ( values ) sortedIndices = v . argsort ( ) for i in sortedIndices [ : : - 1 ] : print ( v [ i ] , p... | Summarize the totalCorrect value from the last iteration for each experiment in the directory tree . |
10,025 | def learningCurve ( expPath , suite ) : print ( "\nLEARNING CURVE ================" , expPath , "=====================" ) try : headers = [ "testerror" , "totalCorrect" , "elapsedTime" , "entropy" ] result = suite . get_value ( expPath , 0 , headers , "all" ) info = [ ] for i , v in enumerate ( zip ( result [ "testerro... | Print the test and overall noise errors from each iteration of this experiment |
10,026 | def compute ( self , inputs , outputs ) : if len ( self . queue ) > 0 : data = self . queue . pop ( ) else : raise Exception ( "CoordinateSensor: No data to encode: queue is empty" ) outputs [ "resetOut" ] [ 0 ] = data [ "reset" ] outputs [ "sequenceIdOut" ] [ 0 ] = data [ "sequenceId" ] sdr = self . encoder . encode (... | Get the next record from the queue and encode it . |
10,027 | def printDiagnostics ( exp , sequences , objects , args , verbosity = 0 ) : print "Experiment start time:" , time . ctime ( ) print "\nExperiment arguments:" pprint . pprint ( args ) r = sequences . objectConfusion ( ) print "Average common pairs in sequences=" , r [ 0 ] , print ", features=" , r [ 2 ] r = objects . ob... | Useful diagnostics for debugging . |
10,028 | def createArgs ( ** kwargs ) : if len ( kwargs ) == 0 : return [ { } ] kargs = deepcopy ( kwargs ) k1 = kargs . keys ( ) [ 0 ] values = kargs . pop ( k1 ) args = [ ] otherArgs = createArgs ( ** kargs ) for v in values : newArgs = deepcopy ( otherArgs ) arg = { k1 : v } for newArg in newArgs : newArg . update ( arg ) ar... | Each kwarg is a list . Return a list of dicts representing all possible combinations of the kwargs . |
10,029 | def randomizeSequence ( sequence , symbolsPerSequence , numColumns , sparsity , p = 0.25 ) : randomizedSequence = [ ] sparseCols = int ( numColumns * sparsity ) numSymbolsToChange = int ( symbolsPerSequence * p ) symIndices = np . random . permutation ( np . arange ( symbolsPerSequence ) ) for symbol in range ( symbols... | Takes a sequence as input and randomizes a percentage p of it by choosing SDRs at random while preserving the remaining invariant . |
10,030 | def generateHOSequence ( sequence , symbolsPerSequence , numColumns , sparsity ) : sequenceHO = [ ] sparseCols = int ( numColumns * sparsity ) for symbol in range ( symbolsPerSequence ) : if symbol == 0 or symbol == ( symbolsPerSequence - 1 ) : sequenceHO . append ( generateRandomSymbol ( numColumns , sparseCols ) ) el... | Generates a high - order sequence by taking an initial sequence and the changing its first and last SDRs by random SDRs |
10,031 | def percentOverlap ( x1 , x2 , numColumns ) : nonZeroX1 = np . count_nonzero ( x1 ) nonZeroX2 = np . count_nonzero ( x2 ) sparseCols = min ( nonZeroX1 , nonZeroX2 ) binX1 = np . zeros ( numColumns , dtype = "uint32" ) binX2 = np . zeros ( numColumns , dtype = "uint32" ) for i in range ( sparseCols ) : binX1 [ x1 [ i ] ... | Calculates the percentage of overlap between two SDRs |
10,032 | def generateRandomSymbol ( numColumns , sparseCols ) : symbol = list ( ) remainingCols = sparseCols while remainingCols > 0 : col = random . randrange ( numColumns ) if col not in symbol : symbol . append ( col ) remainingCols -= 1 return symbol | Generates a random SDR with sparseCols number of active columns |
10,033 | def generateRandomSequence ( numSymbols , numColumns , sparsity ) : sequence = [ ] sparseCols = int ( numColumns * sparsity ) for _ in range ( numSymbols ) : sequence . append ( generateRandomSymbol ( numColumns , sparseCols ) ) return sequence | Generate a random sequence comprising numSymbols SDRs |
10,034 | def accuracy ( current , predicted ) : acc = 0 if np . count_nonzero ( predicted ) > 0 : acc = float ( np . dot ( current , predicted ) ) / float ( np . count_nonzero ( predicted ) ) return acc | Computes the accuracy of the TM at time - step t based on the prediction at time - step t - 1 and the current active columns at time - step t . |
10,035 | def sampleCellsWithinColumns ( numCellPairs , cellsPerColumn , numColumns , seed = 42 ) : np . random . seed ( seed ) cellPairs = [ ] for i in range ( numCellPairs ) : randCol = np . random . randint ( numColumns ) randCells = np . random . choice ( np . arange ( cellsPerColumn ) , ( 2 , ) , replace = False ) cellsPair... | Generate indices of cell pairs each pair of cells are from the same column |
10,036 | def sampleCellsAcrossColumns ( numCellPairs , cellsPerColumn , numColumns , seed = 42 ) : np . random . seed ( seed ) cellPairs = [ ] for i in range ( numCellPairs ) : randCols = np . random . choice ( np . arange ( numColumns ) , ( 2 , ) , replace = False ) randCells = np . random . choice ( np . arange ( cellsPerColu... | Generate indices of cell pairs each pair of cells are from different column |
10,037 | def subSample ( spikeTrains , numCells , totalCells , currentTS , timeWindow ) : indices = np . random . permutation ( np . arange ( totalCells ) ) if currentTS > 0 and currentTS < timeWindow : subSpikeTrains = np . zeros ( ( numCells , currentTS ) , dtype = "uint32" ) for i in range ( numCells ) : subSpikeTrains [ i ,... | Obtains a random sample of cells from the whole spike train matrix consisting of numCells cells from the start of simulation time up to currentTS |
10,038 | def subSampleWholeColumn ( spikeTrains , colIndices , cellsPerColumn , currentTS , timeWindow ) : numColumns = np . shape ( colIndices ) [ 0 ] numCells = numColumns * cellsPerColumn if currentTS > 0 and currentTS < timeWindow : subSpikeTrains = np . zeros ( ( numCells , currentTS ) , dtype = "uint32" ) for i in range (... | Obtains subsample from matrix of spike trains by considering the cells in columns specified by colIndices . Thus it returns a matrix of spike trains of cells within the same column . |
10,039 | def computeEntropy ( spikeTrains ) : MIN_ACTIVATION_PROB = 0.000001 activationProb = np . mean ( spikeTrains , 1 ) activationProb [ activationProb < MIN_ACTIVATION_PROB ] = MIN_ACTIVATION_PROB activationProb = activationProb / np . sum ( activationProb ) entropy = - np . dot ( activationProb , np . log2 ( activationPro... | Estimates entropy in spike trains . |
10,040 | def computeISI ( spikeTrains ) : zeroCount = 0 isi = [ ] cells = 0 for i in range ( np . shape ( spikeTrains ) [ 0 ] ) : if cells > 0 and cells % 250 == 0 : print str ( cells ) + " cells processed" for j in range ( np . shape ( spikeTrains ) [ 1 ] ) : if spikeTrains [ i ] [ j ] == 0 : zeroCount += 1 elif zeroCount > 0 ... | Estimates the inter - spike interval from a spike train matrix . |
10,041 | def poissonSpikeGenerator ( firingRate , nBins , nTrials ) : dt = 0.001 poissonSpikeTrain = np . zeros ( ( nTrials , nBins ) , dtype = "uint32" ) for i in range ( nTrials ) : for j in range ( int ( nBins ) ) : if random . random ( ) < firingRate * dt : poissonSpikeTrain [ i , j ] = 1 return poissonSpikeTrain | Generates a Poisson spike train . |
10,042 | def raster ( event_times_list , color = 'k' ) : ax = plt . gca ( ) for ith , trial in enumerate ( event_times_list ) : plt . vlines ( trial , ith + .5 , ith + 1.5 , color = color ) plt . ylim ( .5 , len ( event_times_list ) + .5 ) return ax | Creates a raster from spike trains . |
10,043 | def rasterPlot ( spikeTrain , model ) : nTrials = np . shape ( spikeTrain ) [ 0 ] spikes = [ ] for i in range ( nTrials ) : spikes . append ( spikeTrain [ i ] . nonzero ( ) [ 0 ] . tolist ( ) ) plt . figure ( ) ax = raster ( spikes ) plt . xlabel ( 'Time' ) plt . ylabel ( 'Neuron' ) plt . savefig ( "raster" + str ( mod... | Plots raster and saves figure in working directory |
10,044 | def saveTM ( tm ) : proto1 = TemporalMemoryProto_capnp . TemporalMemoryProto . new_message ( ) tm . write ( proto1 ) with open ( 'tm.nta' , 'wb' ) as f : proto1 . write ( f ) | Saves the temporal memory and the sequences generated for its training . |
10,045 | def mapLabelRefs ( dataDict ) : labelRefs = [ label for label in set ( itertools . chain . from_iterable ( [ x [ 1 ] for x in dataDict . values ( ) ] ) ) ] for recordNumber , data in dataDict . iteritems ( ) : dataDict [ recordNumber ] = ( data [ 0 ] , numpy . array ( [ labelRefs . index ( label ) for label in data [ 1... | Replace the label strings in dataDict with corresponding ints . |
10,046 | def bucketCSVs ( csvFile , bucketIdx = 2 ) : try : with open ( csvFile , "rU" ) as f : reader = csv . reader ( f ) headers = next ( reader , None ) dataDict = OrderedDict ( ) for lineNumber , line in enumerate ( reader ) : if line [ bucketIdx ] in dataDict : dataDict [ line [ bucketIdx ] ] . append ( line ) else : data... | Write the individual buckets in csvFile to their own CSV files . |
10,047 | def readDir ( dirPath , numLabels , modify = False ) : samplesDict = defaultdict ( list ) for _ , _ , files in os . walk ( dirPath ) : for f in files : basename , extension = os . path . splitext ( os . path . basename ( f ) ) if "." in basename and extension == ".csv" : category = basename . split ( "." ) [ - 1 ] if m... | Reads in data from a directory of CSV files ; assumes the directory only contains CSV files . |
10,048 | def writeCSV ( data , headers , csvFile ) : with open ( csvFile , "wb" ) as f : writer = csv . writer ( f , delimiter = "," ) writer . writerow ( headers ) writer . writerows ( data ) | Write data with column headers to a CSV . |
10,049 | def writeFromDict ( dataDict , headers , csvFile ) : with open ( csvFile , "wb" ) as f : writer = csv . writer ( f , delimiter = "," ) writer . writerow ( headers ) for row in sorted ( dataDict . keys ( ) ) : writer . writerow ( dataDict [ row ] ) | Write dictionary to a CSV where keys are row numbers and values are a list . |
10,050 | def readDataAndReshuffle ( args , categoriesInOrderOfInterest = None ) : dataDict = readCSV ( args . dataPath , 1 ) labelRefs , dataDict = mapLabelRefs ( dataDict ) if "numLabels" in args : numLabels = args . numLabels else : numLabels = len ( labelRefs ) if categoriesInOrderOfInterest is None : categoriesInOrderOfInte... | Read data file specified in args optionally reshuffle categories print out some statistics and return various data structures . This routine is pretty specific and only used in some simple test scripts . |
10,051 | def createModel ( modelName , ** kwargs ) : if modelName not in TemporalMemoryTypes . getTypes ( ) : raise RuntimeError ( "Unknown model type: " + modelName ) return getattr ( TemporalMemoryTypes , modelName ) ( ** kwargs ) | Return a classification model of the appropriate type . The model could be any supported subclass of ClassficationModel based on modelName . |
10,052 | def getConstructorArguments ( modelName ) : if modelName not in TemporalMemoryTypes . getTypes ( ) : raise RuntimeError ( "Unknown model type: " + modelName ) argspec = inspect . getargspec ( getattr ( TemporalMemoryTypes , modelName ) . __init__ ) return ( argspec . args [ 1 : ] , argspec . defaults ) | Return constructor arguments and associated default values for the given model type . |
10,053 | def getTypes ( cls ) : for attrName in dir ( cls ) : attrValue = getattr ( cls , attrName ) if ( isinstance ( attrValue , type ) ) : yield attrName | Get sequence of acceptable model types . Iterates through class attributes and separates the user - defined enumerations from the default attributes implicit to Python classes . i . e . this function returns the names of the attributes explicitly defined above . |
10,054 | def initialize_dendrites ( self ) : self . dendrites = SM32 ( ) self . dendrites . reshape ( self . dim , self . num_dendrites ) for row in range ( self . num_dendrites ) : synapses = numpy . random . choice ( self . dim , self . dendrite_length , replace = False ) for synapse in synapses : self . dendrites [ synapse ,... | Initialize all the dendrites of the neuron to a set of random connections |
10,055 | def calculate_activation ( self , datapoint ) : activations = datapoint * self . dendrites activations = self . nonlinearity ( activations ) return activations . sum ( ) | Only for a single datapoint |
10,056 | def HTM_style_initialize_on_data ( self , data , labels ) : current_dendrite = 0 self . dendrites = SM32 ( ) self . dendrites . reshape ( self . dim , self . num_dendrites ) data = copy . deepcopy ( data ) data . deleteRows ( [ i for i , v in enumerate ( labels ) if v != 1 ] ) if data . nRows ( ) > self . num_dendrites... | Uses a style of initialization inspired by the temporal memory . When a new positive example is found a dendrite is chosen and a number of synapses are created to the example . |
10,057 | def HTM_style_train_on_datapoint ( self , datapoint , label ) : activations = datapoint * self . dendrites self . nonlinearity ( activations ) activation = numpy . sign ( activations . sum ( ) ) if label >= 1 and activation >= 0.5 : strongest_branch = activations . rowMax ( 0 ) [ 0 ] datapoint . transpose ( ) inc_vecto... | Run a version of permanence - based training on a datapoint . Due to the fixed dendrite count and dendrite length we are forced to more efficiently use each synapse deleting synapses and resetting them if they are not found useful . |
10,058 | def initialize ( self ) : autoArgs = { name : getattr ( self , name ) for name in self . _poolerArgNames } autoArgs [ "inputDimensions" ] = [ self . _inputWidth ] autoArgs [ "columnDimensions" ] = [ self . _columnCount ] autoArgs [ "potentialRadius" ] = self . _inputWidth autoArgs [ "historyLength" ] = self . _historyL... | Initialize the self . _poolerClass |
10,059 | def compute ( self , inputs , outputs ) : resetSignal = False if 'resetIn' in inputs : if len ( inputs [ 'resetIn' ] ) != 1 : raise Exception ( "resetIn has invalid length" ) if inputs [ 'resetIn' ] [ 0 ] != 0 : resetSignal = True outputs [ "mostActiveCells" ] [ : ] = numpy . zeros ( self . _columnCount , dtype = GetNT... | Run one iteration of TemporalPoolerRegion s compute . |
10,060 | def getSpec ( cls ) : spec = cls . getBaseSpec ( ) p , o = _getAdditionalSpecs ( ) spec [ "parameters" ] . update ( p ) spec [ "parameters" ] . update ( o ) return spec | Return the Spec for TemporalPoolerRegion . |
10,061 | def computeCapacity ( results , threshold ) : closestBelow = None closestAbove = None for numObjects , accuracy in sorted ( results ) : if accuracy >= threshold : if closestAbove is None or closestAbove [ 0 ] < numObjects : closestAbove = ( numObjects , accuracy ) closestBelow = None else : if closestBelow is None : cl... | Returns largest number of objects with accuracy above threshold . |
10,062 | def reset ( self ) : self . activeCells = np . empty ( 0 , dtype = "uint32" ) self . activeDeltaSegments = np . empty ( 0 , dtype = "uint32" ) self . activeFeatureLocationSegments = np . empty ( 0 , dtype = "uint32" ) | Deactivate all cells . |
10,063 | def compute ( self , deltaLocation = ( ) , newLocation = ( ) , featureLocationInput = ( ) , featureLocationGrowthCandidates = ( ) , learn = True ) : prevActiveCells = self . activeCells self . activeDeltaSegments = np . where ( ( self . internalConnections . computeActivity ( prevActiveCells , self . connectedPermanenc... | Run one time step of the Location Memory algorithm . |
10,064 | def initialize ( self ) : if self . _modules is None : self . _modules = [ ] for i in xrange ( self . moduleCount ) : self . _modules . append ( ThresholdedGaussian2DLocationModule ( cellsPerAxis = self . cellsPerAxis , scale = self . scale [ i ] , orientation = self . orientation [ i ] , anchorInputSize = self . ancho... | Initialize grid cell modules |
10,065 | def compute ( self , inputs , outputs ) : if inputs . get ( "resetIn" , False ) : self . reset ( ) if self . learningMode : self . activateRandomLocation ( ) outputs [ "activeCells" ] [ : ] = 0 outputs [ "learnableCells" ] [ : ] = 0 outputs [ "sensoryAssociatedCells" ] [ : ] = 0 return displacement = inputs . get ( "di... | Compute the location based on the displacement and anchorInput by first applying the movement if displacement is present in the input array and then applying the sensation if anchorInput is present in the input array . The anchorGrowthCandidates input array is used during learning |
10,066 | def setParameter ( self , parameterName , index , parameterValue ) : spec = self . getSpec ( ) if parameterName not in spec [ 'parameters' ] : raise Exception ( "Unknown parameter: " + parameterName ) setattr ( self , parameterName , parameterValue ) | Set the value of a Spec parameter . |
10,067 | def getOutputElementCount ( self , name ) : if name in [ "activeCells" , "learnableCells" , "sensoryAssociatedCells" ] : return self . cellCount * self . moduleCount else : raise Exception ( "Invalid output name specified: " + name ) | Returns the size of the output array |
10,068 | def reset ( self ) : self . L4 . reset ( ) for module in self . L6aModules : module . reset ( ) | Clear all cell activity . |
10,069 | def getLocationRepresentation ( self ) : activeCells = np . array ( [ ] , dtype = "uint32" ) totalPrevCells = 0 for module in self . L6aModules : activeCells = np . append ( activeCells , module . getActiveCells ( ) + totalPrevCells ) totalPrevCells += module . numberOfCells ( ) return activeCells | Get the full population representation of the location layer . |
10,070 | def getLearnableLocationRepresentation ( self ) : learnableCells = np . array ( [ ] , dtype = "uint32" ) totalPrevCells = 0 for module in self . L6aModules : learnableCells = np . append ( learnableCells , module . getLearnableCells ( ) + totalPrevCells ) totalPrevCells += module . numberOfCells ( ) return learnableCel... | Get the cells in the location layer that should be associated with the sensory input layer representation . In some models this is identical to the active cells . In others it s a subset . |
10,071 | def learnObject ( self , objectDescription , randomLocation = False , useNoise = False , noisyTrainingTime = 1 ) : self . reset ( ) self . column . activateRandomLocation ( ) locationsAreUnique = True if randomLocation or useNoise : numIters = noisyTrainingTime else : numIters = 1 for i in xrange ( numIters ) : for iFe... | Train the network to recognize the specified object . Move the sensor to one of its features and activate a random location representation in the location layer . Move the sensor over the object updating the location representation through path integration . At each point on the object form reciprocal connections betwe... |
10,072 | def _move ( self , feature , randomLocation = False , useNoise = True ) : if randomLocation : locationOnObject = { "top" : feature [ "top" ] + np . random . rand ( ) * feature [ "height" ] , "left" : feature [ "left" ] + np . random . rand ( ) * feature [ "width" ] , } else : locationOnObject = { "top" : feature [ "top... | Move the sensor to the center of the specified feature . If the sensor is currently at another location send the displacement into the cortical column so that it can perform path integration . |
10,073 | def _sense ( self , featureSDR , learn , waitForSettle ) : for monitor in self . monitors . values ( ) : monitor . beforeSense ( featureSDR ) iteration = 0 prevCellActivity = None while True : ( inputParams , locationParams ) = self . column . sensoryCompute ( featureSDR , learn ) if waitForSettle : cellActivity = ( se... | Send the sensory input into the network . Optionally send it multiple times until the network settles . |
10,074 | def createObjectMachine ( machineType , ** kwargs ) : if machineType not in ObjectMachineTypes . getTypes ( ) : raise RuntimeError ( "Unknown model type: " + machineType ) return getattr ( ObjectMachineTypes , machineType ) ( ** kwargs ) | Return an object machine of the appropriate type . |
10,075 | def getEntropies ( m ) : entropy = 0.0 max_entropy = 0.0 for module in m . children ( ) : e , m = getEntropies ( module ) entropy += e max_entropy += m e , m = getEntropy ( m ) entropy += e max_entropy += m return entropy , max_entropy | Recursively get the current and max entropies from every child module |
10,076 | def updateBoostStrength ( m ) : if isinstance ( m , KWinnersBase ) : if m . training : m . boostStrength = m . boostStrength * m . boostStrengthFactor | Function used to update KWinner modules boost strength after each epoch . |
10,077 | def updateBoostStrength ( self ) : if self . training : self . boostStrength = self . boostStrength * self . boostStrengthFactor | Update boost strength using given strength factor during training |
10,078 | def entropy ( self ) : if self . k < self . n : _ , entropy = binaryEntropy ( self . dutyCycle ) return entropy else : return 0 | Returns the current total entropy of this layer |
10,079 | def greedySensorPositions ( numSensors , numLocations ) : locationViewCounts = [ 0 ] * numLocations locationViewCountsBySensor = [ [ 0 ] * numLocations for _ in xrange ( numSensors ) ] placement = random . sample ( xrange ( numLocations ) , numSensors ) while True : yield tuple ( placement ) for sensor , location in en... | Returns an infinite sequence of sensor placements . |
10,080 | def initialize ( self ) : if self . _tm is None : params = { "columnCount" : self . columnCount , "basalInputSize" : self . basalInputWidth , "apicalInputSize" : self . apicalInputWidth , "cellsPerColumn" : self . cellsPerColumn , "activationThreshold" : self . activationThreshold , "initialPermanence" : self . initial... | Initialize the self . _tm if not already initialized . |
10,081 | def getOutputElementCount ( self , name ) : if name in [ "activeCells" , "predictedCells" , "predictedActiveCells" , "winnerCells" ] : return self . cellsPerColumn * self . columnCount else : raise Exception ( "Invalid output name specified: %s" % name ) | Return the number of elements for the given output . |
10,082 | def learnSequences ( self , sequences ) : sequence_order = range ( len ( sequences ) ) if self . config [ "L2Params" ] [ "onlineLearning" ] : self . _setLearningMode ( l4Learning = True , l2Learning = True ) for _ in xrange ( self . numLearningPoints ) : random . shuffle ( sequence_order ) for i in sequence_order : seq... | Learns all provided sequences . Always reset the network in between sequences . |
10,083 | def getL4PredictedActiveCells ( self ) : predictedActive = [ ] for i in xrange ( self . numColumns ) : region = self . network . regions [ "L4Column_" + str ( i ) ] predictedActive . append ( region . getOutputData ( "predictedActiveCells" ) . nonzero ( ) [ 0 ] ) return predictedActive | Returns the predicted active cells in each column in L4 . |
10,084 | def _setLearningMode ( self , l4Learning = False , l2Learning = False ) : for column in self . L4Columns : column . setParameter ( "learn" , 0 , l4Learning ) for column in self . L2Columns : column . setParameter ( "learningMode" , 0 , l2Learning ) | Sets the learning mode for L4 and L2 . |
10,085 | def printDiagnosticsAfterTraining ( exp , verbosity = 0 ) : print "Number of connected synapses per cell" l2 = exp . getAlgorithmInstance ( "L2" ) numConnectedCells = 0 connectedSynapses = 0 for c in range ( 4096 ) : cp = l2 . numberOfConnectedProximalSynapses ( [ c ] ) if cp > 0 : numConnectedCells += 1 connectedSynap... | Useful diagnostics a trained system for debugging . |
10,086 | def trainSequences ( sequences , exp , idOffset = 0 ) : for seqId in sequences : iterations = 3 * len ( sequences [ seqId ] ) for p in range ( iterations ) : s = sequences . provideObjectsToLearn ( [ seqId ] ) objectSDRs = dict ( ) objectSDRs [ seqId + idOffset ] = s [ seqId ] exp . learnObjects ( objectSDRs , reset = ... | Train the network on all the sequences |
10,087 | def trainObjects ( objects , exp , numRepeatsPerObject , experimentIdOffset = 0 ) : objectsToLearn = objects . provideObjectsToLearn ( ) objectTraversals = { } for objectId in objectsToLearn : objectTraversals [ objectId + experimentIdOffset ] = objects . randomTraversal ( objectsToLearn [ objectId ] , numRepeatsPerObj... | Train the network on all the objects by randomly traversing points on each object . We offset the id of each object to avoid confusion with any sequences that might have been learned . |
10,088 | def inferObject ( exp , objectId , objects , objectName ) : objectSensations = { } objectSensations [ 0 ] = [ ] obj = objects [ objectId ] objectCopy = [ pair for pair in obj ] random . shuffle ( objectCopy ) for pair in objectCopy : objectSensations [ 0 ] . append ( pair ) inferConfig = { "numSteps" : len ( objectSens... | Run inference on the given object . objectName is the name of this object in the experiment . |
10,089 | def createSuperimposedSensorySDRs ( sequenceSensations , objectSensations ) : assert len ( sequenceSensations ) == len ( objectSensations ) superimposedSensations = [ ] for i , objectSensation in enumerate ( objectSensations ) : newSensation = { 0 : ( objectSensation [ 0 ] [ 0 ] , sequenceSensations [ i ] [ 0 ] [ 1 ] .... | 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 . |
10,090 | def runExperimentPool ( numSequences , numFeatures , numLocations , numObjects , numWorkers = 7 , nTrials = 1 , seqLength = 10 , figure = "" , numRepetitions = 1 , synPermProximalDecL2 = [ 0.001 ] , minThresholdProximalL2 = [ 10 ] , sampleSizeProximalL2 = [ 15 ] , inputSize = [ 1024 ] , basalPredictedSegmentDecrement =... | 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 . |
10,091 | def runExperiment5A ( dirName ) : resultsFilename = os . path . join ( dirName , "sensorimotor_sequence_example.pkl" ) results = runExperiment ( { "numSequences" : 0 , "seqLength" : 10 , "numFeatures" : 100 , "trialNum" : 4 , "numObjects" : 50 , "numLocations" : 100 , } ) with open ( resultsFilename , "wb" ) as f : cPi... | This runs the first experiment in the section Simulations with Sensorimotor Sequences an example sensorimotor sequence . |
10,092 | def runExperiment5B ( dirName ) : resultsName = os . path . join ( dirName , "sensorimotor_batch_results_more_objects.pkl" ) numTrials = 10 featureRange = [ 10 , 50 , 100 , 150 , 500 ] objectRange = [ 110 , 130 , 200 , 300 ] locationRange = [ 100 ] runExperimentPool ( numSequences = [ 0 ] , numObjects = objectRange , n... | 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 . |
10,093 | def runExperiment6 ( dirName ) : resultsFilename = os . path . join ( dirName , "combined_results.pkl" ) results = runExperiment ( { "numSequences" : 50 , "seqLength" : 10 , "numObjects" : 50 , "numFeatures" : 500 , "trialNum" : 8 , "numLocations" : 100 , "settlingTime" : 1 , "figure" : "6" , "numRepetitions" : 30 , "b... | This runs the experiment the section Simulations with Combined Sequences an example stream containing a mixture of temporal and sensorimotor sequences . |
10,094 | def runExperimentS ( dirName ) : resultsFilename = os . path . join ( dirName , "superimposed_training.pkl" ) results = runExperiment ( { "numSequences" : 50 , "numObjects" : 50 , "seqLength" : 10 , "numFeatures" : 100 , "trialNum" : 8 , "numLocations" : 100 , "numRepetitions" : 30 , "sampleSizeProximalL2" : 15 , "minT... | This runs an experiment where the network is trained on stream containing a mixture of temporal and sensorimotor sequences . |
10,095 | def runExperimentSP ( dirName ) : resultsFilename = os . path . join ( dirName , "superimposed_128mcs.pkl" ) numTrials = 10 featureRange = [ 1000 ] objectRange = [ 50 ] runExperimentPool ( numSequences = objectRange , numObjects = objectRange , numFeatures = featureRange , numLocations = [ 100 ] , nTrials = numTrials ,... | This runs a pool of experiments where the network is trained on stream containing a mixture of temporal and sensorimotor sequences . |
10,096 | def reset ( self , ) : 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 .... | Reset the state of all cells . This is normally used between sequences while training . All internal states are reset to 0 . |
10,097 | def printComputeEnd ( self , output , learn = False ) : 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:... | Called at the end of inference to print out various diagnostic information based on the current verbosity level . |
10,098 | def computePhase2 ( self , doLearn = False ) : for c in xrange ( self . numberOfCols ) : buPredicted = False for i in xrange ( self . cellsPerColumn ) : maxConfidence = 0 for s in self . cells [ c ] [ i ] : if self . isSegmentActive ( s , self . activeState [ 't' ] ) : self . predictedState [ 't' ] [ c , i ] = 1 buPred... | 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 . |
10,099 | def columnConfidences ( self , cellConfidences = None ) : if cellConfidences is None : cellConfidences = self . confidence [ 't' ] colConfidences = cellConfidences . sum ( axis = 1 ) return colConfidences | 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 . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.