Search is not available for this dataset
text
stringlengths
75
104k
def computeSaturationLevels(outputs, outputsShape, sparseForm=False): """ Compute the saturation for a continuous level. This breaks the level into multiple regions and computes the saturation level for each region. Parameters: -------------------------------------------- outputs: output of the level....
def checkMatch(input, prediction, sparse=True, verbosity=0): """ Compares the actual input with the predicted input and returns results Parameters: ----------------------------------------------- input: The actual input prediction: the predicted input verbosity: If > 0, print debuggin...
def predictionExtent(inputs, resets, outputs, minOverlapPct=100.0): """ Computes the predictive ability of a temporal memory (TM). This routine returns a value which is the average number of time steps of prediction provided by the TM. It accepts as input the inputs, outputs, and resets provided to the TM as ...
def getCentreAndSpreadOffsets(spaceShape, spreadShape, stepSize=1): """ Generates centre offsets and spread offsets for block-mode based training regimes - star, cross, block. Parameters: ----------------------------------------------- space...
def makeCloneMap(columnsShape, outputCloningWidth, outputCloningHeight=-1): """Make a two-dimensional clone map mapping columns to clone master. This makes a map that is (numColumnsHigh, numColumnsWide) big that can be used to figure out which clone master to use for each column. Here are a few sample calls ...
def numpyStr(array, format='%f', includeIndices=False, includeZeros=True): """ Pretty print a numpy matrix using the given format string for each value. Return the string representation Parameters: ------------------------------------------------------------ array: The numpy array to print. This can be ei...
def sample(self, rgen): """Generates a random sample from the discrete probability distribution and returns its value and the log of the probability of sampling that value. """ rf = rgen.uniform(0, self.sum) index = bisect.bisect(self.cdf, rf) return self.keys[index], numpy.log(self.pmf[index])
def logProbability(self, distn): """Form of distribution must be an array of counts in order of self.keys.""" x = numpy.asarray(distn) n = x.sum() return (logFactorial(n) - numpy.sum([logFactorial(k) for k in x]) + numpy.sum(x * numpy.log(self.dist.pmf)))
def sample(self, rgen): """Generates a random sample from the Poisson probability distribution and returns its value and the log of the probability of sampling that value. """ x = rgen.poisson(self.lambdaParameter) return x, self.logDensity(x)
def createDataOutLink(network, sensorRegionName, regionName): """Link sensor region to other region so that it can pass it data.""" network.link(sensorRegionName, regionName, "UniformLink", "", srcOutput="dataOut", destInput="bottomUpIn")
def createFeedForwardLink(network, regionName1, regionName2): """Create a feed-forward link between 2 regions: regionName1 -> regionName2""" network.link(regionName1, regionName2, "UniformLink", "", srcOutput="bottomUpOut", destInput="bottomUpIn")
def createResetLink(network, sensorRegionName, regionName): """Create a reset link from a sensor region: sensorRegionName -> regionName""" network.link(sensorRegionName, regionName, "UniformLink", "", srcOutput="resetOut", destInput="resetIn")
def createSensorToClassifierLinks(network, sensorRegionName, classifierRegionName): """Create required links from a sensor region to a classifier region.""" network.link(sensorRegionName, classifierRegionName, "UniformLink", "", srcOutput="bucketIdxOut", destInput="b...
def createNetwork(dataSource): """Create and initialize a network.""" with open(_PARAMS_PATH, "r") as f: modelParams = yaml.safe_load(f)["modelParams"] # Create a network that will hold the regions. network = Network() # Add a sensor region. network.addRegion("sensor", "py.RecordSensor", '{}') # Se...
def getPredictionResults(network, clRegionName): """Get prediction results for all prediction steps.""" classifierRegion = network.regions[clRegionName] actualValues = classifierRegion.getOutputData("actualValues") probabilities = classifierRegion.getOutputData("probabilities") steps = classifierRegion.getSel...
def runHotgym(numRecords): """Run the Hot Gym example.""" # Create a data source for the network. dataSource = FileRecordStream(streamID=_INPUT_FILE_PATH) numRecords = min(numRecords, dataSource.getDataRowCount()) network = createNetwork(dataSource) # Set predicted field network.regions["sensor"].setPar...
def _loadDummyModelParameters(self, params): """ Loads all the parameters for this dummy model. For any paramters specified as lists, read the appropriate value for this model using the model index """ for key, value in params.iteritems(): if type(value) == list: index = self.modelIndex %...
def _computModelDelay(self): """ Computes the amount of time (if any) to delay the run of this model. This can be determined by two mutually exclusive parameters: delay and sleepModelRange. 'delay' specifies the number of seconds a model should be delayed. If a list is specified, the appropriate am...
def _getMetrics(self): """ Protected function that can be overridden by subclasses. Its main purpose is to allow the the OPFDummyModelRunner to override this with deterministic values Returns: All the metrics being computed for this model """ metric = None if self.metrics is not None: ...
def run(self): """ Runs the given OPF task against the given Model instance """ self._logger.debug("Starting Dummy Model: modelID=%s;" % (self._modelID)) # ========================================================================= # Initialize periodic activities (e.g., for model result updates) # ...
def _createPredictionLogger(self): """ Creates the model's PredictionLogger object, which is an interface to write model results to a permanent storage location """ class DummyLogger: def writeRecord(self, record): pass def writeRecords(self, records, progressCB): pass def close(s...
def __shouldSysExit(self, iteration): """ Checks to see if the model should exit based on the exitAfter dummy parameter """ if self._exitAfter is None \ or iteration < self._exitAfter: return False results = self._jobsDAO.modelsGetFieldsForJob(self._jobID, ['params']) modelID...
def getDescription(self): """Returns a description of the dataset""" description = {'name':self.name, 'fields':[f.name for f in self.fields], \ 'numRecords by field':[f.numRecords for f in self.fields]} return description
def setSeed(self, seed): """Set the random seed and the numpy seed Parameters: -------------------------------------------------------------------- seed: random seed """ rand.seed(seed) np.random.seed(seed)
def addField(self, name, fieldParams, encoderParams): """Add a single field to the dataset. Parameters: ------------------------------------------------------------------- name: The user-specified name of the field fieldSpec: A list of one or more dictionaries specifying parameter...
def addMultipleFields(self, fieldsInfo): """Add multiple fields to the dataset. Parameters: ------------------------------------------------------------------- fieldsInfo: A list of dictionaries, containing a field name, specs for the data classes and encoder params for the c...
def defineField(self, name, encoderParams=None): """Initialize field using relevant encoder parameters. Parameters: ------------------------------------------------------------------- name: Field name encoderParams: Parameters for the encoder. Returns the index of the fie...
def setFlag(self, index, flag): """Set flag for field at index. Flags are special characters such as 'S' for sequence or 'T' for timestamp. Parameters: -------------------------------------------------------------------- index: index of field whose flag is being set flag: ...
def generateRecord(self, record): """Generate a record. Each value is stored in its respective field. Parameters: -------------------------------------------------------------------- record: A 1-D array containing as many values as the number of fields fields: An object of the class fiel...
def generateRecords(self, records): """Generate multiple records. Refer to definition for generateRecord""" if self.verbosity>0: print 'Generating', len(records), 'records...' for record in records: self.generateRecord(record)
def getRecord(self, n=None): """Returns the nth record""" if n is None: assert len(self.fields)>0 n = self.fields[0].numRecords-1 assert (all(field.numRecords>n for field in self.fields)) record = [field.values[n] for field in self.fields] return record
def getAllRecords(self): """Returns all the records""" values=[] numRecords = self.fields[0].numRecords assert (all(field.numRecords==numRecords for field in self.fields)) for x in range(numRecords): values.append(self.getRecord(x)) return values
def encodeRecord(self, record, toBeAdded=True): """Encode a record as a sparse distributed representation Parameters: -------------------------------------------------------------------- record: Record to be encoded toBeAdded: Whether the encodings corresponding to the record are added to...
def encodeAllRecords(self, records=None, toBeAdded=True): """Encodes a list of records. Parameters: -------------------------------------------------------------------- records: One or more records. (i,j)th element of this 2D array specifies the value at field j of record i. ...
def addValueToField(self, i, value=None): """Add 'value' to the field i. Parameters: -------------------------------------------------------------------- value: value to be added i: value is added to field i """ assert(len(self.fields)>i) if value is None: value = ...
def addValuesToField(self, i, numValues): """Add values to the field i.""" assert(len(self.fields)>i) values = [self.addValueToField(i) for n in range(numValues)] return values
def getSDRforValue(self, i, j): """Returns the sdr for jth value at column i""" assert len(self.fields)>i assert self.fields[i].numRecords>j encoding = self.fields[i].encodings[j] return encoding
def getZeroedOutEncoding(self, n): """Returns the nth encoding with the predictedField zeroed out""" assert all(field.numRecords>n for field in self.fields) encoding = np.concatenate([field.encoder.encode(SENTINEL_VALUE_FOR_MISSING_DATA)\ if field.isPredictedField else field.encodings[n] for field...
def getTotaln(self): """Returns the cumulative n for all the fields in the dataset""" n = sum([field.n for field in self.fields]) return n
def getTotalw(self): """Returns the cumulative w for all the fields in the dataset""" w = sum([field.w for field in self.fields]) return w
def getEncoding(self, n): """Returns the nth encoding""" assert (all(field.numEncodings>n for field in self.fields)) encoding = np.concatenate([field.encodings[n] for field in self.fields]) return encoding
def getAllEncodings(self): """Returns encodings for all the records""" numEncodings=self.fields[0].numEncodings assert (all(field.numEncodings==numEncodings for field in self.fields)) encodings = [self.getEncoding(index) for index in range(numEncodings)] return encodings
def saveRecords(self, path='myOutput'): """Export all the records into a csv file in numenta format. Example header format: fieldName1 fieldName2 fieldName3 date string float T S Parameters: -----------------------------------------------------------------...
def removeAllRecords(self): """Deletes all the values in the dataset""" for field in self.fields: field.encodings, field.values=[], [] field.numRecords, field.numEncodings= (0, 0)
def encodeValue(self, value, toBeAdded=True): """Value is encoded as a sdr using the encoding parameters of the Field""" encodedValue = np.array(self.encoder.encode(value), dtype=realDType) if toBeAdded: self.encodings.append(encodedValue) self.numEncodings+=1 return encodedValue
def _setTypes(self, encoderSpec): """Set up the dataTypes and initialize encoders""" if self.encoderType is None: if self.dataType in ['int','float']: self.encoderType='adaptiveScalar' elif self.dataType=='string': self.encoderType='category' elif self.dataType in ['date', 'da...
def _initializeEncoders(self, encoderSpec): """ Initialize the encoders""" #Initializing scalar encoder if self.encoderType in ['adaptiveScalar', 'scalar']: if 'minval' in encoderSpec: self.minval = encoderSpec.pop('minval') else: self.minval=None if 'maxval' in encoderSpec: ...
def getScalars(self, input): """ See method description in base.py """ if input == SENTINEL_VALUE_FOR_MISSING_DATA: return numpy.array([None]) else: return numpy.array([self.categoryToIndex.get(input, 0)])
def getBucketIndices(self, input): """ See method description in base.py """ # Get the bucket index from the underlying scalar encoder if input == SENTINEL_VALUE_FOR_MISSING_DATA: return [None] else: return self.encoder.getBucketIndices(self.categoryToIndex.get(input, 0))
def decode(self, encoded, parentFieldName=''): """ See the function description in base.py """ # Get the scalar values from the underlying scalar encoder (fieldsDict, fieldNames) = self.encoder.decode(encoded) if len(fieldsDict) == 0: return (fieldsDict, fieldNames) # Expect only 1 field...
def closenessScores(self, expValues, actValues, fractional=True,): """ See the function description in base.py kwargs will have the keyword "fractional", which is ignored by this encoder """ expValue = expValues[0] actValue = actValues[0] if expValue == actValue: closeness = 1.0 els...
def getBucketValues(self): """ See the function description in base.py """ if self._bucketValues is None: numBuckets = len(self.encoder.getBucketValues()) self._bucketValues = [] for bucketIndex in range(numBuckets): self._bucketValues.append(self.getBucketInfo([bucketIndex])[0].value...
def getBucketInfo(self, buckets): """ See the function description in base.py """ # For the category encoder, the bucket index is the category index bucketInfo = self.encoder.getBucketInfo(buckets)[0] categoryIndex = int(round(bucketInfo.value)) category = self.indexToCategory[categoryIndex] ...
def topDownCompute(self, encoded): """ See the function description in base.py """ encoderResult = self.encoder.topDownCompute(encoded)[0] value = encoderResult.value categoryIndex = int(round(value)) category = self.indexToCategory[categoryIndex] return EncoderResult(value=category, scala...
def loadExperiment(path): """Loads the experiment description file from the path. :param path: (string) The path to a directory containing a description.py file or the file itself. :returns: (config, control) """ if not os.path.isdir(path): path = os.path.dirname(path) descriptionPyModule = lo...
def loadExperimentDescriptionScriptFromDir(experimentDir): """ Loads the experiment description python script from the given experiment directory. :param experimentDir: (string) experiment directory path :returns: module of the loaded experiment description scripts """ descriptionScriptPath = os.pa...
def getExperimentDescriptionInterfaceFromModule(module): """ :param module: imported description.py module :returns: (:class:`nupic.frameworks.opf.exp_description_api.DescriptionIface`) represents the experiment description """ result = module.descriptionInterface assert isinstance(result, exp_...
def _loadDescriptionFile(descriptionPyPath): """Loads a description file and returns it as a module. descriptionPyPath: path of description.py file to load """ global g_descriptionImportCount if not os.path.isfile(descriptionPyPath): raise RuntimeError(("Experiment description file %s does not exist or ...
def update(self, modelID, modelParams, modelParamsHash, metricResult, completed, completionReason, matured, numRecords): """ Insert a new entry or update an existing one. If this is an update of an existing entry, then modelParams will be None Parameters: ----------------------------------...
def getModelIDFromParamsHash(self, paramsHash): """ Return the modelID of the model with the given paramsHash, or None if not found. Parameters: --------------------------------------------------------------------- paramsHash: paramsHash to look for retval: modelId, or None if not found ...
def numModels(self, swarmId=None, includeHidden=False): """Return the total # of models we have in our database (if swarmId is None) or in a specific swarm. Parameters: --------------------------------------------------------------------- swarmId: A string representation of the sorted list o...
def bestModelIdAndErrScore(self, swarmId=None, genIdx=None): """Return the model ID of the model with the best result so far and it's score on the optimize metric. If swarm is None, then it returns the global best, otherwise it returns the best for the given swarm for all generatons up to and including ...
def getParticleInfo(self, modelId): """Return particle info for a specific modelId. Parameters: --------------------------------------------------------------------- modelId: which model Id retval: (particleState, modelId, errScore, completed, matured) """ entry = self._allResults[self._...
def getParticleInfos(self, swarmId=None, genIdx=None, completed=None, matured=None, lastDescendent=False): """Return a list of particleStates for all particles we know about in the given swarm, their model Ids, and metric results. Parameters: -------------------------------------...
def getOrphanParticleInfos(self, swarmId, genIdx): """Return a list of particleStates for all particles in the given swarm generation that have been orphaned. Parameters: --------------------------------------------------------------------- swarmId: A string representation of the sorted list of en...
def getMaturedSwarmGenerations(self): """Return a list of swarm generations that have completed and the best (minimal) errScore seen for each of them. Parameters: --------------------------------------------------------------------- retval: list of tuples. Each tuple is of the form: ...
def firstNonFullGeneration(self, swarmId, minNumParticles): """ Return the generation index of the first generation in the given swarm that does not have numParticles particles in it, either still in the running state or completed. This does not include orphaned particles. Parameters: -------------...
def getResultsPerChoice(self, swarmId, maxGenIdx, varName): """ Return a dict of the errors obtained on models that were run with each value from a PermuteChoice variable. For example, if a PermuteChoice variable has the following choices: ['a', 'b', 'c'] The dict will have 3 elements. The keys ...
def _getStreamDef(self, modelDescription): """ Generate stream definition based on """ #-------------------------------------------------------------------------- # Generate the string containing the aggregation settings. aggregationPeriod = { 'days': 0, 'hours': 0, 'micr...
def close(self): """Deletes temporary system objects/files. """ if self._tempDir is not None and os.path.isdir(self._tempDir): self.logger.debug("Removing temporary directory %r", self._tempDir) shutil.rmtree(self._tempDir) self._tempDir = None return
def _readPermutationsFile(self, filename, modelDescription): """ Read the permutations file and initialize the following member variables: _predictedField: field name of the field we are trying to predict _permutations: Dict containing the full permutations dictionary. _flatten...
def _checkForOrphanedModels (self): """If there are any models that haven't been updated in a while, consider them dead, and mark them as hidden in our resultsDB. We also change the paramsHash and particleHash of orphaned models so that we can re-generate that particle and/or model again if we desire. ...
def _hsStatePeriodicUpdate(self, exhaustedSwarmId=None): """ Periodically, check to see if we should remove a certain field combination from evaluation (because it is doing so poorly) or move on to the next sprint (add in more fields). This method is called from _getCandidateParticleAndSwarm(), whi...
def _getCandidateParticleAndSwarm (self, exhaustedSwarmId=None): """Find or create a candidate particle to produce a new model. At any one time, there is an active set of swarms in the current sprint, where each swarm in the sprint represents a particular combination of fields. Ideally, we should try t...
def _okToExit(self): """Test if it's OK to exit this worker. This is only called when we run out of prospective new models to evaluate. This method sees if all models have matured yet. If not, it will sleep for a bit and return False. This will indicate to the hypersearch worker that we should keep runn...
def createModels(self, numModels=1): """Create one or more new models for evaluation. These should NOT be models that we already know are in progress (i.e. those that have been sent to us via recordModelProgress). We return a list of models to the caller (HypersearchWorker) and if one can be successfull...
def recordModelProgress(self, modelID, modelParams, modelParamsHash, results, completed, completionReason, matured, numRecords): """Record or update the results for a model. This is called by the HSW whenever it gets results info for another model, or updated results on a model that...
def runModel(self, modelID, jobID, modelParams, modelParamsHash, jobsDAO, modelCheckpointGUID): """Run the given model. This runs the model described by 'modelParams'. Periodically, it updates the results seen on the model to the model database using the databaseAO (database Access Objec...
def _escape(s): """Escape commas, tabs, newlines and dashes in a string Commas are encoded as tabs """ assert isinstance(s, str), \ "expected %s but got %s; value=%s" % (type(str), type(s), s) s = s.replace("\\", "\\\\") s = s.replace("\n", "\\n") s = s.replace("\t", "\\t") s = s.replace(",", "...
def _engineServicesRunning(): """ Return true if the engine services are running """ process = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE) stdout = process.communicate()[0] result = process.returncode if result != 0: raise RuntimeError("Unable to check for running client job manager") # ...
def runWithConfig(swarmConfig, options, outDir=None, outputLabel="default", permWorkDir=None, verbosity=1): """ Starts a swarm, given an dictionary configuration. @param swarmConfig {dict} A complete [swarm description](http://nupic.docs.numenta.org/0.7.0.dev0/guides/swarming/r...
def runWithJsonFile(expJsonFilePath, options, outputLabel, permWorkDir): """ Starts a swarm, given a path to a JSON file containing configuration. This function is meant to be used with a CLI wrapper that passes command line arguments in through the options parameter. @param expJsonFilePath {string} Path to...
def runWithPermutationsScript(permutationsFilePath, options, outputLabel, permWorkDir): """ Starts a swarm, given a path to a permutations.py script. This function is meant to be used with a CLI wrapper that passes command line arguments in through the options parameter. @pa...
def _backupFile(filePath): """Back up a file Parameters: ---------------------------------------------------------------------- retval: Filepath of the back-up """ assert os.path.exists(filePath) stampNum = 0 (prefix, suffix) = os.path.splitext(filePath) while True: backupPath = "%s.%d%s...
def _iterModels(modelIDs): """Creates an iterator that returns ModelInfo elements for the given modelIDs WARNING: The order of ModelInfo elements returned by the iterator may not match the order of the given modelIDs Parameters: ------------------------------------------------------------...
def pickupSearch(self): """Pick up the latest search from a saved jobID and monitor it to completion Parameters: ---------------------------------------------------------------------- retval: nothing """ self.__searchJob = self.loadSavedHyperSearchJob( permWorkDir=self._options["pe...
def monitorSearchJob(self): """ Parameters: ---------------------------------------------------------------------- retval: nothing """ assert self.__searchJob is not None jobID = self.__searchJob.getJobID() startTime = time.time() lastUpdateTime = datetime.now() # Moni...
def _launchWorkers(self, cmdLine, numWorkers): """ Launch worker processes to execute the given command line Parameters: ----------------------------------------------- cmdLine: The command line for each worker numWorkers: number of workers to launch """ self._workers = [] for i in ran...
def __startSearch(self): """Starts HyperSearch as a worker or runs it inline for the "dryRun" action Parameters: ---------------------------------------------------------------------- retval: the new _HyperSearchJob instance representing the HyperSearch job """ # Thi...
def generateReport(cls, options, replaceReport, hyperSearchJob, metricsKeys): """Prints all available results in the given HyperSearch job and emits model information to the permutations report csv. The job may be completed...
def loadSavedHyperSearchJob(cls, permWorkDir, outputLabel): """Instantiates a _HyperSearchJob instance from info saved in file Parameters: ---------------------------------------------------------------------- permWorkDir: Directory path for saved jobID file outputLabel: Label string for incorporat...
def __saveHyperSearchJobID(cls, permWorkDir, outputLabel, hyperSearchJob): """Saves the given _HyperSearchJob instance's jobID to file Parameters: ---------------------------------------------------------------------- permWorkDir: Directory path for saved jobID file outputLabel: Label string fo...
def __loadHyperSearchJobID(cls, permWorkDir, outputLabel): """Loads a saved jobID from file Parameters: ---------------------------------------------------------------------- permWorkDir: Directory path for saved jobID file outputLabel: Label string for incorporating into file name for saved jobI...
def __getHyperSearchJobIDFilePath(cls, permWorkDir, outputLabel): """Returns filepath where to store HyperSearch JobID Parameters: ---------------------------------------------------------------------- permWorkDir: Directory path for saved jobID file outputLabel: Label string for incorporating into...
def emit(self, modelInfo): """Emit model info to csv file Parameters: ---------------------------------------------------------------------- modelInfo: _NupicModelInfo instance retval: nothing """ # Open/init csv file, if needed if self.__csvFileObj is None: # sets up...
def finalize(self): """Close file and print report/backup csv file paths Parameters: ---------------------------------------------------------------------- retval: nothing """ if self.__csvFileObj is not None: # Done with file self.__csvFileObj.close() self.__csvFileOb...
def __openAndInitCSVFile(self, modelInfo): """ - Backs up old report csv file; - opens the report csv file in append or overwrite mode (per self.__replaceReport); - emits column fields; - sets up self.__sortedVariableNames, self.__csvFileObj, self.__backupCSVPath, and self.__reportCSVPat...
def getJobStatus(self, workers): """ Parameters: ---------------------------------------------------------------------- workers: If this job was launched outside of the nupic job engine, then this is an array of subprocess Popen instances, one for each worker retval: _NupicJo...
def queryModelIDs(self): """Queuries DB for model IDs of all currently instantiated models associated with this HyperSearch job. See also: _iterModels() Parameters: ---------------------------------------------------------------------- retval: A sequence of Nupic modelIDs """ j...
def makeSearchJobParamsDict(cls, options, forRunning=False): """Constructs a dictionary of HyperSearch parameters suitable for converting to json and passing as the params argument to ClientJobsDAO.jobInsert() Parameters: ---------------------------------------------------------------------- options...