Search is not available for this dataset
text stringlengths 75 104k |
|---|
def _getAdditionalSpecs(temporalImp, kwargs={}):
"""Build the additional specs in three groups (for the inspector)
Use the type of the default argument to set the Spec type, defaulting
to 'Byte' for None and complex types
Determines the spatial parameters based on the selected implementation.
It defaults to... |
def initialize(self):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.initialize`.
"""
# Allocate appropriate temporal memory object
# Retrieve the necessary extra arguments that were handled automatically
autoArgs = dict((name, getattr(self, name))
for name in self._te... |
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... |
def getBaseSpec(cls):
"""
Doesn't include the spatial, temporal and other parameters
:returns: (dict) the base Spec for TMRegion.
"""
spec = dict(
description=TMRegion.__doc__,
singleNodeOnly=True,
inputs=dict(
bottomUpIn=dict(
description="""The input signal, co... |
def getSpec(cls):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.getSpec`.
The parameters collection is constructed based on the parameters specified
by the various components (spatialSpec, temporalSpec and otherSpec)
"""
spec = cls.getBaseSpec()
t, o = _getAdditionalSpecs(t... |
def getParameter(self, parameterName, index=-1):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.getParameter`.
Get the value of a parameter. Most parameters are handled automatically by
:class:`~nupic.bindings.regions.PyRegion.PyRegion`'s parameter get mechanism. The
ones that need... |
def setParameter(self, parameterName, index, parameterValue):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.setParameter`.
"""
if parameterName in self._temporalArgNames:
setattr(self._tfdr, parameterName, parameterValue)
elif parameterName == "logPathOutput":
self.logP... |
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
all potential inputs to each column.
"""
if self._tfdr is None:
raise RuntimeError("Temporal memory has not bee... |
def writeToProto(self, proto):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.writeToProto`.
Write state to proto object.
:param proto: TMRegionProto capnproto object
"""
proto.temporalImp = self.temporalImp
proto.columnCount = self.columnCount
proto.inputWidth = self.i... |
def readFromProto(cls, proto):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.readFromProto`.
Read state from proto object.
:param proto: TMRegionProto capnproto object
"""
instance = cls(proto.columnCount, proto.inputWidth, proto.cellsPerColumn)
instance.temporalImp = pro... |
def getOutputElementCount(self, name):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.getOutputElementCount`.
"""
if name == 'bottomUpOut':
return self.outputWidth
elif name == 'topDownOut':
return self.columnCount
elif name == 'lrnActiveStateT':
return self.out... |
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... |
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
... |
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... |
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.... |
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... |
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... |
def _generateOverlapping(filename="overlap.csv", numSequences=2, elementsPerSeq=3,
numRepeats=10, hub=[0,1], hubOffset=1, resets=False):
""" Generate a temporal dataset containing sequences that overlap one or more
elements with other sequences.
Parameters:
--------------------------... |
def _generateFirstOrder0():
""" Generate the initial, first order, and second order transition
probabilities for 'probability0'. For this model, we generate the following
set of sequences:
.1 .75
0----1-----2
\ \
\ \ .25
\ \-----3
\
\ .9 .5
\--- 4-----... |
def _generateFileFromProb(filename, numRecords, categoryList, initProb,
firstOrderProb, secondOrderProb, seqLen, numNoise=0, resetsEvery=None):
""" Generate a set of records reflecting a set of probabilities.
Parameters:
----------------------------------------------------------------
filename: ... |
def getVersion():
"""
Get version from local file.
"""
with open(os.path.join(REPO_DIR, "VERSION"), "r") as versionFile:
return versionFile.read().strip() |
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... |
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... |
def _handleDescriptionOption(cmdArgStr, outDir, usageStr, hsVersion,
claDescriptionTemplateFile):
"""
Parses and validates the --description option args and executes the
request
Parameters:
-----------------------------------------------------------------------
cmdArgStr: JSON... |
def _handleDescriptionFromFileOption(filename, outDir, usageStr, hsVersion,
claDescriptionTemplateFile):
"""
Parses and validates the --descriptionFromFile option and executes the
request
Parameters:
-----------------------------------------------------------------------
filena... |
def _isInt(x, precision = 0.0001):
"""
Return (isInt, intValue) for a given floating point number.
Parameters:
----------------------------------------------------------------------
x: floating point number to evaluate
precision: desired precision
retval: (isInt, intValue)
isInt: True if x... |
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
"""... |
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:
------------------... |
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... |
def _generateEncoderChoicesV1(fieldInfo):
""" Return a list of possible encoder parameter combinations for the given
field and the default aggregation function to use. Each parameter combination
is a dict defining the parameters for the encoder. Here is an example
return value for the encoderChoicesList:
[
... |
def _generateEncoderStringsV1(includedFields):
""" Generate and return the following encoder related substitution variables:
encoderSpecsStr:
For the base description file, this string defines the default
encoding dicts for each encoder. For example:
'__gym_encoder' : { 'fieldname': 'gym',
... |
def _generatePermEncoderStr(options, encoderDict):
""" Generate the string that defines the permutations to apply for a given
encoder.
Parameters:
-----------------------------------------------------------------------
options: experiment params
encoderDict: the encoder dict, which gets placed into the des... |
def _generateEncoderStringsV2(includedFields, options):
""" Generate and return the following encoder related substitution variables:
encoderSpecsStr:
For the base description file, this string defines the default
encoding dicts for each encoder. For example:
__gym_encoder = { 'fieldname': 'gym... |
def _handleJAVAParameters(options):
""" Handle legacy options (TEMPORARY) """
# Find the correct InferenceType for the Model
if 'inferenceType' not in options:
prediction = options.get('prediction', {InferenceType.TemporalNextStep:
{'optimize':True}})
inferen... |
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]
if 'default' in paramsSchema:
options[propertyName] = pa... |
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... |
def _generateExperiment(options, outputDirPath, hsVersion,
claDescriptionTemplateFile):
""" Executes the --description option, which includes:
1. Perform provider compatibility checks
2. Preprocess the training and testing datasets (filter, join providers)
3. If test da... |
def _generateMetricsSubstitutions(options, tokenReplacements):
"""Generate the token substitution for metrics related fields.
This includes:
\$METRICS
\$LOGGED_METRICS
\$PERM_OPTIMIZE_SETTING
"""
# -----------------------------------------------------------------------
#
options['loggedMetrics']... |
def _generateMetricSpecs(options):
""" Generates the Metrics for a given InferenceType
Parameters:
-------------------------------------------------------------------------
options: ExpGenerator options
retval: (metricsList, optimizeMetricLabel)
metricsList: list of metric string names
... |
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,... |
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... |
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... |
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.
"""
# -----------------------------... |
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... |
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", "0"):
return False
raise Exception("Unable to convert string '%s' to a boolean value" % s) |
def escape(s):
"""
Escape commas, tabs, newlines and dashes in a string
Commas are encoded as tabs.
:param s: (string) to escape
:returns: (string) escaped string
"""
if s is None:
return ''
assert isinstance(s, basestring), \
"expected %s but got %s; value=%s" % (basestring, type(s), s)
... |
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)
s = s.replace('\t', ',')
s = s.replace('\\,', ',')
s = s.replace('\\n', '... |
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
"""
assert isinstance(s, basestring)
sdr = [int(c) for c in s if c in ("0", "1")]
if len(sdr) != len(s):
raise ValueError("The provided strin... |
def parseStringList(s):
"""
Parse a string of space-separated numbers, returning a Python list.
:param s: (string) to parse
:returns: (list) binary SDR
"""
assert isinstance(s, basestring)
return [int(i) for i in s.split()] |
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... |
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... |
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. ... |
def encodeIntoArray(self, inputData, output):
"""
See `nupic.encoders.base.Encoder` for more information.
@param inputData (tuple) Contains coordinate (numpy.array, N-dimensional
integer coordinate) and radius (int)
@param output (numpy.array) Stores encoded SDR in this num... |
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`
@return (numpy.array) List of coordinates
"""... |
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... |
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.
hash = int(int(hashlib.md5(coordinateStr).hexdigest(), 16) % (2 ** 64))
return hash |
def _orderForCoordinate(cls, coordinate):
"""
Returns the order for a coordinate.
@param coordinate (numpy.array) Coordinate
@return (float) A value in the interval [0, 1), representing the
order of the coordinate
"""
seed = cls._hashCoordinate(coordinate)
rng = Random(s... |
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
@return (int) The index to a bit in the SDR
"""
seed = cls._hashCoordinate(coordinate)
rng = Random(s... |
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 of the element if it is found and -1 otherwise.
"""
i = bisect_left(arr, val)
... |
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... |
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)... |
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... |
def destroySynapse(self, synapse):
"""
Destroys a synapse.
:param synapse: (:class:`Synapse`) synapse to destroy
"""
self._numSynapses -= 1
self._removeSynapseFromPresynapticMap(synapse)
synapse.segment._synapses.remove(synapse) |
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... |
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 specified cell
"""
if cell ... |
def segmentPositionSortKey(self, segment):
"""
Return a numeric key for sorting this segment. This can be used with the
python built-in ``sorted()`` function.
:param segment: (:class:`Segment`) within this :class:`Connections`
instance.
:returns: (float) A numeric key for sorting.
... |
def write(self, proto):
"""
Writes serialized data to proto object.
:param proto: (DynamicStructBuilder) Proto object
"""
protoCells = proto.init('cells', self.numCells)
for i in xrange(self.numCells):
segments = self._cells[i]._segments
protoSegments = protoCells[i].init('segment... |
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... |
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()... |
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... |
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
"""
if cls._properties is None:
cls._readStdConfigFiles()
cls._properties[prop] = str(value) |
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
... |
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.
"""
... |
def findConfigFile(cls, filename):
""" Search the configuration path (specified via the NTA_CONF_PATH
environment variable) for the given filename. If found, return the complete
path to the file.
:param filename: (string) name of file to locate
"""
paths = cls.getConfigPaths()
for p in pat... |
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 = os.environ['NTA_CONF_PATH']
... |
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... |
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.... |
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... |
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:
--------------------------------------... |
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... |
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 ... |
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'... |
def generateL2Sequences(nL1Patterns=10, l1Hubs=[2,6], l1SeqLength=[5,6,7],
nL1SimpleSequences=50, nL1HubSequences=50,
l1Pooling=4, perfectStability=False, spHysteresisFactor=1.0,
patternLen=500, patternActivity=50):
"""
Generate the simulated output from a spat... |
def vectorsFromSeqList(seqList, patternMatrix):
"""
Convert a list of sequences of pattern indices, and a pattern lookup table
into a an array of patterns
Parameters:
-----------------------------------------------
seq: the sequence, given as indices into the patternMatrix
patternMatrix: ... |
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... |
def sameSynapse(syn, synapses):
"""Given a synapse and a list of synapses, check whether this synapse
exist in the list. A synapse is represented as [col, cell, permanence].
A synapse matches if col and cell are identical and the permanence value is
within 0.001."""
for s in synapses:
if (s[0]==syn[0]) a... |
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... |
def tmDiff(tm1, tm2, verbosity = 0, relaxSegmentTests =True):
"""
Given two TM instances, list the difference between them and returns False
if there is a difference. This function checks the major parameters. If this
passes (and checkLearn is true) it checks the number of segments on
each cell. If this passe... |
def tmDiff2(tm1, tm2, verbosity = 0, relaxSegmentTests =True,
checkLearn = True, checkStates = True):
"""
Given two TM instances, list the difference between them and returns False
if there is a difference. This function checks the major parameters. If this
passes (and checkLearn is true) it checks ... |
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 ... |
def removeSeqStarts(vectors, resets, numSteps=1):
"""
Convert a list of sequences of pattern indices, and a pattern lookup table
into a an array of patterns
Parameters:
-----------------------------------------------
vectors: the data vectors. Row 0 contains the outputs from time
... |
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... |
def _listOfOnTimesInVec(vector):
"""
Returns 3 things for a vector:
* the total on time
* the number of runs
* a list of the durations of each run.
Parameters:
-----------------------------------------------
input stream: 11100000001100000000011111100000
return value: (11, 3, [3, 2, 6])
"""
... |
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:
------... |
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 ... |
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... |
def plotOutputsOverTime(vectors, buVectors=None, title='On-times'):
"""
Generate a figure that shows each output over time. Time goes left to right,
and each output is plotted on a different line, allowing you to see the overlap
in the outputs, when they turn on/off, etc.
Parameters:
----------------------... |
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(... |
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 ... |
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.