Search is not available for this dataset
text stringlengths 75 104k |
|---|
def _finalize(self):
"""Run final activities after a model has run. These include recording and
logging the final score"""
self._logger.info(
"Finished: modelID=%r; %r records processed. Performing final activities",
self._modelID, self._currentRecordIndex + 1)
# ==========================... |
def __createModelCheckpoint(self):
""" Create a checkpoint from the current model, and store it in a dir named
after checkpoint GUID, and finally store the GUID in the Models DB """
if self._model is None or self._modelCheckpointGUID is None:
return
# Create an output store, if one doesn't exist... |
def __deleteModelCheckpoint(self, modelID):
"""
Delete the stored checkpoint for the specified modelID. This function is
called if the current model is now the best model, making the old model's
checkpoint obsolete
Parameters:
--------------------------------------------------------------------... |
def _createPredictionLogger(self):
"""
Creates the model's PredictionLogger object, which is an interface to write
model results to a permanent storage location
"""
# Write results to a file
self._predictionLogger = BasicPredictionLogger(
fields=self._model.getFieldInfo(),
experiment... |
def __getOptimizedMetricLabel(self):
""" Get the label for the metric being optimized. This function also caches
the label in the instance variable self._optimizedMetricLabel
Parameters:
-----------------------------------------------------------------------
metricLabels: A sequence of all the la... |
def _getFieldStats(self):
"""
Method which returns a dictionary of field statistics received from the
input source.
Returns:
fieldStats: dict of dicts where the first level is the field name and
the second level is the statistic. ie. fieldStats['pounds']['min']
"""
fieldStats =... |
def _updateModelDBResults(self):
""" Retrieves the current results and updates the model's record in
the Model database.
"""
# -----------------------------------------------------------------------
# Get metrics
metrics = self._getMetrics()
# ----------------------------------------------... |
def __updateJobResultsPeriodic(self):
"""
Periodic check to see if this is the best model. This should only have an
effect if this is the *first* model to report its progress
"""
if self._isBestModelStored and not self._isBestModel:
return
while True:
jobResultsStr = self._jobsDAO.j... |
def __checkIfBestCompletedModel(self):
"""
Reads the current "best model" for the job and returns whether or not the
current model is better than the "best model" stored for the job
Returns: (isBetter, storedBest, origResultsStr)
isBetter:
True if the current model is better than the stored ... |
def __updateJobResults(self):
""""
Check if this is the best model
If so:
1) Write it's checkpoint
2) Record this model as the best
3) Delete the previous best's output cache
Otherwise:
1) Delete our output cache
"""
isSaved = False
while True:
self._isBestMode... |
def _writePrediction(self, result):
"""
Writes the results of one iteration of a model. The results are written to
this ModelRunner's in-memory cache unless this model is the "best model" for
the job. If this model is the "best model", the predictions are written out
to a permanent store via a predi... |
def __flushPredictionCache(self):
"""
Writes the contents of this model's in-memory prediction cache to a permanent
store via the prediction output stream instance
"""
if not self.__predictionCache:
return
# Create an output store, if one doesn't exist already
if self._predictionLogg... |
def __deleteOutputCache(self, modelID):
"""
Delete's the output cache associated with the given modelID. This actually
clears up the resources associated with the cache, rather than deleting al
the records in the cache
Parameters:
----------------------------------------------------------------... |
def _initPeriodicActivities(self):
""" Creates and returns a PeriodicActivityMgr instance initialized with
our periodic activities
Parameters:
-------------------------------------------------------------------------
retval: a PeriodicActivityMgr instance
"""
# Activity to upda... |
def __checkCancelation(self):
""" Check if the cancelation flag has been set for this model
in the Model DB"""
# Update a hadoop job counter at least once every 600 seconds so it doesn't
# think our map task is dead
print >>sys.stderr, "reporter:counter:HypersearchWorker,numRecords,50"
# See ... |
def __checkMaturity(self):
""" Save the current metric value and see if the model's performance has
'leveled off.' We do this by looking at some number of previous number of
recordings """
if self._currentRecordIndex+1 < self._MIN_RECORDS_TO_BE_BEST:
return
# If we are already mature, don't ... |
def __setAsOrphaned(self):
"""
Sets the current model as orphaned. This is called when the scheduler is
about to kill the process to reallocate the worker to a different process.
"""
cmplReason = ClientJobsDAO.CMPL_REASON_ORPHAN
cmplMessage = "Killed by Scheduler"
self._jobsDAO.modelSetCompl... |
def readStateFromDB(self):
"""Set our state to that obtained from the engWorkerState field of the
job record.
Parameters:
---------------------------------------------------------------------
stateJSON: JSON encoded state from job record
"""
self._priorStateJSON = self._hsObj._cjDAO.jo... |
def writeStateToDB(self):
"""Update the state in the job record with our local changes (if any).
If we don't have the latest state in our priorStateJSON, then re-load
in the latest state and return False. If we were successful writing out
our changes, return True
Parameters:
-------------------... |
def getFieldContributions(self):
"""Return the field contributions statistics.
Parameters:
---------------------------------------------------------------------
retval: Dictionary where the keys are the field names and the values
are how much each field contributed to the best score.
... |
def getAllSwarms(self, sprintIdx):
"""Return the list of all swarms in the given sprint.
Parameters:
---------------------------------------------------------------------
retval: list of active swarm Ids in the given sprint
"""
swarmIds = []
for swarmId, info in self._state['swarms'].iter... |
def getCompletedSwarms(self):
"""Return the list of all completed swarms.
Parameters:
---------------------------------------------------------------------
retval: list of active swarm Ids
"""
swarmIds = []
for swarmId, info in self._state['swarms'].iteritems():
if info['status'] ==... |
def getCompletingSwarms(self):
"""Return the list of all completing swarms.
Parameters:
---------------------------------------------------------------------
retval: list of active swarm Ids
"""
swarmIds = []
for swarmId, info in self._state['swarms'].iteritems():
if info['status'] ... |
def bestModelInSprint(self, sprintIdx):
"""Return the best model ID and it's errScore from the given sprint,
which may still be in progress. This returns the best score from all models
in the sprint which have matured so far.
Parameters:
-------------------------------------------------------------... |
def setSwarmState(self, swarmId, newStatus):
"""Change the given swarm's state to 'newState'. If 'newState' is
'completed', then bestModelId and bestErrScore must be provided.
Parameters:
---------------------------------------------------------------------
swarmId: swarm Id
newStatus: ... |
def anyGoodSprintsActive(self):
"""Return True if there are any more good sprints still being explored.
A 'good' sprint is one that is earlier than where we detected an increase
in error from sprint to subsequent sprint.
"""
if self._state['lastGoodSprint'] is not None:
goodSprints = self._sta... |
def isSprintCompleted(self, sprintIdx):
"""Return True if the given sprint has completed."""
numExistingSprints = len(self._state['sprints'])
if sprintIdx >= numExistingSprints:
return False
return (self._state['sprints'][sprintIdx]['status'] == 'completed') |
def killUselessSwarms(self):
"""See if we can kill off some speculative swarms. If an earlier sprint
has finally completed, we can now tell which fields should *really* be present
in the sprints we've already started due to speculation, and kill off the
swarms that should not have been included.
"""... |
def isSprintActive(self, sprintIdx):
"""If the given sprint exists and is active, return active=True.
If the sprint does not exist yet, this call will create it (and return
active=True). If it already exists, but is completing or complete, return
active=False.
If sprintIdx is past the end of the p... |
def addEncoder(self, name, encoder):
"""
Adds one encoder.
:param name: (string) name of encoder, should be unique
:param encoder: (:class:`.Encoder`) the encoder to add
"""
self.encoders.append((name, encoder, self.width))
for d in encoder.getDescription():
self.description.append((d... |
def invariant(self):
"""Verify the validity of the node spec object
The type of each sub-object is verified and then
the validity of each node spec item is verified by calling
it invariant() method. It also makes sure that there is at most
one default input and one default output.
"""
# Ver... |
def toDict(self):
"""Convert the information of the node spec to a plain dict of basic types
The description and singleNodeOnly attributes are placed directly in
the result dicts. The inputs, outputs, parameters and commands dicts
contain Spec item objects (InputSpec, OutputSpec, etc). Each such object... |
def updateResultsForJob(self, forceUpdate=True):
""" Chooses the best model for a given job.
Parameters
-----------------------------------------------------------------------
forceUpdate: (True/False). If True, the update will ignore all the
restrictions on the minimum time to updat... |
def createEncoder():
"""Create the encoder instance for our test and return it."""
consumption_encoder = ScalarEncoder(21, 0.0, 100.0, n=50, name="consumption",
clipInput=True)
time_encoder = DateEncoder(timeOfDay=(21, 9.5), name="timestamp_timeOfDay")
encoder = MultiEncoder()
encoder.addEncoder("consu... |
def createNetwork(dataSource):
"""Create the Network instance.
The network has a sensor region reading data from `dataSource` and passing
the encoded representation to an SPRegion. The SPRegion output is passed to
a TMRegion.
:param dataSource: a RecordStream instance to get data from
:returns: a Network ... |
def runNetwork(network, writer):
"""Run the network and write output to writer.
:param network: a Network instance to run
:param writer: a csv.writer instance to write output to
"""
sensorRegion = network.regions["sensor"]
spatialPoolerRegion = network.regions["spatialPoolerRegion"]
temporalPoolerRegion ... |
def __validateExperimentControl(self, control):
""" Validates control dictionary for the experiment context"""
# Validate task list
taskList = control.get('tasks', None)
if taskList is not None:
taskLabelsList = []
for task in taskList:
validateOpfJsonValue(task, "opfTaskSchema.json... |
def normalizeStreamSource(self, stream):
"""
TODO: document
:param stream:
"""
# The stream source in the task might be in several formats, so we need
# to make sure it gets converted into an absolute path:
source = stream['source'][len(FILE_SCHEME):]
# If the source is already an absolu... |
def normalizeStreamSources(self):
"""
TODO: document
"""
task = dict(self.__control)
if 'dataset' in task:
for stream in task['dataset']['streams']:
self.normalizeStreamSource(stream)
else:
for subtask in task['tasks']:
for stream in subtask['dataset']['streams']:
... |
def convertNupicEnvToOPF(self):
"""
TODO: document
"""
# We need to create a task structure, most of which is taken verbatim
# from the Nupic control dict
task = dict(self.__control)
task.pop('environment')
inferenceArgs = task.pop('inferenceArgs')
task['taskLabel'] = 'DefaultTask'... |
def createNetwork(dataSource):
"""Create the Network instance.
The network has a sensor region reading data from `dataSource` and passing
the encoded representation to an Identity Region.
:param dataSource: a RecordStream instance to get data from
:returns: a Network instance ready to run
"""
network = ... |
def runNetwork(network, writer):
"""Run the network and write output to writer.
:param network: a Network instance to run
:param writer: a csv.writer instance to write output to
"""
identityRegion = network.regions["identityRegion"]
for i in xrange(_NUM_RECORDS):
# Run the network for a single iterati... |
def _appendReportKeys(keys, prefix, results):
"""
Generate a set of possible report keys for an experiment's results.
A report key is a string of key names separated by colons, each key being one
level deeper into the experiment results dict. For example, 'key1:key2'.
This routine is called recursively to bu... |
def _matchReportKeys(reportKeyREs=[], allReportKeys=[]):
"""
Extract all items from the 'allKeys' list whose key matches one of the regular
expressions passed in 'reportKeys'.
Parameters:
----------------------------------------------------------------------------
reportKeyREs: List of regular expressi... |
def _getReportItem(itemName, results):
"""
Get a specific item by name out of the results dict.
The format of itemName is a string of dictionary keys separated by colons,
each key being one level deeper into the results dict. For example,
'key1:key2' would fetch results['key1']['key2'].
If itemName is not... |
def filterResults(allResults, reportKeys, optimizeKey=None):
""" Given the complete set of results generated by an experiment (passed in
'results'), filter out and return only the ones the caller wants, as
specified through 'reportKeys' and 'optimizeKey'.
A report key is a string of key names separated by colo... |
def _handleModelRunnerException(jobID, modelID, jobsDAO, experimentDir, logger,
e):
""" Perform standard handling of an exception that occurs while running
a model.
Parameters:
-------------------------------------------------------------------------
jobID: ID f... |
def runModelGivenBaseAndParams(modelID, jobID, baseDescription, params,
predictedField, reportKeys, optimizeKey, jobsDAO,
modelCheckpointGUID, logLevel=None, predictionCacheMaxRecords=None):
""" This creates an experiment directory with a base.py description file
created from 'baseDescriptio... |
def rCopy(d, f=identityConversion, discardNoneKeys=True, deepCopy=True):
"""Recursively copies a dict and returns the result.
Args:
d: The dict to copy.
f: A function to apply to values when copying that takes the value and the
list of keys from the root of the dict to the value and returns a value... |
def rApply(d, f):
"""Recursively applies f to the values in dict d.
Args:
d: The dict to recurse over.
f: A function to apply to values in d that takes the value and a list of
keys from the root of the dict to the value.
"""
remainingDicts = [(d, ())]
while len(remainingDicts) > 0:
curren... |
def clippedObj(obj, maxElementSize=64):
"""
Return a clipped version of obj suitable for printing, This
is useful when generating log messages by printing data structures, but
don't want the message to be too long.
If passed in a dict, list, or namedtuple, each element of the structure's
string representat... |
def validate(value, **kwds):
""" Validate a python value against json schema:
validate(value, schemaPath)
validate(value, schemaDict)
value: python object to validate against the schema
The json schema may be specified either as a path of the file containing
the json schema or as a python diction... |
def loadJsonValueFromFile(inputFilePath):
""" Loads a json value from a file and converts it to the corresponding python
object.
inputFilePath:
Path of the json file;
Returns:
python value that represents the loaded json value
"""
with open(inputFilePath) as fileObj:
... |
def sortedJSONDumpS(obj):
"""
Return a JSON representation of obj with sorted keys on any embedded dicts.
This insures that the same object will always be represented by the same
string even if it contains dicts (where the sort order of the keys is
normally undefined).
"""
itemStrs = []
if isinstance(... |
def tick(self):
""" Activity tick handler; services all activities
Returns: True if controlling iterator says it's okay to keep going;
False to stop
"""
# Run activities whose time has come
for act in self.__activities:
if not act.iteratorHolder[0]:
continue
... |
def rUpdate(original, updates):
"""Recursively updates the values in original with the values from updates."""
# Keep a list of the sub-dictionaries that need to be updated to avoid having
# to use recursion (which could fail for dictionaries with a lot of nesting.
dictPairs = [(original, updates)]
while len(... |
def dictDiffAndReport(da, db):
""" Compares two python dictionaries at the top level and report differences,
if any, to stdout
da: first dictionary
db: second dictionary
Returns: The same value as returned by dictDiff() for the given args
"""
differences = dictDiff(da, db)... |
def dictDiff(da, db):
""" Compares two python dictionaries at the top level and return differences
da: first dictionary
db: second dictionary
Returns: None if dictionaries test equal; otherwise returns a
dictionary as follows:
{
... |
def _seed(self, seed=-1):
"""
Initialize the random seed
"""
if seed != -1:
self.random = NupicRandom(seed)
else:
self.random = NupicRandom() |
def _newRep(self):
"""Generate a new and unique representation. Returns a numpy array
of shape (n,). """
maxAttempts = 1000
for _ in xrange(maxAttempts):
foundUnique = True
population = numpy.arange(self.n, dtype=numpy.uint32)
choices = numpy.arange(self.w, dtype=numpy.uint32)
o... |
def getScalars(self, input):
""" See method description in base.py """
if input == SENTINEL_VALUE_FOR_MISSING_DATA:
return numpy.array([0])
index = self.categoryToIndex.get(input, None)
if index is None:
if self._learningEnabled:
self._addCategory(input)
index = self.ncate... |
def decode(self, encoded, parentFieldName=''):
""" See the function description in base.py
"""
assert (encoded[0:self.n] <= 1.0).all()
resultString = ""
resultRanges = []
overlaps = (self.sdrs * encoded[0:self.n]).sum(axis=1)
if self.verbosity >= 2:
print "Overlaps for decoding:"... |
def _getTopDownMapping(self):
""" Return the interal _topDownMappingM matrix used for handling the
bucketInfo() and topDownCompute() methods. This is a matrix, one row per
category (bucket) where each row contains the encoded output for that
category.
"""
# -------------------------------------... |
def getBucketInfo(self, buckets):
""" See the function description in base.py
"""
if self.ncategories==0:
return 0
topDownMappingM = self._getTopDownMapping()
categoryIndex = buckets[0]
category = self.categories[categoryIndex]
encoding = topDownMappingM.getRow(categoryIndex)
r... |
def topDownCompute(self, encoded):
""" See the function description in base.py
"""
if self.ncategories==0:
return 0
topDownMappingM = self._getTopDownMapping()
categoryIndex = topDownMappingM.rightVecProd(encoded).argmax()
category = self.categories[categoryIndex]
encoding = topDown... |
def getScalarNames(self, parentFieldName=''):
""" See method description in base.py """
names = []
# This forms a name which is the concatenation of the parentFieldName
# passed in and the encoder's own name.
def _formFieldName(encoder):
if parentFieldName == '':
return encoder.nam... |
def getEncodedValues(self, input):
""" See method description in base.py """
if input == SENTINEL_VALUE_FOR_MISSING_DATA:
return numpy.array([None])
assert isinstance(input, datetime.datetime)
values = []
# -------------------------------------------------------------------------
# Get ... |
def getBucketIndices(self, input):
""" See method description in base.py """
if input == SENTINEL_VALUE_FOR_MISSING_DATA:
# Encoder each sub-field
return [None] * len(self.encoders)
else:
assert isinstance(input, datetime.datetime)
# Get the scalar values for each sub-field
... |
def encodeIntoArray(self, input, output):
""" See method description in base.py """
if input == SENTINEL_VALUE_FOR_MISSING_DATA:
output[0:] = 0
else:
if not isinstance(input, datetime.datetime):
raise ValueError("Input is type %s, expected datetime. Value: %s" % (
type(input... |
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"... |
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"]
)
if encoder["type"] == "RandomDis... |
def addLabel(self, start, end, labelName):
"""
Add the label labelName to each record with record ROWID in range from
start to end, noninclusive of end.
This will recalculate all points from end to the last record stored in the
internal cache of this classifier.
"""
if len(self.saved_states... |
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 ... |
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... |
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... |
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... |
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,)),
... |
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_... |
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)
# Save new classification recor... |
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... |
def setAutoDetectThreshold(self, threshold):
"""
Sets the autoDetectThreshold.
TODO: Ensure previously classified points outside of classifier are valid.
"""
if not (isinstance(threshold, float) or isinstance(threshold, int)):
raise HTMPredictionModelInvalidArgument("Invalid argument type \'%s... |
def _getAdditionalSpecs(spatialImp, 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 _initializeEphemeralMembers(self):
"""
Initialize all ephemeral data members, and give the derived class the
opportunity to do the same by invoking the virtual member _initEphemerals(),
which is intended to be overridden.
NOTE: this is used by both __init__ and __setstate__ code paths.
"""
... |
def initialize(self):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.initialize`.
"""
# Zero out the spatial output in case it is requested
self._spatialPoolerOutput = numpy.zeros(self.columnCount,
dtype=GetNTAReal())
# Zero out the rf... |
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... |
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
"""
... |
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... |
def _doBottomUpCompute(self, rfInput, resetSignal):
"""
Do one iteration of inference and/or learning and return the result
Parameters:
--------------------------------------------
rfInput: Input vector. Shape is: (1, inputVectorLen).
resetSignal: True if reset is asserted
"""
#... |
def getBaseSpec(cls):
"""
Doesn't include the spatial, temporal and other parameters
:returns: (dict) The base Spec for SPRegion.
"""
spec = dict(
description=SPRegion.__doc__,
singleNodeOnly=True,
inputs=dict(
bottomUpIn=dict(
description="""The input vector."""... |
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()
s, o = _getAdditionalSpecs(s... |
def getParameter(self, parameterName, index=-1):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.getParameter`.
Most parameters are handled automatically by PyRegion's parameter get
mechanism. The ones that need special treatment are explicitly handled here.
"""
if parame... |
def setParameter(self, parameterName, index, parameterValue):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.setParameter`.
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 ex... |
def writeToProto(self, proto):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.writeToProto`.
Write state to proto object.
:param proto: SPRegionProto capnproto object
"""
proto.spatialImp = self.spatialImp
proto.columnCount = self.columnCount
proto.inputWidth = self.inp... |
def readFromProto(cls, proto):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.readFromProto`.
Read state from proto object.
:param proto: SPRegionProto capnproto object
"""
instance = cls(proto.columnCount, proto.inputWidth)
instance.spatialImp = proto.spatialImp
i... |
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 = ... |
def getParameterArrayCount(self, name, index):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.getParameterArrayCount`.
TODO: as a temporary hack, getParameterArrayCount checks to see if there's a
variable, private or not, with that name. If so, it returns the value of the
variable.
... |
def getParameterArray(self, name, index, a):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.getParameterArray`.
TODO: as a temporary hack, getParameterArray checks to see if there's a
variable, private or not, with that name. If so, it returns the value of the
variable.
"""
... |
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... |
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 == 'tm_py':
return backtracking_tm_shim.TMShi... |
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.