_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q252400
IdentityRegion.getSpec
validation
def getSpec(cls): """Return the Spec for IdentityRegion. """ spec = { "description":IdentityRegion.__doc__, "singleNodeOnly":True, "inputs":{ "in":{ "description":"The input vector.", "dataType":"Real32", "count":0, "required"...
python
{ "resource": "" }
q252401
_setRandomEncoderResolution
validation
def _setRandomEncoderResolution(minResolution=0.001): """ Given model params, figure out the correct resolution for the RandomDistributed encoder. Modifies params in place. """ encoder = ( model_params.MODEL_PARAMS["modelParams"]["sensorParams"]["encoders"]["value"]
python
{ "resource": "" }
q252402
HTMPredictionModelClassifierHelper.removeLabels
validation
def removeLabels(self, start=None, end=None, labelFilter=None): """ Remove labels from each record with record ROWID in range from start to end, noninclusive of end. Removes all records if labelFilter is None, otherwise only removes the labels eqaul to labelFilter. This will recalculate all points ...
python
{ "resource": "" }
q252403
HTMPredictionModelClassifierHelper._addRecordToKNN
validation
def _addRecordToKNN(self, record): """ This method will add the record to the KNN classifier. """ classifier = self.htm_prediction_model._getAnomalyClassifier() knn = classifier.getSelf()._knn prototype_idx = classifier.getSelf().getParameter('categoryRecencyList') category = self._labelLis...
python
{ "resource": "" }
q252404
HTMPredictionModelClassifierHelper._deleteRecordsFromKNN
validation
def _deleteRecordsFromKNN(self, recordsToDelete): """ This method will remove the given records from the classifier. parameters ------------ recordsToDelete - list of records to delete from the classififier """ classifier = self.htm_prediction_model._getAnomalyClassifier() knn = classif...
python
{ "resource": "" }
q252405
HTMPredictionModelClassifierHelper._deleteRangeFromKNN
validation
def _deleteRangeFromKNN(self, start=0, end=None): """ This method will remove any stored records within the range from start to end. Noninclusive of end. parameters ------------ start - integer representing the ROWID of the start of the deletion range, end - integer representing the ROWID o...
python
{ "resource": "" }
q252406
HTMPredictionModelClassifierHelper._recomputeRecordFromKNN
validation
def _recomputeRecordFromKNN(self, record): """ return the classified labeling of record """ inputs = { "categoryIn": [None], "bottomUpIn": self._getStateAnomalyVector(record), } outputs = {"categoriesOut": numpy.zeros((1,)), "bestPrototypeIndices":numpy.zeros((1,)), ...
python
{ "resource": "" }
q252407
HTMPredictionModelClassifierHelper._constructClassificationRecord
validation
def _constructClassificationRecord(self): """ Construct a _HTMClassificationRecord based on the current state of the htm_prediction_model of this classifier. ***This will look into the internals of the model and may depend on the SP, TM, and KNNClassifier*** """ model = self.htm_prediction_...
python
{ "resource": "" }
q252408
HTMPredictionModelClassifierHelper.compute
validation
def compute(self): """ Run an iteration of this anomaly classifier """ result = self._constructClassificationRecord() # Classify this point after waiting the classification delay if result.ROWID >= self._autoDetectWaitRecords: self._updateState(result)
python
{ "resource": "" }
q252409
HTMPredictionModelClassifierHelper.setAutoDetectWaitRecords
validation
def setAutoDetectWaitRecords(self, waitRecords): """ Sets the autoDetectWaitRecords. """ if not isinstance(waitRecords, int): raise HTMPredictionModelInvalidArgument("Invalid argument type \'%s\'. WaitRecord " "must be a number." % (type(waitRecords))) if len(self.saved_states) > 0 an...
python
{ "resource": "" }
q252410
SPRegion._allocateSpatialFDR
validation
def _allocateSpatialFDR(self, rfInput): """Allocate the spatial pooler instance.""" if self._sfdr: return # Retrieve the necessary extra arguments that were handled automatically autoArgs = dict((name, getattr(self, name)) for name in self._spatialArgNames) # Instantiate...
python
{ "resource": "" }
q252411
SPRegion.compute
validation
def compute(self, inputs, outputs): """ Run one iteration, profiling it if requested. :param inputs: (dict) mapping region input names to numpy.array values :param outputs: (dict) mapping region output names to numpy.arrays that should be populated with output values by this method """ ...
python
{ "resource": "" }
q252412
SPRegion._compute
validation
def _compute(self, inputs, outputs): """ Run one iteration of SPRegion's compute """ #if self.topDownMode and (not 'topDownIn' in inputs): # raise RuntimeError("The input topDownIn must be linked in if " # "topDownMode is True") if self._sfdr is None: raise Runti...
python
{ "resource": "" }
q252413
SPRegion._initEphemerals
validation
def _initEphemerals(self): """ Initialize all ephemerals used by derived classes. """ if hasattr(self, '_sfdr') and self._sfdr: self._spatialPoolerOutput = numpy.zeros(self.columnCount, dtype=GetNTAReal()) else: self._spatialPoolerOutput = ...
python
{ "resource": "" }
q252414
FunctionSource._cacheSequenceInfoType
validation
def _cacheSequenceInfoType(self): """Figure out whether reset, sequenceId, both or neither are present in the data. Compute once instead of every time. Taken from filesource.py""" hasReset = self.resetFieldName is not None hasSequenceId = self.sequenceIdFieldName is not None if hasReset a...
python
{ "resource": "" }
q252415
_getTPClass
validation
def _getTPClass(temporalImp): """ Return the class corresponding to the given temporalImp string """ if temporalImp == 'py': return backtracking_tm.BacktrackingTM elif temporalImp == 'cpp': return backtracking_tm_cpp.BacktrackingTMCPP elif temporalImp ==
python
{ "resource": "" }
q252416
_buildArgs
validation
def _buildArgs(f, self=None, kwargs={}): """ Get the default arguments from the function and assign as instance vars. Return a list of 3-tuples with (name, description, defaultValue) for each argument to the function. Assigns all arguments to the function as instance variables of TMRegion. If the argume...
python
{ "resource": "" }
q252417
TMRegion._compute
validation
def _compute(self, inputs, outputs): """ Run one iteration of TMRegion's compute """ #if self.topDownMode and (not 'topDownIn' in inputs): # raise RuntimeError("The input topDownIn must be linked in if " # "topDownMode is True") if self._tfdr is None: raise Runtime...
python
{ "resource": "" }
q252418
TMRegion.finishLearning
validation
def finishLearning(self): """ Perform an internal optimization step that speeds up inference if we know learning will not be performed anymore. This call may, for example, remove
python
{ "resource": "" }
q252419
computeRawAnomalyScore
validation
def computeRawAnomalyScore(activeColumns, prevPredictedColumns): """Computes the raw anomaly score. The raw anomaly score is the fraction of active columns not predicted. :param activeColumns: array of active column indices :param prevPredictedColumns: array of columns indices predicted in prev step :return...
python
{ "resource": "" }
q252420
Anomaly.compute
validation
def compute(self, activeColumns, predictedColumns, inputValue=None, timestamp=None): """Compute the anomaly score as the percent of active columns not predicted. :param activeColumns: array of active column indices :param predictedColumns: array of columns indices predicted in this step ...
python
{ "resource": "" }
q252421
Plot.addGraph
validation
def addGraph(self, data, position=111, xlabel=None, ylabel=None): """ Adds a graph to the plot's figure. @param data See matplotlib.Axes.plot documentation. @param position A 3-digit number. The first two digits define a 2D grid where subplots may be added. The final digit specifies the nth gri...
python
{ "resource": "" }
q252422
Plot.addHistogram
validation
def addHistogram(self, data, position=111, xlabel=None, ylabel=None, bins=None): """ Adds a histogram to the plot's figure. @param data See matplotlib.Axes.hist documentation. @param position A 3-digit number. The first two digits define a 2D grid where subplots may be added....
python
{ "resource": "" }
q252423
Plot.add2DArray
validation
def add2DArray(self, data, position=111, xlabel=None, ylabel=None, cmap=None, aspect="auto", interpolation="nearest", name=None): """ Adds an image to the plot's figure. @param data a 2D array. See matplotlib.Axes.imshow documentation. @param position A 3-digit number. The first two digits...
python
{ "resource": "" }
q252424
Plot._addBase
validation
def _addBase(self, position, xlabel=None, ylabel=None): """ Adds a subplot to the plot's figure at specified position. @param position A 3-digit number. The first two digits define a 2D grid where subplots may be added. The final digit specifies the nth grid location for the added subpl...
python
{ "resource": "" }
q252425
getVersion
validation
def getVersion(): """ Get version from local file. """ with open(os.path.join(REPO_DIR, "VERSION"), "r") as
python
{ "resource": "" }
q252426
nupicBindingsPrereleaseInstalled
validation
def nupicBindingsPrereleaseInstalled(): """ Make an attempt to determine if a pre-release version of nupic.bindings is installed already. @return: boolean """ try: nupicDistribution = pkg_resources.get_distribution("nupic.bindings") if pkg_resources.parse_version(nupicDistribution.version).is_prere...
python
{ "resource": "" }
q252427
findRequirements
validation
def findRequirements(): """ Read the requirements.txt file and parse into requirements for setup's install_requirements option. """ requirementsPath = os.path.join(REPO_DIR, "requirements.txt") requirements = parse_file(requirementsPath) if nupicBindingsPrereleaseInstalled(): # User has a pre-release...
python
{ "resource": "" }
q252428
_indentLines
validation
def _indentLines(str, indentLevels = 1, indentFirstLine=True): """ Indent all lines in the given string str: input string indentLevels: number of levels of indentation to apply indentFirstLine: if False, the 1st line will not be indented Returns: The result string with all lines indented """...
python
{ "resource": "" }
q252429
_generateMetricSpecString
validation
def _generateMetricSpecString(inferenceElement, metric, params=None, field=None, returnLabel=False): """ Generates the string representation of a MetricSpec object, and returns the metric key associated with the metric. Parameters: ------------------...
python
{ "resource": "" }
q252430
_generateFileFromTemplates
validation
def _generateFileFromTemplates(templateFileNames, outputFilePath, replacementDict): """ Generates a file by applying token replacements to the given template file templateFileName: A list of template file names; these files are assumed to be in th...
python
{ "resource": "" }
q252431
_getPropertyValue
validation
def _getPropertyValue(schema, propertyName, options): """Checks to see if property is specified in 'options'. If not, reads the default value from the schema""" if propertyName not in options: paramsSchema = schema['properties'][propertyName]
python
{ "resource": "" }
q252432
_getExperimentDescriptionSchema
validation
def _getExperimentDescriptionSchema(): """ Returns the experiment description schema. This implementation loads it in from file experimentDescriptionSchema.json. Parameters: -------------------------------------------------------------------------- Returns: returns a dict representing the experiment des...
python
{ "resource": "" }
q252433
_generateExtraMetricSpecs
validation
def _generateExtraMetricSpecs(options): """Generates the non-default metrics specified by the expGenerator params """ _metricSpecSchema = {'properties': {}} results = [] for metric in options['metrics']: for propertyName in _metricSpecSchema['properties'].keys(): _getPropertyValue(_metricSpecSchema,...
python
{ "resource": "" }
q252434
_getPredictedField
validation
def _getPredictedField(options): """ Gets the predicted field and it's datatype from the options dictionary Returns: (predictedFieldName, predictedFieldType) """ if not options['inferenceArgs'] or \ not options['inferenceArgs']['predictedField']: return None, None predictedField = options['inferen...
python
{ "resource": "" }
q252435
_generateInferenceArgs
validation
def _generateInferenceArgs(options, tokenReplacements): """ Generates the token substitutions related to the predicted field and the supplemental arguments for prediction """ inferenceType = options['inferenceType'] optionInferenceArgs = options.get('inferenceArgs', None) resultInferenceArgs = {} predicte...
python
{ "resource": "" }
q252436
expGenerator
validation
def expGenerator(args): """ Parses, validates, and executes command-line options; On success: Performs requested operation and exits program normally On Error: Dumps exception/error info in JSON format to stdout and exits the program with non-zero status. """ # -----------------------------...
python
{ "resource": "" }
q252437
parseTimestamp
validation
def parseTimestamp(s): """ Parses a textual datetime format and return a Python datetime object. The supported format is: ``yyyy-mm-dd h:m:s.ms`` The time component is optional. - hours are 00..23 (no AM/PM) - minutes are 00..59 - seconds are 00..59 - micro-seconds are 000000..999999 :param s: (st...
python
{ "resource": "" }
q252438
parseBool
validation
def parseBool(s): """ String to boolean :param s: (string) :return: (bool) """ l = s.lower() if l in ("true", "t", "1"): return True if l in ("false", "f",
python
{ "resource": "" }
q252439
unescape
validation
def unescape(s): """ Unescapes a string that may contain commas, tabs, newlines and dashes Commas are decoded from tabs. :param s: (string) to unescape :returns: (string) unescaped string """ assert isinstance(s, basestring)
python
{ "resource": "" }
q252440
parseSdr
validation
def parseSdr(s): """ Parses a string containing only 0's and 1's and return a Python list object. :param s: (string) string to parse :returns: (list) SDR out """
python
{ "resource": "" }
q252441
parseStringList
validation
def parseStringList(s): """ Parse a string of space-separated numbers, returning a Python list.
python
{ "resource": "" }
q252442
coordinatesFromIndex
validation
def coordinatesFromIndex(index, dimensions): """ Translate an index into coordinates, using the given coordinate system. Similar to ``numpy.unravel_index``. :param index: (int) The index of the point. The coordinates are expressed as a single index by using the dimensions as a mixed radix definition...
python
{ "resource": "" }
q252443
indexFromCoordinates
validation
def indexFromCoordinates(coordinates, dimensions): """ Translate coordinates into an index, using the given coordinate system. Similar to ``numpy.ravel_multi_index``. :param coordinates: (list of ints) A list of coordinates of length ``dimensions.size()``. :param dimensions: (list of ints) The co...
python
{ "resource": "" }
q252444
neighborhood
validation
def neighborhood(centerIndex, radius, dimensions): """ Get the points in the neighborhood of a point. A point's neighborhood is the n-dimensional hypercube with sides ranging [center - radius, center + radius], inclusive. For example, if there are two dimensions and the radius is 3, the neighborhood is 6x6. ...
python
{ "resource": "" }
q252445
CoordinateEncoder._neighbors
validation
def _neighbors(coordinate, radius): """ Returns coordinates around given coordinate, within given radius. Includes given coordinate. @param coordinate (numpy.array) N-dimensional integer coordinate @param radius (int) Radius around `coordinate`
python
{ "resource": "" }
q252446
CoordinateEncoder._topWCoordinates
validation
def _topWCoordinates(cls, coordinates, w): """ Returns the top W coordinates by order. @param coordinates (numpy.array) A 2D numpy array, where each element is a coordinate @param w (int) Number of top coordinates to return @return (numpy.array) A subset of `coo...
python
{ "resource": "" }
q252447
CoordinateEncoder._hashCoordinate
validation
def _hashCoordinate(coordinate): """Hash a coordinate to a 64 bit integer.""" coordinateStr = ",".join(str(v) for v in coordinate) # Compute the hash and convert to 64 bit int.
python
{ "resource": "" }
q252448
CoordinateEncoder._orderForCoordinate
validation
def _orderForCoordinate(cls, coordinate): """ Returns the order for a coordinate. @param coordinate (numpy.array) Coordinate @return
python
{ "resource": "" }
q252449
CoordinateEncoder._bitForCoordinate
validation
def _bitForCoordinate(cls, coordinate, n): """ Maps the coordinate to a bit in the SDR. @param coordinate (numpy.array) Coordinate @param n (int) The number of available bits in the SDR
python
{ "resource": "" }
q252450
binSearch
validation
def binSearch(arr, val): """ Function for running binary search on a sorted list. :param arr: (list) a sorted list of integers to search :param val: (int) a integer to search for in the sorted array :returns: (int) the index
python
{ "resource": "" }
q252451
Connections.createSegment
validation
def createSegment(self, cell): """ Adds a new segment on a cell. :param cell: (int) Cell index :returns: (int) New segment index """ cellData = self._cells[cell] if len(self._freeFlatIdxs) > 0: flatIdx = self._freeFlatIdxs.pop() else: flatIdx = self._nextFlatIdx self...
python
{ "resource": "" }
q252452
Connections.destroySegment
validation
def destroySegment(self, segment): """ Destroys a segment. :param segment: (:class:`Segment`) representing the segment to be destroyed. """ # Remove the synapses from all data structures outside this Segment. for synapse in segment._synapses: self._removeSynapseFromPresynapticMap(synapse)...
python
{ "resource": "" }
q252453
Connections.createSynapse
validation
def createSynapse(self, segment, presynapticCell, permanence): """ Creates a new synapse on a segment. :param segment: (:class:`Segment`) Segment object for synapse to be synapsed to. :param presynapticCell: (int) Source cell index. :param permanence: (float) Initial permanence of syna...
python
{ "resource": "" }
q252454
Connections.destroySynapse
validation
def destroySynapse(self, synapse): """ Destroys a synapse. :param synapse: (:class:`Synapse`) synapse to destroy """ self._numSynapses -= 1
python
{ "resource": "" }
q252455
Connections.computeActivity
validation
def computeActivity(self, activePresynapticCells, connectedPermanence): """ Compute each segment's number of active synapses for a given input. In the returned lists, a segment's active synapse count is stored at index ``segment.flatIdx``. :param activePresynapticCells: (iter) Active cells. :p...
python
{ "resource": "" }
q252456
Connections.numSegments
validation
def numSegments(self, cell=None): """ Returns the number of segments. :param cell: (int) Optional parameter to get the number of segments on a cell. :returns: (int) Number of segments on all cells if cell is not specified, or on a specific
python
{ "resource": "" }
q252457
Connections.read
validation
def read(cls, proto): """ Reads deserialized data from proto object :param proto: (DynamicStructBuilder) Proto object :returns: (:class:`Connections`) instance """ #pylint: disable=W0212 protoCells = proto.cells connections = cls(len(protoCells)) for cellIdx, protoCell in enumera...
python
{ "resource": "" }
q252458
Configuration.getString
validation
def getString(cls, prop): """ Retrieve the requested property as a string. If property does not exist, then KeyError will be raised. :param prop: (string) name of the property :raises: KeyError :returns: (string) property value """ if cls._properties is None: cls._readStdConfigFiles()...
python
{ "resource": "" }
q252459
Configuration.getBool
validation
def getBool(cls, prop): """ Retrieve the requested property and return it as a bool. If property does not exist, then KeyError will be raised. If the property value is neither 0 nor 1, then ValueError will be raised :param prop: (string) name of the property :raises: KeyError, ValueError :retur...
python
{ "resource": "" }
q252460
Configuration.set
validation
def set(cls, prop, value): """ Set the value of the given configuration property. :param prop: (string) name of the property :param value: (object) value to set """
python
{ "resource": "" }
q252461
Configuration.dict
validation
def dict(cls): """ Return a dict containing all of the configuration properties :returns: (dict) containing all configuration properties. """ if cls._properties is None: cls._readStdConfigFiles() # Make a copy so we can update any current values obtained from environment # variables ...
python
{ "resource": "" }
q252462
Configuration.readConfigFile
validation
def readConfigFile(cls, filename, path=None): """ Parse the given XML file and store all properties it describes. :param filename: (string) name of XML file to parse (no path) :param path: (string) path of the XML file. If None, then use the standard configuration search path. """ ...
python
{ "resource": "" }
q252463
Configuration.getConfigPaths
validation
def getConfigPaths(cls): """ Return the list of paths to search for configuration files. :returns: (list) of paths """ configPaths = [] if cls._configPaths is not None: return cls._configPaths else: if 'NTA_CONF_PATH' in os.environ: configVar
python
{ "resource": "" }
q252464
addNoise
validation
def addNoise(input, noise=0.1, doForeground=True, doBackground=True): """ Add noise to the given input. Parameters: ----------------------------------------------- input: the input to add noise to noise: how much noise to add doForeground: If true, turn off some of the 1 bits in the inpu...
python
{ "resource": "" }
q252465
generateCoincMatrix
validation
def generateCoincMatrix(nCoinc=10, length=500, activity=50): """ Generate a coincidence matrix. This is used to generate random inputs to the temporal learner and to compare the predicted output against. It generates a matrix of nCoinc rows, each row has length 'length' and has a total of 'activity' bits on....
python
{ "resource": "" }
q252466
generateVectors
validation
def generateVectors(numVectors=100, length=500, activity=50): """ Generate a list of random sparse distributed vectors. This is used to generate training vectors to the spatial or temporal learner and to compare the predicted output against. It generates a list of 'numVectors' elements, each element has len...
python
{ "resource": "" }
q252467
generateSimpleSequences
validation
def generateSimpleSequences(nCoinc=10, seqLength=[5,6,7], nSeq=100): """ Generate a set of simple sequences. The elements of the sequences will be integers from 0 to 'nCoinc'-1. The length of each sequence will be randomly chosen from the 'seqLength' list. Parameters: --------------------------------------...
python
{ "resource": "" }
q252468
generateHubSequences
validation
def generateHubSequences(nCoinc=10, hubs = [2,6], seqLength=[5,6,7], nSeq=100): """ Generate a set of hub sequences. These are sequences which contain a hub element in the middle. The elements of the sequences will be integers from 0 to 'nCoinc'-1. The hub elements will only appear in the middle of each seque...
python
{ "resource": "" }
q252469
generateSimpleCoincMatrix
validation
def generateSimpleCoincMatrix(nCoinc=10, length=500, activity=50): """ Generate a non overlapping coincidence matrix. This is used to generate random inputs to the temporal learner and to compare the predicted output against. It generates a matrix of nCoinc rows, each row has length 'length' and has a total ...
python
{ "resource": "" }
q252470
generateSequences
validation
def generateSequences(nPatterns=10, patternLen=500, patternActivity=50, hubs=[2,6], seqLength=[5,6,7], nSimpleSequences=50, nHubSequences=50): """ Generate a set of simple and hub sequences. A simple sequence contains a randomly chosen set of elements from 0 to 'nCoinc-1'...
python
{ "resource": "" }
q252471
sameTMParams
validation
def sameTMParams(tp1, tp2): """Given two TM instances, see if any parameters are different.""" result = True for param in ["numberOfCols", "cellsPerColumn", "initialPerm", "connectedPerm", "minThreshold", "newSynapseCount", "permanenceInc", "permanenceDec", "permanenceMax", "global...
python
{ "resource": "" }
q252472
sameSegment
validation
def sameSegment(seg1, seg2): """Return True if seg1 and seg2 are identical, ignoring order of synapses""" result = True # check sequence segment, total activations etc. In case any are floats, # check that they are within 0.001. for field in [1, 2, 3, 4, 5, 6]: if abs(seg1[0][field] - seg2[0][field]) > 0...
python
{ "resource": "" }
q252473
spDiff
validation
def spDiff(SP1,SP2): """ Function that compares two spatial pooler instances. Compares the static variables between the two poolers to make sure that they are equivalent. Parameters ----------------------------------------- SP1 first spatial pooler to be compared SP2 second spatial pooler ...
python
{ "resource": "" }
q252474
_accumulateFrequencyCounts
validation
def _accumulateFrequencyCounts(values, freqCounts=None): """ Accumulate a list of values 'values' into the frequency counts 'freqCounts', and return the updated frequency counts For example, if values contained the following: [1,1,3,5,1,3,5], and the initial freqCounts was None, then the return value would b...
python
{ "resource": "" }
q252475
_fillInOnTimes
validation
def _fillInOnTimes(vector, durations): """ Helper function used by averageOnTimePerTimestep. 'durations' is a vector which must be the same len as vector. For each "on" in vector, it fills in the corresponding element of duration with the duration of that "on" signal up until that time Parameters: ------...
python
{ "resource": "" }
q252476
averageOnTimePerTimestep
validation
def averageOnTimePerTimestep(vectors, numSamples=None): """ Computes the average on-time of the outputs that are on at each time step, and then averages this over all time steps. This metric is resiliant to the number of outputs that are on at each time step. That is, if time step 0 has many more outputs on ...
python
{ "resource": "" }
q252477
averageOnTime
validation
def averageOnTime(vectors, numSamples=None): """ Returns the average on-time, averaged over all on-time runs. Parameters: ----------------------------------------------- vectors: the vectors for which the onTime is calculated. Row 0 contains the outputs from time step 0, row 1 fr...
python
{ "resource": "" }
q252478
plotHistogram
validation
def plotHistogram(freqCounts, title='On-Times Histogram', xLabel='On-Time'): """ This is usually used to display a histogram of the on-times encountered in a particular output. The freqCounts is a vector containg the frequency counts of each on-time (starting at an on-time of 0 and going to an on-time = len(...
python
{ "resource": "" }
q252479
populationStability
validation
def populationStability(vectors, numSamples=None): """ Returns the stability for the population averaged over multiple time steps Parameters: ----------------------------------------------- vectors: the vectors for which the stability is calculated numSamples the number of time steps where ...
python
{ "resource": "" }
q252480
percentOutputsStableOverNTimeSteps
validation
def percentOutputsStableOverNTimeSteps(vectors, numSamples=None): """ Returns the percent of the outputs that remain completely stable over N time steps. Parameters: ----------------------------------------------- vectors: the vectors for which the stability is calculated numSamples: the numbe...
python
{ "resource": "" }
q252481
computeSaturationLevels
validation
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....
python
{ "resource": "" }
q252482
checkMatch
validation
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...
python
{ "resource": "" }
q252483
getCentreAndSpreadOffsets
validation
def getCentreAndSpreadOffsets(spaceShape, spreadShape, stepSize=1): """ Generates centre offsets and spread offsets for block-mode based training regimes - star, cross, block. Parameters: ----------------------------------------------- space...
python
{ "resource": "" }
q252484
makeCloneMap
validation
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 ...
python
{ "resource": "" }
q252485
numpyStr
validation
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...
python
{ "resource": "" }
q252486
DiscreteDistribution.sample
validation
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. """
python
{ "resource": "" }
q252487
MultinomialDistribution.logProbability
validation
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()
python
{ "resource": "" }
q252488
PoissonDistribution.sample
validation
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.
python
{ "resource": "" }
q252489
createDataOutLink
validation
def createDataOutLink(network, sensorRegionName, regionName): """Link sensor region to other region so that it can pass it data.""" network.link(sensorRegionName,
python
{ "resource": "" }
q252490
createSensorToClassifierLinks
validation
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...
python
{ "resource": "" }
q252491
createNetwork
validation
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...
python
{ "resource": "" }
q252492
getPredictionResults
validation
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...
python
{ "resource": "" }
q252493
runHotgym
validation
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...
python
{ "resource": "" }
q252494
OPFDummyModelRunner._loadDummyModelParameters
validation
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:
python
{ "resource": "" }
q252495
OPFDummyModelRunner._getMetrics
validation
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: ...
python
{ "resource": "" }
q252496
OPFDummyModelRunner.__shouldSysExit
validation
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...
python
{ "resource": "" }
q252497
DataGenerator.getDescription
validation
def getDescription(self): """Returns a description of the dataset""" description = {'name':self.name, 'fields':[f.name for f in self.fields], \
python
{ "resource": "" }
q252498
DataGenerator.generateRecords
validation
def generateRecords(self, records): """Generate multiple records. Refer to definition for generateRecord""" if self.verbosity>0: print 'Generating',
python
{ "resource": "" }
q252499
DataGenerator.getRecord
validation
def getRecord(self, n=None): """Returns the nth record""" if n is None: assert len(self.fields)>0
python
{ "resource": "" }