INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Get tuple ( actually a generator ) of indices where the max value of array x occurs. Requires that x have a max () method as x. max () ( in the case of NumPy ) is much faster than max ( x ). For a simpler faster argmax when there is only a single maximum entry or when knowing only the first index where the maximum occu...
def MultiArgMax(x): """ Get tuple (actually a generator) of indices where the max value of array x occurs. Requires that x have a max() method, as x.max() (in the case of NumPy) is much faster than max(x). For a simpler, faster argmax when there is only a single maximum entry, or when knowing only the first...
Tests much faster ( 30% ) than bool ( sum ( bool ( x ) for x in sequence )).
def Any(sequence): """ Tests much faster (30%) than bool(sum(bool(x) for x in sequence)). :returns: (bool) true if any element of the sequence satisfies True. :param sequence: Any sequence whose elements can be evaluated as booleans. """ return bool(reduce(lambda x, y: x or y, sequence, False))
: param sequence: Any sequence whose elements can be evaluated as booleans.: returns: true if all elements of the sequence satisfy True and x.
def All(sequence): """ :param sequence: Any sequence whose elements can be evaluated as booleans. :returns: true if all elements of the sequence satisfy True and x. """ return bool(reduce(lambda x, y: x and y, sequence, True))
Returns an array of length size and type dtype that is everywhere 0 except in the indices listed in sequence pos.
def MultiIndicator(pos, size, dtype): """ Returns an array of length size and type dtype that is everywhere 0, except in the indices listed in sequence pos. :param pos: A single integer or sequence of integers that specify the position of ones to be set. :param size: The total size of the array t...
Returns an array of length size and type dtype that is everywhere 0 except in the indices listed in sequence pos. The non - zero indices contain a normalized distribution based on the counts.
def Distribution(pos, size, counts, dtype): """ Returns an array of length size and type dtype that is everywhere 0, except in the indices listed in sequence pos. The non-zero indices contain a normalized distribution based on the counts. :param pos: A single integer or sequence of integers that specify...
Grows the histogram to have rows rows and cols columns. Must not have been initialized before or already have the same number of columns. If rows is smaller than the current number of rows does not shrink. Also updates the sizes of the row and column sums.
def grow(self, rows, cols): """ Grows the histogram to have rows rows and cols columns. Must not have been initialized before, or already have the same number of columns. If rows is smaller than the current number of rows, does not shrink. Also updates the sizes of the row and column sums. ...
Add distribution to row row. Distribution should be an array of probabilities or counts.
def updateRow(self, row, distribution): """ Add distribution to row row. Distribution should be an array of probabilities or counts. :param row: Integer index of the row to add to. May be larger than the current number of rows, in which case the histogram grows. ...
Equivalent to the category inference of zeta1. TopLevel. Computes the max_prod ( maximum component of a component - wise multiply ) between the rows of the histogram and the incoming distribution. May be slow if the result of clean_outcpd () is not valid.
def inferRowCompat(self, distribution): """ Equivalent to the category inference of zeta1.TopLevel. Computes the max_prod (maximum component of a component-wise multiply) between the rows of the histogram and the incoming distribution. May be slow if the result of clean_outcpd() is not valid. :...
Hack to act like clean_outcpd on zeta1. TopLevelNode. Take the max element in each to column set it to 1 and set all the other elements to 0. Only called by inferRowMaxProd () and only needed if an updateRow () has been called since the last clean_outcpd ().
def clean_outcpd(self): """Hack to act like clean_outcpd on zeta1.TopLevelNode. Take the max element in each to column, set it to 1, and set all the other elements to 0. Only called by inferRowMaxProd() and only needed if an updateRow() has been called since the last clean_outcpd(). """ m = ...
Run a named function specified by a filesystem path module name and function name.
def importAndRunFunction( path, moduleName, funcName, **keywords ): """ Run a named function specified by a filesystem path, module name and function name. Returns the value returned by the imported function. Use this when access is needed to code that has not been added to a package acc...
Gets the coincidence matrix from one element and sets it on another element ( using locked handles a la nupic. bindings. research. lockHandle ).
def transferCoincidences(network, fromElementName, toElementName): """ Gets the coincidence matrix from one element and sets it on another element (using locked handles, a la nupic.bindings.research.lockHandle). TODO: Generalize to more node types, parameter name pairs, etc. Does not work across processes...
Routine for computing a moving average.
def compute(slidingWindow, total, newVal, windowSize): """Routine for computing a moving average. @param slidingWindow a list of previous values to use in computation that will be modified and returned @param total the sum of the values in slidingWindow to be used in the calculation of the ...
Instance method wrapper around compute.
def next(self, newValue): """Instance method wrapper around compute.""" newAverage, self.slidingWindow, self.total = self.compute( self.slidingWindow, self.total, newValue, self.windowSize) return newAverage
Factory method to return an appropriate: class: MetricsIface module. - rmse:: class: MetricRMSE - nrmse:: class: MetricNRMSE - aae:: class: MetricAAE - acc:: class: MetricAccuracy - avg_err:: class: MetricAveError - trivial:: class: MetricTrivial - two_gram:: class: MetricTwoGram - moving_mean:: class: MetricMovingMean...
def getModule(metricSpec): """ Factory method to return an appropriate :class:`MetricsIface` module. - ``rmse``: :class:`MetricRMSE` - ``nrmse``: :class:`MetricNRMSE` - ``aae``: :class:`MetricAAE` - ``acc``: :class:`MetricAccuracy` - ``avg_err``: :class:`MetricAveError` - ``trivial``: :class:`MetricT...
Helper method that generates a unique label for a: class: MetricSpec/: class: ~nupic. frameworks. opf. opf_utils. InferenceType pair. The label is formatted as follows:
def getLabel(self, inferenceType=None): """ Helper method that generates a unique label for a :class:`MetricSpec` / :class:`~nupic.frameworks.opf.opf_utils.InferenceType` pair. The label is formatted as follows: :: <predictionKind>:<metric type>:(paramName=value)*:field=<fieldna...
Extracts the PredictionKind ( temporal vs. nontemporal ) from the given metric label.
def getInferenceTypeFromLabel(cls, label): """ Extracts the PredictionKind (temporal vs. nontemporal) from the given metric label. :param label: (string) for a metric spec generated by :meth:`getMetricLabel` :returns: (:class:`~nupic.frameworks.opf.opf_utils.InferenceType`) """ ...
Utility function that saves the passed in groundTruth into a local history buffer and returns the groundTruth from self. _predictionSteps ago where self. _predictionSteps is defined by the steps parameter. This can be called from the beginning of a derived class s addInstance () before it passes groundTruth and predict...
def _getShiftedGroundTruth(self, groundTruth): """ Utility function that saves the passed in groundTruth into a local history buffer, and returns the groundTruth from self._predictionSteps ago, where self._predictionSteps is defined by the 'steps' parameter. This can be called from the beginning of a de...
Compute and store metric value
def addInstance(self, groundTruth, prediction, record = None, result = None): """Compute and store metric value""" self.value = self.avg(prediction)
Helper function to return a scalar value representing the most likely outcome given a probability distribution
def mostLikely(self, pred): """ Helper function to return a scalar value representing the most likely outcome given a probability distribution """ if len(pred) == 1: return pred.keys()[0] mostLikelyOutcome = None maxProbability = 0 for prediction, probability in pred.items(): ...
Helper function to return a scalar value representing the expected value of a probability distribution
def expValue(self, pred): """ Helper function to return a scalar value representing the expected value of a probability distribution """ if len(pred) == 1: return pred.keys()[0] return sum([x*p for x,p in pred.items()])
Convenience wrapper for: meth:. encodeIntoArray.
def encode(self, inputData): """Convenience wrapper for :meth:`.encodeIntoArray`. This may be less efficient because it allocates a new numpy array every call. :param inputData: input data to be encoded :return: a numpy array with the encoded representation of inputData """ output = numpy....
Return the field names for each of the scalar values returned by getScalars.
def getScalarNames(self, parentFieldName=''): """ Return the field names for each of the scalar values returned by getScalars. :param parentFieldName: The name of the encoder which is our parent. This name is prefixed to each of the field names within this encoder to form the keys of th...
Returns a sequence of field types corresponding to the elements in the decoded output field array. The types are defined by: class: ~nupic. data. field_meta. FieldMetaType.
def getDecoderOutputFieldTypes(self): """ Returns a sequence of field types corresponding to the elements in the decoded output field array. The types are defined by :class:`~nupic.data.field_meta.FieldMetaType`. :return: list of :class:`~nupic.data.field_meta.FieldMetaType` objects """ if...
Gets the value of a given field from the input record
def _getInputValue(self, obj, fieldName): """ Gets the value of a given field from the input record """ if isinstance(obj, dict): if not fieldName in obj: knownFields = ", ".join( key for key in obj.keys() if not key.startswith("_") ) raise ValueError( "...
: return: a reference to each sub - encoder in this encoder. They are returned in the same order as they are for: meth:. getScalarNames and: meth:. getScalars.
def getEncoderList(self): """ :return: a reference to each sub-encoder in this encoder. They are returned in the same order as they are for :meth:`.getScalarNames` and :meth:`.getScalars`. """ if hasattr(self, '_flattenedEncoderList') and \ self._flattenedEncoderList i...
Returns a numpy array containing the sub - field scalar value ( s ) for each sub - field of the inputData. To get the associated field names for each of the scalar values call: meth:. getScalarNames ().
def getScalars(self, inputData): """ Returns a numpy array containing the sub-field scalar value(s) for each sub-field of the ``inputData``. To get the associated field names for each of the scalar values, call :meth:`.getScalarNames()`. For a simple scalar encoder, the scalar value is simply the i...
Returns the input in the same format as is returned by: meth:. topDownCompute. For most encoder types this is the same as the input data. For instance for scalar and category types this corresponds to the numeric and string values respectively from the inputs. For datetime encoders this returns the list of scalars for ...
def getEncodedValues(self, inputData): """ Returns the input in the same format as is returned by :meth:`.topDownCompute`. For most encoder types, this is the same as the input data. For instance, for scalar and category types, this corresponds to the numeric and string values, respectively, from th...
Returns an array containing the sub - field bucket indices for each sub - field of the inputData. To get the associated field names for each of the buckets call: meth:. getScalarNames.
def getBucketIndices(self, inputData): """ Returns an array containing the sub-field bucket indices for each sub-field of the inputData. To get the associated field names for each of the buckets, call :meth:`.getScalarNames`. :param inputData: The data from the source. This is typically an object w...
Return a pretty print string representing the return values from: meth:. getScalars and: meth:. getScalarNames.
def scalarsToStr(self, scalarValues, scalarNames=None): """ Return a pretty print string representing the return values from :meth:`.getScalars` and :meth:`.getScalarNames`. :param scalarValues: input values to encode to string :param scalarNames: optional input of scalar names to convert. If None,...
Return the offset and length of a given field within the encoded output.
def getFieldDescription(self, fieldName): """ Return the offset and length of a given field within the encoded output. :param fieldName: Name of the field :return: tuple(``offset``, ``width``) of the field within the encoded output """ # Find which field it's in description = self.getDescr...
Return a description of the given bit in the encoded output. This will include the field name and the offset within the field.
def encodedBitDescription(self, bitOffset, formatted=False): """ Return a description of the given bit in the encoded output. This will include the field name and the offset within the field. :param bitOffset: Offset of the bit to get the description of :param formatted: If True, the bitO...
Pretty - print a header that labels the sub - fields of the encoded output. This can be used in conjuction with: meth:. pprint.
def pprintHeader(self, prefix=""): """ Pretty-print a header that labels the sub-fields of the encoded output. This can be used in conjuction with :meth:`.pprint`. :param prefix: printed before the header if specified """ print prefix, description = self.getDescription() + [("end", self.get...
Pretty - print the encoded output using ascii art.
def pprint(self, output, prefix=""): """ Pretty-print the encoded output using ascii art. :param output: to print :param prefix: printed before the header if specified """ print prefix, description = self.getDescription() + [("end", self.getWidth())] for i in xrange(len(description) - 1...
Takes an encoded output and does its best to work backwards and generate the input that would have generated it.
def decode(self, encoded, parentFieldName=''): """ Takes an encoded output and does its best to work backwards and generate the input that would have generated it. In cases where the encoded output contains more ON bits than an input would have generated, this routine will return one or more ranges...
Return a pretty print string representing the return value from: meth:. decode.
def decodedToStr(self, decodeResults): """ Return a pretty print string representing the return value from :meth:`.decode`. """ (fieldsDict, fieldsOrder) = decodeResults desc = '' for fieldName in fieldsOrder: (ranges, rangesStr) = fieldsDict[fieldName] if len(desc) > 0: ...
Returns a list of: class:. EncoderResult namedtuples describing the inputs for each sub - field that correspond to the bucket indices passed in buckets. To get the associated field names for each of the values call: meth:. getScalarNames.
def getBucketInfo(self, buckets): """ Returns a list of :class:`.EncoderResult` namedtuples describing the inputs for each sub-field that correspond to the bucket indices passed in ``buckets``. To get the associated field names for each of the values, call :meth:`.getScalarNames`. :param bucket...
Returns a list of: class:. EncoderResult namedtuples describing the top - down best guess inputs for each sub - field given the encoded output. These are the values which are most likely to generate the given encoded output. To get the associated field names for each of the values call: meth:. getScalarNames.
def topDownCompute(self, encoded): """ Returns a list of :class:`.EncoderResult` namedtuples describing the top-down best guess inputs for each sub-field given the encoded output. These are the values which are most likely to generate the given encoded output. To get the associated field names for e...
Compute closeness scores between the expected scalar value ( s ) and actual scalar value ( s ). The expected scalar values are typically those obtained from the: meth:. getScalars method. The actual scalar values are typically those returned from: meth:. topDownCompute.
def closenessScores(self, expValues, actValues, fractional=True): """ Compute closeness scores between the expected scalar value(s) and actual scalar value(s). The expected scalar values are typically those obtained from the :meth:`.getScalars` method. The actual scalar values are typically those re...
/ models/ { name }
def POST(self, name): """ /models/{name} schema: { "modelParams": dict containing model parameters "predictedFieldName": str } returns: {"success":name} """ global g_models data = json.loads(web.data()) modelParams = data["modelParams"] predictedFieldName =...
/ models/ { name }/ run
def POST(self, name): """ /models/{name}/run schema: { predictedFieldName: value timestamp: %m/%d/%y %H:%M } NOTE: predictedFieldName MUST be the same name specified when creating the model. returns: { "predictionNumber":<number of record>, ...
Mirror Image Visualization: Shows the encoding space juxtaposed against the coincidence space. The encoding space is the bottom - up sensory encoding and the coincidence space depicts the corresponding activation of coincidences in the SP. Hence the mirror image visualization is a visual depiction of the mapping of SP ...
def analyzeOverlaps(activeCoincsFile, encodingsFile, dataset): '''Mirror Image Visualization: Shows the encoding space juxtaposed against the coincidence space. The encoding space is the bottom-up sensory encoding and the coincidence space depicts the corresponding activation of coincidences in the SP. Hence, t...
The similarity of two patterns in the bit - encoding space is displayed alongside their similarity in the sp - coinc space.
def drawFile(dataset, matrix, patterns, cells, w, fnum): '''The similarity of two patterns in the bit-encoding space is displayed alongside their similarity in the sp-coinc space.''' score=0 count = 0 assert len(patterns)==len(cells) for p in xrange(len(patterns)-1): matrix[p+1:,p] = [len(set(patterns[p...
Compare the results and return True if success False if failure Parameters: -------------------------------------------------------------------- coincs: Which cells are we comparing? comparedTo: The set of 40 cells we being compared to ( they have no overlap with seen ) seen: Which of the cells we are comparing to have...
def printOverlaps(comparedTo, coincs, seen): """ Compare the results and return True if success, False if failure Parameters: -------------------------------------------------------------------- coincs: Which cells are we comparing? comparedTo: The set of 40 cells we being compare...
create a random input vector
def createInput(self): """create a random input vector""" print "-" * 70 + "Creating a random input vector" + "-" * 70 #clear the inputArray to zero before creating a new input vector self.inputArray[0:] = 0 for i in range(self.inputSize): #randrange returns 0 or 1 self.inputArray[i] ...
Run the spatial pooler with the input vector
def run(self): """Run the spatial pooler with the input vector""" print "-" * 80 + "Computing the SDR" + "-" * 80 #activeArray[column]=1 if column is active after spatial pooling self.sp.compute(self.inputArray, True, self.activeArray) print self.activeArray.nonzero()
Flip the value of 10% of input bits ( add noise )
def addNoise(self, noiseLevel): """Flip the value of 10% of input bits (add noise) :param noiseLevel: The percentage of total input bits that should be flipped """ for _ in range(int(noiseLevel * self.inputSize)): # 0.1*self.inputSize represents 10% of the total input bits # random.random(...
Print the list of [ column cellIdx ] indices for each of the active cells in activeInputs.
def _labeledInput(activeInputs, cellsPerCol=32): """Print the list of [column, cellIdx] indices for each of the active cells in activeInputs. """ if cellsPerCol == 0: cellsPerCol = 1 cols = activeInputs.size / cellsPerCol activeInputs = activeInputs.reshape(cols, cellsPerCol) (cols, cellIdxs) = active...
Clears the state of the KNNClassifier.
def clear(self): """Clears the state of the KNNClassifier.""" self._Memory = None self._numPatterns = 0 self._M = None self._categoryList = [] self._partitionIdList = [] self._partitionIdMap = {} self._finishedLearning = False self._iterationIdx = -1 # Fixed capacity KNN if ...
Allows ids to be assigned a category and subsequently enables users to use:
def prototypeSetCategory(self, idToCategorize, newCategory): """ Allows ids to be assigned a category and subsequently enables users to use: - :meth:`~.KNNClassifier.KNNClassifier.removeCategory` - :meth:`~.KNNClassifier.KNNClassifier.closestTrainingPattern` - :meth:`~.KNNClassifier.KNNClassi...
There are two caveats. First this is a potentially slow operation. Second pattern indices will shift if patterns before them are removed.
def removeIds(self, idsToRemove): """ There are two caveats. First, this is a potentially slow operation. Second, pattern indices will shift if patterns before them are removed. :param idsToRemove: A list of row indices to remove. """ # Form a list of all categories to remove rowsToRemove =...
There are two caveats. First this is a potentially slow operation. Second pattern indices will shift if patterns before them are removed.
def removeCategory(self, categoryToRemove): """ There are two caveats. First, this is a potentially slow operation. Second, pattern indices will shift if patterns before them are removed. :param categoryToRemove: Category label to remove """ removedRows = 0 if self._Memory is None: re...
A list of row indices to remove. There are two caveats. First this is a potentially slow operation. Second pattern indices will shift if patterns before them are removed.
def _removeRows(self, rowsToRemove): """ A list of row indices to remove. There are two caveats. First, this is a potentially slow operation. Second, pattern indices will shift if patterns before them are removed. """ # Form a numpy array of row indices to be removed removalArray = numpy.arr...
Train the classifier to associate specified input pattern with a particular category.
def learn(self, inputPattern, inputCategory, partitionId=None, isSparse=0, rowID=None): """ Train the classifier to associate specified input pattern with a particular category. :param inputPattern: (list) The pattern to be assigned a category. If isSparse is 0, this should be a den...
Return the degree of overlap between an input pattern and each category stored in the classifier. The overlap is computed by computing:
def getOverlaps(self, inputPattern): """ Return the degree of overlap between an input pattern and each category stored in the classifier. The overlap is computed by computing: .. code-block:: python logical_and(inputPattern != 0, trainingPattern != 0).sum() :param inputPattern: pattern to ...
Return the distances between the input pattern and all other stored patterns.
def getDistances(self, inputPattern): """Return the distances between the input pattern and all other stored patterns. :param inputPattern: pattern to check distance with :returns: (distances, categories) numpy arrays of the same length. - overlaps: an integer overlap amount for each category ...
Finds the category that best matches the input pattern. Returns the winning category index as well as a distribution over all categories.
def infer(self, inputPattern, computeScores=True, overCategories=True, partitionId=None): """Finds the category that best matches the input pattern. Returns the winning category index as well as a distribution over all categories. :param inputPattern: (list or array) The pattern to be classifie...
Returns the index of the pattern that is closest to inputPattern the distances of all patterns to inputPattern and the indices of the k closest categories.
def getClosest(self, inputPattern, topKCategories=3): """Returns the index of the pattern that is closest to inputPattern, the distances of all patterns to inputPattern, and the indices of the k closest categories. """ inferenceResult = numpy.zeros(max(self._categoryList)+1) dist = self._getDist...
Returns the closest training pattern to inputPattern that belongs to category cat.
def closestTrainingPattern(self, inputPattern, cat): """Returns the closest training pattern to inputPattern that belongs to category "cat". :param inputPattern: The pattern whose closest neighbor is sought :param cat: The required category of closest neighbor :returns: A dense version of the clo...
Gets a training pattern either by index or category number.
def getPattern(self, idx, sparseBinaryForm=False, cat=None): """Gets a training pattern either by index or category number. :param idx: Index of the training pattern :param sparseBinaryForm: If true, returns a list of the indices of the non-zero bits in the training pattern :param cat: If not...
Gets the partition id given an index.
def getPartitionId(self, i): """ Gets the partition id given an index. :param i: index of partition :returns: the partition id associated with pattern i. Returns None if no id is associated with it. """ if (i < 0) or (i >= self._numPatterns): raise RuntimeError("index out of bound...
Adds partition id for pattern index
def _addPartitionId(self, index, partitionId=None): """ Adds partition id for pattern index """ if partitionId is None: self._partitionIdList.append(numpy.inf) else: self._partitionIdList.append(partitionId) indices = self._partitionIdMap.get(partitionId, []) indices.append(i...
Rebuilds the partition Id map using the given partitionIdList
def _rebuildPartitionIdMap(self, partitionIdList): """ Rebuilds the partition Id map using the given partitionIdList """ self._partitionIdMap = {} for row, partitionId in enumerate(partitionIdList): indices = self._partitionIdMap.get(partitionId, []) indices.append(row) self._parti...
Calculate the distances from inputPattern to all stored patterns. All distances are between 0. 0 and 1. 0
def _calcDistance(self, inputPattern, distanceNorm=None): """Calculate the distances from inputPattern to all stored patterns. All distances are between 0.0 and 1.0 :param inputPattern The pattern from which distances to all other patterns are calculated :param distanceNorm Degree of the dista...
Return the distances from inputPattern to all stored patterns.
def _getDistances(self, inputPattern, partitionId=None): """Return the distances from inputPattern to all stored patterns. :param inputPattern The pattern from which distances to all other patterns are returned :param partitionId If provided, ignore all training vectors with this partition...
Compute the singular value decomposition ( SVD ). The SVD is a factorization of a real or complex matrix. It factors the matrix a as u * np. diag ( s ) * v where u and v are unitary and s is a 1 - d array of a s singular values.
def computeSVD(self, numSVDSamples=0, finalize=True): """ Compute the singular value decomposition (SVD). The SVD is a factorization of a real or complex matrix. It factors the matrix `a` as `u * np.diag(s) * v`, where `u` and `v` are unitary and `s` is a 1-d array of `a`'s singular values. **R...
Compute the number of eigenvectors ( singularValues ) to keep.
def getAdaptiveSVDDims(self, singularValues, fractionOfMax=0.001): """ Compute the number of eigenvectors (singularValues) to keep. :param singularValues: :param fractionOfMax: :return: """ v = singularValues/singularValues[0] idx = numpy.where(v<fractionOfMax)[0] if len(idx): ...
Called by finalizeLearning (). This will project all the patterns onto the SVD eigenvectors.: param numSVDDims: ( int ) number of egeinvectors used for projection.: return:
def _finalizeSVD(self, numSVDDims=None): """ Called by finalizeLearning(). This will project all the patterns onto the SVD eigenvectors. :param numSVDDims: (int) number of egeinvectors used for projection. :return: """ if numSVDDims is not None: self.numSVDDims = numSVDDims if se...
Change the category indices.
def remapCategories(self, mapping): """Change the category indices. Used by the Network Builder to keep the category indices in sync with the ImageSensor categoryInfo when the user renames or removes categories. :param mapping: List of new category indices. For example, mapping=[2,0,1] would c...
Change the category associated with this vector ( s ).
def setCategoryOfVectors(self, vectorIndices, categoryIndices): """Change the category associated with this vector(s). Used by the Network Builder to move vectors between categories, to enable categories, and to invalidate vectors by setting the category to -1. :param vectorIndices: Single index or li...
Get the next record to encode. Includes getting a record from the dataSource and applying filters. If the filters request more data from the dataSource continue to get data from the dataSource until all filters are satisfied. This method is separate from: meth:. RecordSensor. compute so that we can use a standalone: cl...
def getNextRecord(self): """ Get the next record to encode. Includes getting a record from the `dataSource` and applying filters. If the filters request more data from the `dataSource` continue to get data from the `dataSource` until all filters are satisfied. This method is separate from :meth:`...
Apply pre - encoding filters. These filters may modify or add data. If a filter needs another record ( e. g. a delta filter ) it will request another record by returning False and the current record will be skipped ( but will still be given to all filters ).
def applyFilters(self, data): """ Apply pre-encoding filters. These filters may modify or add data. If a filter needs another record (e.g. a delta filter) it will request another record by returning False and the current record will be skipped (but will still be given to all filters). We hav...
Populate the output array with the category indices... note:: Non - categories are represented with - 1.
def populateCategoriesOut(self, categories, output): """ Populate the output array with the category indices. .. note:: Non-categories are represented with ``-1``. :param categories: (list) of category strings :param output: (list) category output, will be overwritten """ if categories...
Get a record from the dataSource and encode it. Overrides: meth: nupic. bindings. regions. PyRegion. PyRegion. compute.
def compute(self, inputs, outputs): """ Get a record from the dataSource and encode it. Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.compute`. """ if not self.topDownMode: data = self.getNextRecord() # The private keys in data are standard of RecordStreamIface objects....
Converts all of the non - numeric fields from spatialOutput and temporalOutput into their scalar equivalents and records them in the output dictionary.
def _convertNonNumericData(self, spatialOutput, temporalOutput, output): """ Converts all of the non-numeric fields from spatialOutput and temporalOutput into their scalar equivalents and records them in the output dictionary. :param spatialOutput: The results of topDownCompute() for the spatial input....
Computes the width of dataOut.
def getOutputElementCount(self, name): """ Computes the width of dataOut. Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getOutputElementCount`. """ if name == "resetOut": print ("WARNING: getOutputElementCount should not have been called with " "resetOut") ...
Set the value of a Spec parameter. Most parameters are handled automatically by PyRegion s parameter set mechanism. The ones that need special treatment are explicitly handled here.
def setParameter(self, parameterName, index, parameterValue): """ Set the value of a Spec parameter. Most parameters are handled automatically by PyRegion's parameter set mechanism. The ones that need special treatment are explicitly handled here. """ if parameterName == 'topDownMode': ...
Overrides: meth: nupic. bindings. regions. PyRegion. PyRegion. writeToProto.
def writeToProto(self, proto): """ Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.writeToProto`. """ self.encoder.write(proto.encoder) if self.disabledEncoder is not None: self.disabledEncoder.write(proto.disabledEncoder) proto.topDownMode = int(self.topDownMode) proto.verbo...
Overrides: meth: nupic. bindings. regions. PyRegion. PyRegion. readFromProto.
def readFromProto(cls, proto): """ Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.readFromProto`. """ instance = cls() instance.encoder = MultiEncoder.read(proto.encoder) if proto.disabledEncoder is not None: instance.disabledEncoder = MultiEncoder.read(proto.disabledEncode...
Compute prediction accuracy by checking if the next page in the sequence is within the top N predictions calculated by the model Args: model: HTM model size: Sample size top: top N predictions to use
def computeAccuracy(model, size, top): """ Compute prediction accuracy by checking if the next page in the sequence is within the top N predictions calculated by the model Args: model: HTM model size: Sample size top: top N predictions to use Returns: Probability the next page in the sequence is ...
Reads the user session record from the file s cursor position Args: datafile: Data file whose cursor points at the beginning of the record
def readUserSession(datafile): """ Reads the user session record from the file's cursor position Args: datafile: Data file whose cursor points at the beginning of the record Returns: list of pages in the order clicked by the user """ for line in datafile: pages = line.split() total = len(pa...
Put us back at the beginning of the file again.
def rewind(self): """ Put us back at the beginning of the file again. """ # Superclass rewind super(FileRecordStream, self).rewind() self.close() self._file = open(self._filename, self._mode) self._reader = csv.reader(self._file, dialect="excel") # Skip header rows self._reade...
Returns next available data record from the file.
def getNextRecord(self, useCache=True): """ Returns next available data record from the file. :returns: a data row (a list or tuple) if available; None, if no more records in the table (End of Stream - EOS); empty sequence (list or tuple) when timing out while waiting for the next r...
Saves the record in the underlying csv file.
def appendRecord(self, record): """ Saves the record in the underlying csv file. :param record: a list of Python objects that will be string-ified """ assert self._file is not None assert self._mode == self._FILE_WRITE_MODE assert isinstance(record, (list, tuple)), \ "unexpected reco...
Saves multiple records in the underlying storage.
def appendRecords(self, records, progressCB=None): """ Saves multiple records in the underlying storage. :param records: array of records as in :meth:`~.FileRecordStream.appendRecord` :param progressCB: (function) callback to report progress """ for record in records: ...
Gets a bookmark or anchor to the current position.
def getBookmark(self): """ Gets a bookmark or anchor to the current position. :returns: an anchor to the current position in the data. Passing this anchor to a constructor makes the current position to be the first returned record. """ if self._write and self._recordCou...
Seeks to numRecords from the end and returns a bookmark to the new position.
def seekFromEnd(self, numRecords): """ Seeks to ``numRecords`` from the end and returns a bookmark to the new position. :param numRecords: how far to seek from end of file. :return: bookmark to desired location. """ self._file.seek(self._getTotalLineCount() - numRecords) return self.get...
Parse the file using dedicated reader and collect fields stats. Never called if user of: class: ~. FileRecordStream does not invoke: meth: ~. FileRecordStream. getStats method.
def getStats(self): """ Parse the file using dedicated reader and collect fields stats. Never called if user of :class:`~.FileRecordStream` does not invoke :meth:`~.FileRecordStream.getStats` method. :returns: a dictionary of stats. In the current implementation, min and max fie...
Keep track of sequence and make sure time goes forward
def _updateSequenceInfo(self, r): """Keep track of sequence and make sure time goes forward Check if the current record is the beginning of a new sequence A new sequence starts in 2 cases: 1. The sequence id changed (if there is a sequence id field) 2. The reset field is 1 (if there is a reset fie...
Extracts start row from the bookmark information
def _getStartRow(self, bookmark): """ Extracts start row from the bookmark information """ bookMarkDict = json.loads(bookmark) realpath = os.path.realpath(self._filename) bookMarkFile = bookMarkDict.get('filepath', None) if bookMarkFile != realpath: print ("Ignoring bookmark due to mism...
Returns: count of ALL lines in dataset including header lines
def _getTotalLineCount(self): """ Returns: count of ALL lines in dataset, including header lines """ # Flush the file before we open it again to count lines if self._mode == self._FILE_WRITE_MODE: self._file.flush() return sum(1 for line in open(self._filename, self._FILE_READ_MODE))
: returns: ( int ) count of data rows in dataset ( excluding header lines )
def getDataRowCount(self): """ :returns: (int) count of data rows in dataset (excluding header lines) """ numLines = self._getTotalLineCount() if numLines == 0: # this may be the case in a file opened for write before the # header rows are written out assert self._mode == self._FI...
Handles looping over the input data and passing each row into the given model object as well as extracting the result object and passing it into an output handler.: param inputData: file path to input data CSV: param model: OPF Model object: param gymName: Gym name used for output handler naming: param plot: Whether to...
def runIoThroughNupic(inputData, model, gymName, plot): """ Handles looping over the input data and passing each row into the given model object, as well as extracting the result object and passing it into an output handler. :param inputData: file path to input data CSV :param model: OPF Model object :par...
[ ScalarEncoder class method override ]
def topDownCompute(self, encoded): """[ScalarEncoder class method override]""" #Decode to delta scalar if self._prevAbsolute==None or self._prevDelta==None: return [EncoderResult(value=0, scalar=0, encoding=numpy.zeros(self.n))] ret = self._adaptiveScalarEnc.topDownCo...
Returns True if the inference from this timestep is predicted the input for the NEXT timestep.
def isTemporal(inferenceElement): """ Returns True if the inference from this timestep is predicted the input for the NEXT timestep. NOTE: This should only be checked IF THE MODEL'S INFERENCE TYPE IS ALSO TEMPORAL. That is, a temporal model CAN have non-temporal inference elements, but a non-tempor...
Returns the number of records that elapse between when an inference is made and when the corresponding input record will appear. For example a multistep prediction for 3 timesteps out will have a delay of 3
def getTemporalDelay(inferenceElement, key=None): """ Returns the number of records that elapse between when an inference is made and when the corresponding input record will appear. For example, a multistep prediction for 3 timesteps out will have a delay of 3 Parameters: ------------------------...
Returns the maximum delay for the InferenceElements in the inference dictionary
def getMaxDelay(inferences): """ Returns the maximum delay for the InferenceElements in the inference dictionary Parameters: ----------------------------------------------------------------------- inferences: A dictionary where the keys are InferenceElements """ maxDelay = 0 for i...
Returns True if the inference type is temporal i. e. requires a temporal memory in the network.
def isTemporal(inferenceType): """ Returns True if the inference type is 'temporal', i.e. requires a temporal memory in the network. """ if InferenceType.__temporalInferenceTypes is None: InferenceType.__temporalInferenceTypes = \ set([InferenceType.TemporalNextStep...
Utility function for creating enumerations in python
def Enum(*args, **kwargs): """ Utility function for creating enumerations in python Example Usage: >> Color = Enum("Red", "Green", "Blue", "Magenta") >> print Color.Red >> 0 >> print Color.Green >> 1 >> print Color.Blue >> 2 >> print Color.Magenta >> 3 >> Color.Violet ...
Makes directory for the given directory path with default permissions. If the directory already exists it is treated as success.
def makeDirectoryFromAbsolutePath(absDirPath): """ Makes directory for the given directory path with default permissions. If the directory already exists, it is treated as success. absDirPath: absolute path of the directory to create. Returns: absDirPath arg Exceptions: OSError if directory ...
Parse the given XML file and return a dict describing the file.
def _readConfigFile(cls, filename, path=None): """ Parse the given XML file and return a dict describing the file. Parameters: ---------------------------------------------------------------- filename: name of XML file to parse (no path) path: path of the XML file. If None, then use the stand...