_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q252700
ModelFactory.create
validation
def create(modelConfig, logLevel=logging.ERROR): """ Create a new model instance, given a description dictionary. :param modelConfig: (dict) A dictionary describing the current model, `described here <../../quick-start/example-model-params.html>`_. :param logLevel: (int) The level of...
python
{ "resource": "" }
q252701
TemporalMemory.compute
validation
def compute(self, activeColumns, learn=True): """ Perform one time step of the Temporal Memory algorithm. This method calls :meth:`activateCells`, then calls :meth:`activateDendrites`. Using :class:`TemporalMemory` via its :meth:`compute` method ensures that you'll always be able to call :me...
python
{ "resource": "" }
q252702
TemporalMemory.activateCells
validation
def activateCells(self, activeColumns, learn=True): """ Calculate the active cells, using the current active columns and dendrite segments. Grow and reinforce synapses. :param activeColumns: (iter) A sorted list of active column indices. :param learn: (bool) If true, reinforce / punish / grow syna...
python
{ "resource": "" }
q252703
TemporalMemory.activateDendrites
validation
def activateDendrites(self, learn=True): """ Calculate dendrite segment activity, using the current active cells. :param learn: (bool) If true, segment activations will be recorded. This information is used during segment cleanup. **Pseudocode:** :: for each distal dendrite...
python
{ "resource": "" }
q252704
TemporalMemory.reset
validation
def reset(self): """ Indicates the start of a new sequence. Clears any predictions and makes sure synapses don't grow to the currently active cells in the next time step. """
python
{ "resource": "" }
q252705
TemporalMemory.activatePredictedColumn
validation
def activatePredictedColumn(self, column, columnActiveSegments, columnMatchingSegments, prevActiveCells, prevWinnerCells, learn): """ Determines which cells in a predicted column should be added to winner cells list, and learns on the segments that...
python
{ "resource": "" }
q252706
TemporalMemory.punishPredictedColumn
validation
def punishPredictedColumn(self, column, columnActiveSegments, columnMatchingSegments, prevActiveCells, prevWinnerCells): """ Punishes the Segments that incorrectly predicted a column to be active. :param column: (int) Index of bursting column. :p...
python
{ "resource": "" }
q252707
TemporalMemory._createSegment
validation
def _createSegment(cls, connections, lastUsedIterationForSegment, cell, iteration, maxSegmentsPerCell): """ Create a segment on the connections, enforcing the maxSegmentsPerCell parameter. """ # Enforce maxSegmentsPerCell. while connections.numSegments(cell) >= maxSegmentsPe...
python
{ "resource": "" }
q252708
TemporalMemory._destroyMinPermanenceSynapses
validation
def _destroyMinPermanenceSynapses(cls, connections, random, segment, nDestroy, excludeCells): """ Destroy nDestroy synapses on the specified segment, but don't destroy synapses to the "excludeCells". """ destroyCandidates = sorted( (synapse for synapse in c...
python
{ "resource": "" }
q252709
TemporalMemory._leastUsedCell
validation
def _leastUsedCell(cls, random, cells, connections): """ Gets the cell with the smallest number of segments. Break ties randomly. :param random: (Object) Random number generator. Gets mutated. :param cells: (list) Indices of cells. :param connections: (Object) Connections instance...
python
{ "resource": "" }
q252710
TemporalMemory._growSynapses
validation
def _growSynapses(cls, connections, random, segment, nDesiredNewSynapes, prevWinnerCells, initialPermanence, maxSynapsesPerSegment): """ Creates nDesiredNewSynapes synapses on the segment passed in if possible, choosing random cells from the previous winner cells that are not already...
python
{ "resource": "" }
q252711
TemporalMemory._adaptSegment
validation
def _adaptSegment(cls, connections, segment, prevActiveCells, permanenceIncrement, permanenceDecrement): """ Updates synapses on segment. Strengthens active synapses; weakens inactive synapses. :param connections: (Object) Connections instance for the tm :param segment:...
python
{ "resource": "" }
q252712
TemporalMemory.columnForCell
validation
def columnForCell(self, cell): """ Returns the index of the column that a cell belongs to. :param cell: (int) Cell index :returns: (int) Column index
python
{ "resource": "" }
q252713
TemporalMemory.cellsForColumn
validation
def cellsForColumn(self, column): """ Returns the indices of cells that belong to a column. :param column: (int) Column index :returns: (list) Cell indices """
python
{ "resource": "" }
q252714
TemporalMemory.mapCellsToColumns
validation
def mapCellsToColumns(self, cells): """ Maps cells to the columns they belong to. :param cells: (set) Cells :returns: (dict) Mapping from columns to their cells in `cells` """ cellsForColumns =
python
{ "resource": "" }
q252715
TemporalMemory.getPredictiveCells
validation
def getPredictiveCells(self): """ Returns the indices of the predictive cells. :returns: (list) Indices of predictive cells. """ previousCell = None predictiveCells = [] for segment in self.activeSegments:
python
{ "resource": "" }
q252716
TemporalMemory.read
validation
def read(cls, proto): """ Reads deserialized data from proto object. :param proto: (DynamicStructBuilder) Proto object :returns: (:class:TemporalMemory) TemporalMemory instance """ tm = object.__new__(cls) # capnp fails to save a tuple, so proto.columnDimensions was forced to # serial...
python
{ "resource": "" }
q252717
SequenceMachine.generateFromNumbers
validation
def generateFromNumbers(self, numbers): """ Generate a sequence from a list of numbers. Note: Any `None` in the list of numbers is considered a reset. @param numbers (list) List of numbers @return (list) Generated sequence """ sequence = [] for number in numbers:
python
{ "resource": "" }
q252718
SequenceMachine.addSpatialNoise
validation
def addSpatialNoise(self, sequence, amount): """ Add spatial noise to each pattern in the sequence. @param sequence (list) Sequence @param amount (float) Amount of spatial noise @return (list) Sequence with spatial noise """ newSequence = [] for pattern in sequence:
python
{ "resource": "" }
q252719
SequenceMachine.prettyPrintSequence
validation
def prettyPrintSequence(self, sequence, verbosity=1): """ Pretty print a sequence. @param sequence (list) Sequence @param verbosity (int) Verbosity level @return (string) Pretty-printed text """ text = ""
python
{ "resource": "" }
q252720
MonitorMixinBase.mmPrettyPrintTraces
validation
def mmPrettyPrintTraces(traces, breakOnResets=None): """ Returns pretty-printed table of traces. @param traces (list) Traces to print in table @param breakOnResets (BoolsTrace) Trace of resets to break table on @return (string) Pretty-printed table of traces. """ assert len(traces) > 0, "N...
python
{ "resource": "" }
q252721
MonitorMixinBase.mmPrettyPrintMetrics
validation
def mmPrettyPrintMetrics(metrics, sigFigs=5): """ Returns pretty-printed table of metrics. @param metrics (list) Traces to print in table @param sigFigs (int) Number of significant figures to print @return (string) Pretty-printed table of metrics. """ assert len(metrics) > 0, "No metrics ...
python
{ "resource": "" }
q252722
updateAnomalyLikelihoods
validation
def updateAnomalyLikelihoods(anomalyScores, params, verbosity=0): """ Compute updated probabilities for anomalyScores using the given params. :param anomalyScores: a list of records. Each record is a list with the following three e...
python
{ "resource": "" }
q252723
AnomalyLikelihood._calcSkipRecords
validation
def _calcSkipRecords(numIngested, windowSize, learningPeriod): """Return the value of skipRecords for passing to estimateAnomalyLikelihoods If `windowSize` is very large (bigger than the amount of data) then this could just return `learningPeriod`. But when some values have fallen out of the historical...
python
{ "resource": "" }
q252724
AnomalyLikelihood.read
validation
def read(cls, proto): """ capnp deserialization method for the anomaly likelihood object :param proto: (Object) capnp proto object specified in nupic.regions.anomaly_likelihood.capnp :returns: (Object) the deserialized AnomalyLikelihood object """ # pylint: disable=W0212 ...
python
{ "resource": "" }
q252725
AnomalyLikelihood.write
validation
def write(self, proto): """ capnp serialization method for the anomaly likelihood object :param proto: (Object) capnp proto object specified in nupic.regions.anomaly_likelihood.capnp """ proto.iteration = self._iteration pHistScores = proto.init('historicalScores', len(s...
python
{ "resource": "" }
q252726
AnomalyLikelihood.anomalyProbability
validation
def anomalyProbability(self, value, anomalyScore, timestamp=None): """ Compute the probability that the current value plus anomaly score represents an anomaly given the historical distribution of anomaly scores. The closer the number is to 1, the higher the chance it is an anomaly. :param value: th...
python
{ "resource": "" }
q252727
OPFTaskDriver.replaceIterationCycle
validation
def replaceIterationCycle(self, phaseSpecs): """ Replaces the Iteration Cycle phases :param phaseSpecs: Iteration cycle description consisting of a sequence of IterationPhaseSpecXXXXX elements that are performed in the given order """
python
{ "resource": "" }
q252728
OPFTaskDriver.handleInputRecord
validation
def handleInputRecord(self, inputRecord): """ Processes the given record according to the current iteration cycle phase :param inputRecord: (object) record expected to be returned from :meth:`nupic.data.record_stream.RecordStreamIface.getNextRecord`. :returns: :class:`nupic.frameworks.opf.o...
python
{ "resource": "" }
q252729
_PhaseManager.__advancePhase
validation
def __advancePhase(self): """ Advance to the next iteration cycle phase """
python
{ "resource": "" }
q252730
_PhaseManager.handleInputRecord
validation
def handleInputRecord(self, inputRecord): """ Processes the given record according to the current phase inputRecord: record object formatted according to nupic.data.FileSource.getNext() result format. Returns: An opf_utils.ModelResult object with the inputs and inferences ...
python
{ "resource": "" }
q252731
_IterationPhase.advance
validation
def advance(self): """ Advances the iteration; Returns: True if more iterations remain; False if this is the final iteration. """ hasMore = True try:
python
{ "resource": "" }
q252732
PreviousValueModel.write
validation
def write(self, proto): """ Serialize via capnp :param proto: capnp PreviousValueModelProto message builder """ super(PreviousValueModel, self).writeBaseToProto(proto.modelBase) proto.fieldNames = self._fieldNames proto.fieldTypes = self._fieldTypes
python
{ "resource": "" }
q252733
PreviousValueModel.read
validation
def read(cls, proto): """Deserialize via capnp :param proto: capnp PreviousValueModelProto message reader :returns: new instance of PreviousValueModel deserialized from the given proto """ instance = object.__new__(cls) super(PreviousValueModel, instance).__init__(proto=proto.mod...
python
{ "resource": "" }
q252734
lscsum
validation
def lscsum(lx, epsilon=None): """ Accepts log-values as input, exponentiates them, computes the sum, then converts the sum back to log-space and returns the result. Handles underflow by rescaling so that the largest values is exactly 1.0. """ lx = numpy.asarray(lx) base = lx.max() # If the input is the...
python
{ "resource": "" }
q252735
normalize
validation
def normalize(lx): """ Accepts log-values as input, exponentiates them, normalizes and returns the result. Handles underflow by rescaling so that the largest values is exactly 1.0. """ lx = numpy.asarray(lx) base = lx.max()
python
{ "resource": "" }
q252736
ExtendedLogger.debug
validation
def debug(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'DEBUG'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.debug("Houston, we
python
{ "resource": "" }
q252737
ExtendedLogger.info
validation
def info(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'INFO'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.info("Houston, we
python
{ "resource": "" }
q252738
ExtendedLogger.warning
validation
def warning(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'WARNING'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.warning("Houston, we
python
{ "resource": "" }
q252739
ExtendedLogger.error
validation
def error(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'ERROR'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.error("Houston, we
python
{ "resource": "" }
q252740
ExtendedLogger.critical
validation
def critical(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'CRITICAL'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.critical("Houston, we
python
{ "resource": "" }
q252741
ExtendedLogger.log
validation
def log(self, level, msg, *args, **kwargs): """ Log 'msg % args' with the integer severity 'level'. To pass exception information, use the keyword argument exc_info with a true value, e.g.
python
{ "resource": "" }
q252742
_filterRecord
validation
def _filterRecord(filterList, record): """ Takes a record and returns true if record meets filter criteria, false otherwise """ for (fieldIdx, fp, params) in filterList: x = dict() x['value'] = record[fieldIdx] x['acceptValues'] = params['acceptValues']
python
{ "resource": "" }
q252743
_aggr_sum
validation
def _aggr_sum(inList): """ Returns sum of the elements in the list. Missing items are replaced with the mean value """ aggrMean = _aggr_mean(inList)
python
{ "resource": "" }
q252744
_aggr_mean
validation
def _aggr_mean(inList): """ Returns mean of non-None elements of the list """ aggrSum = 0 nonNone = 0 for elem in inList: if elem != SENTINEL_VALUE_FOR_MISSING_DATA: aggrSum +=
python
{ "resource": "" }
q252745
_aggr_mode
validation
def _aggr_mode(inList): """ Returns most common value seen in the non-None elements of the list """ valueCounts = dict() nonNone = 0 for elem in inList: if elem == SENTINEL_VALUE_FOR_MISSING_DATA: continue nonNone += 1 if elem in valueCounts: valueCounts[elem] += 1 else:
python
{ "resource": "" }
q252746
generateDataset
validation
def generateDataset(aggregationInfo, inputFilename, outputFilename=None): """Generate a dataset of aggregated values Parameters: ---------------------------------------------------------------------------- aggregationInfo: a dictionary that contains the following entries - fields: a list of pairs. Each pai...
python
{ "resource": "" }
q252747
getFilename
validation
def getFilename(aggregationInfo, inputFile): """Generate the filename for aggregated dataset The filename is based on the input filename and the aggregation period. Returns the inputFile if no aggregation required (aggregation info has all 0's) """ # Find the actual file, with an absolute path inputF...
python
{ "resource": "" }
q252748
Aggregator._getEndTime
validation
def _getEndTime(self, t): """Add the aggregation period to the input time t and return a datetime object Years and months are handled as aspecial case due to leap years and months with different number of dates. They can't be converted to a strict timedelta because a period of 3 months will have differ...
python
{ "resource": "" }
q252749
Aggregator._getFuncPtrAndParams
validation
def _getFuncPtrAndParams(self, funcName): """ Given the name of an aggregation function, returns the function pointer and param. Parameters: ------------------------------------------------------------------------ funcName: a string (name of function) or funcPtr retval: (funcPtr, param) ...
python
{ "resource": "" }
q252750
Aggregator._createAggregateRecord
validation
def _createAggregateRecord(self): """ Generate the aggregated output record Parameters: ------------------------------------------------------------------------ retval: outputRecord """ record = [] for i, (fieldIdx, aggFP, paramIdx) in enumerate(self._fields): if aggFP is None: # t...
python
{ "resource": "" }
q252751
Aggregator.next
validation
def next(self, record, curInputBookmark): """ Return the next aggregated record, if any Parameters: ------------------------------------------------------------------------ record: The input record (values only) from the input source, or None if the input has reached EOF (th...
python
{ "resource": "" }
q252752
Model.run
validation
def run(self, inputRecord): """ Run one iteration of this model. :param inputRecord: (object) A record object formatted according to :meth:`~nupic.data.record_stream.RecordStreamIface.getNextRecord` or :meth:`~nupic.data.record_stream.RecordStreamIface.getNextRecordDict` ...
python
{ "resource": "" }
q252753
Model._getModelCheckpointFilePath
validation
def _getModelCheckpointFilePath(checkpointDir): """ Return the absolute path of the model's checkpoint file. :param checkpointDir: (string)
python
{ "resource": "" }
q252754
Model.writeToCheckpoint
validation
def writeToCheckpoint(self, checkpointDir): """Serializes model using capnproto and writes data to ``checkpointDir``""" proto = self.getSchema().new_message() self.write(proto) checkpointPath = self._getModelCheckpointFilePath(checkpointDir) # Clean up old saved state, if any if os.path.exist...
python
{ "resource": "" }
q252755
Model.readFromCheckpoint
validation
def readFromCheckpoint(cls, checkpointDir): """Deserializes model from checkpointDir using capnproto""" checkpointPath = cls._getModelCheckpointFilePath(checkpointDir)
python
{ "resource": "" }
q252756
Model.writeBaseToProto
validation
def writeBaseToProto(self, proto): """Save the state maintained by the Model base class :param proto: capnp ModelProto message builder """ inferenceType = self.getInferenceType() # lower-case first letter to be compatible with capnproto enum naming inferenceType = inferenceType[:1].lower() + in...
python
{ "resource": "" }
q252757
Model.save
validation
def save(self, saveModelDir): """ Save the model in the given directory. :param saveModelDir: (string) Absolute directory path for saving the model. This directory should only be used to store a saved model. If the directory does not exist, it will be created automatically and popula...
python
{ "resource": "" }
q252758
Model._getModelPickleFilePath
validation
def _getModelPickleFilePath(saveModelDir): """ Return the absolute path of the model's pickle file. :param saveModelDir: (string) Directory of where the experiment is to be or was
python
{ "resource": "" }
q252759
runExperiment
validation
def runExperiment(args, model=None): """ Run a single OPF experiment. .. note:: The caller is responsible for initializing python logging before calling this function (e.g., import :mod:`nupic.support`; :meth:`nupic.support.initLogging`) See also: :meth:`.initExperimentPrng`. :param args: (string...
python
{ "resource": "" }
q252760
reapVarArgsCallback
validation
def reapVarArgsCallback(option, optStr, value, parser): """Used as optparse callback for reaping a variable number of option args. The option may be specified multiple times, and all the args associated with that option name will be accumulated in the order that they are encountered """ newValues = [] # Re...
python
{ "resource": "" }
q252761
_reportCommandLineUsageErrorAndExit
validation
def _reportCommandLineUsageErrorAndExit(parser, message): """Report usage error and exit program with error indication."""
python
{ "resource": "" }
q252762
_runExperimentImpl
validation
def _runExperimentImpl(options, model=None): """Creates and runs the experiment Args: options: namedtuple ParseCommandLineOptionsResult model: For testing: may pass in an existing OPF Model instance to use instead of creating a new one. Returns: reference to OPFExperiment instance that was const...
python
{ "resource": "" }
q252763
_getModelCheckpointDir
validation
def _getModelCheckpointDir(experimentDir, checkpointLabel): """Creates directory for serialization of the model checkpointLabel: Checkpoint label (string) Returns: absolute path to the serialization directory """ checkpointDir = os.path.join(getCheckpointParentDir(experimentDir),
python
{ "resource": "" }
q252764
getCheckpointParentDir
validation
def getCheckpointParentDir(experimentDir): """Get checkpoint parent dir. Returns: absolute path to the base serialization directory within which model checkpoints for this experiment are created """
python
{ "resource": "" }
q252765
_checkpointLabelFromCheckpointDir
validation
def _checkpointLabelFromCheckpointDir(checkpointDir): """Returns a checkpoint label string for the given model checkpoint directory checkpointDir: relative or absolute model
python
{ "resource": "" }
q252766
_isCheckpointDir
validation
def _isCheckpointDir(checkpointDir): """Return true iff checkpointDir appears to be a checkpoint directory.""" lastSegment = os.path.split(checkpointDir)[1]
python
{ "resource": "" }
q252767
_printAvailableCheckpoints
validation
def _printAvailableCheckpoints(experimentDir): """List available checkpoints for the specified experiment.""" checkpointParentDir = getCheckpointParentDir(experimentDir) if not os.path.exists(checkpointParentDir): print "No available checkpoints." return checkpointDirs = [x for x in os.listdir(checkpo...
python
{ "resource": "" }
q252768
_TaskRunner.run
validation
def run(self): """Runs a single experiment task""" self.__logger.debug("run(): Starting task <%s>", self.__task['taskLabel']) # Set up the task # Create our main loop-control iterator if self.__cmdOptions.privateOptions['testMode']: numIters = 10 else: numIters = self.__task['itera...
python
{ "resource": "" }
q252769
_TaskRunner._createPeriodicActivities
validation
def _createPeriodicActivities(self): """Creates and returns a list of activites for this TaskRunner instance Returns: a list of PeriodicActivityRequest elements """ # Initialize periodic activities periodicActivities = [] # Metrics reporting class MetricsReportCb(object): def __init_...
python
{ "resource": "" }
q252770
corruptVector
validation
def corruptVector(v1, noiseLevel, numActiveCols): """ Corrupts a copy of a binary vector by inverting noiseLevel percent of its bits. @param v1 (array) binary vector whose copy will be corrupted @param noiseLevel (float) amount of noise to be applied on the new vector @param numActiveCols (int) num...
python
{ "resource": "" }
q252771
showPredictions
validation
def showPredictions(): """ Shows predictions of the TM when presented with the characters A, B, C, D, X, and Y without any contextual information, that is, not embedded within a sequence. """ for k in range(6): tm.reset() print "--- " + "ABCDXY"[k] + " ---" tm.compute(set(seqT[k][:].nonzero()[0...
python
{ "resource": "" }
q252772
trainTM
validation
def trainTM(sequence, timeSteps, noiseLevel): """ Trains the TM with given sequence for a given number of time steps and level of input corruption @param sequence (array) array whose rows are the input characters @param timeSteps (int) number of time steps in which the TM will be presented with sequen...
python
{ "resource": "" }
q252773
PassThroughEncoder.closenessScores
validation
def closenessScores(self, expValues, actValues, **kwargs): """ Does a bitwise compare of the two bitmaps and returns a fractonal value between 0 and 1 of how similar they are. - ``1`` => identical - ``0`` => no overlaping bits ``kwargs`` will have the keyword "fractional", which is assumed by ...
python
{ "resource": "" }
q252774
getCallerInfo
validation
def getCallerInfo(depth=2): """Utility function to get information about function callers The information is the tuple (function/method name, filename, class) The class will be None if the caller is just a function and not an object method. :param depth: (int) how far back in the callstack to go to extract ...
python
{ "resource": "" }
q252775
title
validation
def title(s=None, additional='', stream=sys.stdout): """Utility function to display nice titles It automatically extracts the name of the function/method it is called from and you can add additional text. title() will then print the name of the function/method and the additional text surrounded by tow lines ...
python
{ "resource": "" }
q252776
getArgumentDescriptions
validation
def getArgumentDescriptions(f): """ Get the arguments, default values, and argument descriptions for a function. Parses the argument descriptions out of the function docstring, using a format something lke this: :: [junk] argument_name: description... description... description... ...
python
{ "resource": "" }
q252777
_genLoggingFilePath
validation
def _genLoggingFilePath(): """ Generate a filepath for the calling app """ appName = os.path.splitext(os.path.basename(sys.argv[0]))[0] or 'UnknownApp' appLogDir = os.path.abspath(os.path.join( os.environ['NTA_LOG_DIR'], 'numenta-logs-%s' % (os.environ['USER'],), appName))
python
{ "resource": "" }
q252778
aggregationToMonthsSeconds
validation
def aggregationToMonthsSeconds(interval): """ Return the number of months and seconds from an aggregation dict that represents a date and time. Interval is a dict that contain one or more of the following keys: 'years', 'months', 'weeks', 'days', 'hours', 'minutes', seconds', 'milliseconds', 'microseconds'...
python
{ "resource": "" }
q252779
aggregationDivide
validation
def aggregationDivide(dividend, divisor): """ Return the result from dividing two dicts that represent date and time. Both dividend and divisor are dicts that contain one or more of the following keys: 'years', 'months', 'weeks', 'days', 'hours', 'minutes', seconds', 'milliseconds', 'microseconds'. For ex...
python
{ "resource": "" }
q252780
validateOpfJsonValue
validation
def validateOpfJsonValue(value, opfJsonSchemaFilename): """ Validate a python object against an OPF json schema file :param value: target python object to validate (typically a dictionary) :param opfJsonSchemaFilename: (string) OPF json schema filename containing the json schema object. (e.g., opfTask...
python
{ "resource": "" }
q252781
initLogger
validation
def initLogger(obj): """ Helper function to create a logger object for the current object with the standard Numenta prefix. :param obj: (object) to add
python
{ "resource": "" }
q252782
matchPatterns
validation
def matchPatterns(patterns, keys): """ Returns a subset of the keys that match any of the given patterns :param patterns: (list) regular expressions to match :param keys: (list)
python
{ "resource": "" }
q252783
LogEncoder._getScaledValue
validation
def _getScaledValue(self, inpt): """ Convert the input, which is in normal space, into log space """ if inpt == SENTINEL_VALUE_FOR_MISSING_DATA: return None else: val = inpt if val < self.minval:
python
{ "resource": "" }
q252784
NetworkVisualizer.export
validation
def export(self): """ Exports a network as a networkx MultiDiGraph intermediate representation suitable for visualization. :return: networkx MultiDiGraph """ graph = nx.MultiDiGraph() # Add regions to graph as nodes, annotated by name regions = self.network.getRegions() for idx in...
python
{ "resource": "" }
q252785
bitsToString
validation
def bitsToString(arr): """Returns a string representing a numpy array of 0's and 1's""" s = array('c','.'*len(arr))
python
{ "resource": "" }
q252786
percentOverlap
validation
def percentOverlap(x1, x2, size): """ Computes the percentage of overlap between vectors x1 and x2. @param x1 (array) binary vector @param x2 (array) binary vector @param size (int) length of binary vectors @return percentOverlap (float) percentage overlap between x1 and x2 """
python
{ "resource": "" }
q252787
resetVector
validation
def resetVector(x1, x2): """ Copies the contents of vector x1 into vector x2. @param x1 (array) binary vector to be copied @param x2
python
{ "resource": "" }
q252788
runCPU
validation
def runCPU(): """Poll CPU usage, make predictions, and plot the results. Runs forever.""" # Create the model for predicting CPU usage. model = ModelFactory.create(model_params.MODEL_PARAMS) model.enableInference({'predictedField': 'cpu'}) # The shifter will align prediction and actual values. shifter = Infe...
python
{ "resource": "" }
q252789
_extractCallingMethodArgs
validation
def _extractCallingMethodArgs(): """ Returns args dictionary from the calling method """ import inspect import copy callingFrame = inspect.stack()[1][0] argNames, _, _, frameLocalVarDict = inspect.getargvalues(callingFrame) argNames.remove("self") args =
python
{ "resource": "" }
q252790
BacktrackingTMCPP._getEphemeralMembers
validation
def _getEphemeralMembers(self): """ List of our member variables that we don't need to be
python
{ "resource": "" }
q252791
BacktrackingTMCPP._copyAllocatedStates
validation
def _copyAllocatedStates(self): """If state is allocated in CPP, copy over the data into our numpy arrays.""" # Get learn states if we need to print them out if self.verbosity > 1 or self.retrieveLearningStates: (activeT, activeT1, predT, predT1) = self.cells4.getLearnStates() self.lrnActiveSta...
python
{ "resource": "" }
q252792
BacktrackingTMCPP._setStatePointers
validation
def _setStatePointers(self): """If we are having CPP use numpy-allocated buffers, set these buffer pointers. This is a relatively fast operation and, for safety, should be done before every call to the cells4 compute methods. This protects us in situations where code
python
{ "resource": "" }
q252793
BacktrackingTMCPP._slowIsSegmentActive
validation
def _slowIsSegmentActive(self, seg, timeStep): """ A segment is active if it has >= activationThreshold connected synapses that are active due to infActiveState. """ numSyn = seg.size() numActiveSyns = 0 for synIdx in xrange(numSyn): if seg.getPermanence(synIdx) < self.connectedPerm:...
python
{ "resource": "" }
q252794
RandomDistributedScalarEncoder.mapBucketIndexToNonZeroBits
validation
def mapBucketIndexToNonZeroBits(self, index): """ Given a bucket index, return the list of non-zero bits. If the bucket index does not exist, it is created. If the index falls outside our range we clip it. :param index The bucket index to get non-zero bits for. @returns numpy array of indices o...
python
{ "resource": "" }
q252795
RandomDistributedScalarEncoder._createBucket
validation
def _createBucket(self, index): """ Create the given bucket index. Recursively create as many in-between bucket indices as necessary. """ if index < self.minIndex: if index == self.minIndex - 1: # Create a new representation that has exactly w-1 overlapping bits # as the min re...
python
{ "resource": "" }
q252796
RandomDistributedScalarEncoder._newRepresentation
validation
def _newRepresentation(self, index, newIndex): """ Return a new representation for newIndex that overlaps with the representation at index by exactly w-1 bits """ newRepresentation = self.bucketMap[index].copy() # Choose the bit we will replace in this representation. We need to shift # thi...
python
{ "resource": "" }
q252797
RandomDistributedScalarEncoder._newRepresentationOK
validation
def _newRepresentationOK(self, newRep, newIndex): """ Return True if this new candidate representation satisfies all our overlap rules. Since we know that neighboring representations differ by at most one bit, we compute running overlaps. """ if newRep.size != self.w: return False if (...
python
{ "resource": "" }
q252798
RandomDistributedScalarEncoder._countOverlapIndices
validation
def _countOverlapIndices(self, i, j): """ Return the overlap between bucket indices i and j """ if self.bucketMap.has_key(i) and self.bucketMap.has_key(j): iRep = self.bucketMap[i] jRep
python
{ "resource": "" }
q252799
RandomDistributedScalarEncoder._countOverlap
validation
def _countOverlap(rep1, rep2): """ Return the overlap between two representations. rep1 and rep2 are lists of non-zero indices. """
python
{ "resource": "" }