INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Retrives the optimization key name and optimization function. | def getOptimizationMetricInfo(cls, searchJobParams):
"""Retrives the optimization key name and optimization function.
Parameters:
---------------------------------------------------------
searchJobParams:
Parameter for passing as the searchParams arg to
Hypersear... |
Parameters: ---------------------------------------------------------------------- retval: Printable description of the model. | def getModelDescription(self):
"""
Parameters:
----------------------------------------------------------------------
retval: Printable description of the model.
"""
params = self.__unwrapParams()
if "experimentName" in params:
return params["experimentName"]
else:
... |
Parameters: ---------------------------------------------------------------------- retval: a dictionary of model parameter labels. For each entry the key is the name of the parameter and the value is the value chosen for it. | def getParamLabels(self):
"""
Parameters:
----------------------------------------------------------------------
retval: a dictionary of model parameter labels. For each entry
the key is the name of the parameter and the value
is the value chosen for it.
... |
Unwraps self. __rawInfo. params into the equivalent python dictionary and caches it in self. __cachedParams. Returns the unwrapped params | def __unwrapParams(self):
"""Unwraps self.__rawInfo.params into the equivalent python dictionary
and caches it in self.__cachedParams. Returns the unwrapped params
Parameters:
----------------------------------------------------------------------
retval: Model params dictionary as correpson... |
Retrives a dictionary of metrics that combines all report and optimization metrics | def getAllMetrics(self):
"""Retrives a dictionary of metrics that combines all report and
optimization metrics
Parameters:
----------------------------------------------------------------------
retval: a dictionary of optimization metrics that were collected
for the mode... |
Unwraps self. __rawInfo. results and caches it in self. __cachedResults ; Returns the unwrapped params | def __unwrapResults(self):
"""Unwraps self.__rawInfo.results and caches it in self.__cachedResults;
Returns the unwrapped params
Parameters:
----------------------------------------------------------------------
retval: ModelResults namedtuple instance
"""
if self.__cachedResults is... |
Returns the next n values for the distribution as a list. | def getData(self, n):
"""Returns the next n values for the distribution as a list."""
records = [self.getNext() for x in range(n)]
return records |
Returns the periodic checks to see if the model should continue running. | def getTerminationCallbacks(self, terminationFunc):
""" Returns the periodic checks to see if the model should
continue running.
Parameters:
-----------------------------------------------------------------------
terminationFunc: The function that will be called in the model main loop
... |
Like itertools. groupby with the following additions: | def groupby2(*args):
""" Like itertools.groupby, with the following additions:
- Supports multiple sequences. Instead of returning (k, g), each iteration
returns (k, g0, g1, ...), with one `g` for each input sequence. The value of
each `g` is either a non-empty iterator or `None`.
- It treats the value `... |
Open the underlying file stream This only supports file:// prefixed paths. | def _openStream(dataUrl,
isBlocking, # pylint: disable=W0613
maxTimeout, # pylint: disable=W0613
bookmark,
firstRecordIdx):
"""Open the underlying file stream
This only supports 'file://' prefixed paths.
:returns: record stream insta... |
Returns combined data from all sources ( values only ). | def getNextRecord(self):
""" Returns combined data from all sources (values only).
:returns: None on EOF; empty sequence on timeout.
"""
# Keep reading from the raw input till we get enough for an aggregated
# record
while True:
# Reached EOF due to lastRow constraint?
if self._... |
Iterates through stream to calculate total records after aggregation. This will alter the bookmark state. | def getDataRowCount(self):
"""
Iterates through stream to calculate total records after aggregation.
This will alter the bookmark state.
"""
inputRowCountAfterAggregation = 0
while True:
record = self.getNextRecord()
if record is None:
return inputRowCountAfterAggregation
... |
TODO: This method needs to be enhanced to get the stats on the * aggregated * records. | def getStats(self):
"""
TODO: This method needs to be enhanced to get the stats on the *aggregated*
records.
:returns: stats (like min and max values of the fields).
"""
# The record store returns a dict of stats, each value in this dict is
# a list with one item per field of the record s... |
Return a pattern for a number. | def get(self, number):
"""
Return a pattern for a number.
@param number (int) Number of pattern
@return (set) Indices of on bits
"""
if not number in self._patterns:
raise IndexError("Invalid number")
return self._patterns[number] |
Add noise to pattern. | def addNoise(self, bits, amount):
"""
Add noise to pattern.
@param bits (set) Indices of on bits
@param amount (float) Probability of switching an on bit with a random bit
@return (set) Indices of on bits in noisy pattern
"""
newBits = set()
for bit in bits:
if self._random.... |
Return the set of pattern numbers that match a bit. | def numbersForBit(self, bit):
"""
Return the set of pattern numbers that match a bit.
@param bit (int) Index of bit
@return (set) Indices of numbers
"""
if bit >= self._n:
raise IndexError("Invalid bit")
numbers = set()
for index, pattern in self._patterns.iteritems():
if... |
Return a map from number to matching on bits for all numbers that match a set of bits. | def numberMapForBits(self, bits):
"""
Return a map from number to matching on bits,
for all numbers that match a set of bits.
@param bits (set) Indices of bits
@return (dict) Mapping from number => on bits.
"""
numberMap = dict()
for bit in bits:
numbers = self.numbersForBit(bit... |
Pretty print a pattern. | def prettyPrintPattern(self, bits, verbosity=1):
"""
Pretty print a pattern.
@param bits (set) Indices of on bits
@param verbosity (int) Verbosity level
@return (string) Pretty-printed text
"""
numberMap = self.numberMapForBits(bits)
text = ""
numberList = []
numberItems ... |
Generates set of random patterns. | def _generate(self):
"""
Generates set of random patterns.
"""
candidates = np.array(range(self._n), np.uint32)
for i in xrange(self._num):
self._random.shuffle(candidates)
pattern = candidates[0:self._getW()]
self._patterns[i] = set(pattern) |
Gets a value of w for use in generating a pattern. | def _getW(self):
"""
Gets a value of `w` for use in generating a pattern.
"""
w = self._w
if type(w) is list:
return w[self._random.getUInt32(len(w))]
else:
return w |
Generates set of consecutive patterns. | def _generate(self):
"""
Generates set of consecutive patterns.
"""
n = self._n
w = self._w
assert type(w) is int, "List for w not supported"
for i in xrange(n / w):
pattern = set(xrange(i * w, (i+1) * w))
self._patterns[i] = pattern |
Process one input sample. | def compute(self, recordNum, patternNZ, classification, learn, infer):
"""
Process one input sample.
This method is called by outer loop code outside the nupic-engine. We
use this instead of the nupic engine compute() because our inputs and
outputs aren't fixed size vectors of reals.
:param r... |
Return the inference value from one input sample. The actual learning happens in compute (). | def infer(self, patternNZ, actValueList):
"""
Return the inference value from one input sample. The actual
learning happens in compute().
:param patternNZ: list of the active indices from the output below
:param classification: dict of the classification information:
bucketIdx: ... |
Perform inference for a single step. Given an SDR input and a weight matrix return a predicted distribution. | def inferSingleStep(self, patternNZ, weightMatrix):
"""
Perform inference for a single step. Given an SDR input and a weight
matrix, return a predicted distribution.
:param patternNZ: list of the active indices from the output below
:param weightMatrix: numpy array of the weight matrix
:return:... |
Calculate error signal | def _calculateError(self, recordNum, bucketIdxList):
"""
Calculate error signal
:param bucketIdxList: list of encoder buckets
:return: dict containing error. The key is the number of steps
The value is a numpy array of error at the output layer
"""
error = dict()
targetDist = ... |
Sort a potentially big file | def sort(filename, key, outputFile, fields=None, watermark=1024 * 1024 * 100):
"""Sort a potentially big file
filename - the input file (standard File format)
key - a list of field names to sort by
outputFile - the name of the output file
fields - a list of fields that should be included (all fields if None)... |
Sort in memory chunk of records | def _sortChunk(records, key, chunkIndex, fields):
"""Sort in memory chunk of records
records - a list of records read from the original dataset
key - a list of indices to sort the records by
chunkIndex - the index of the current chunk
The records contain only the fields requested by the user.
_sortChunk(... |
Merge sorted chunk files into a sorted output file | def _mergeFiles(key, chunkCount, outputFile, fields):
"""Merge sorted chunk files into a sorted output file
chunkCount - the number of available chunk files
outputFile the name of the sorted output file
_mergeFiles()
"""
title()
# Open all chun files
files = [FileRecordStream('chunk_%d.csv' % i) for... |
Feeds input record through TM performing inference and learning. Updates member variables with new state. | def compute(self, activeColumns, learn=True):
"""
Feeds input record through TM, performing inference and learning.
Updates member variables with new state.
@param activeColumns (set) Indices of active columns in `t`
"""
bottomUpInput = numpy.zeros(self.numberOfCols, dtype=dtype)
bottomUpIn... |
Deserialize from proto instance. | def read(cls, proto):
"""Deserialize from proto instance.
:param proto: (TemporalMemoryShimProto) the proto instance to read from
"""
tm = super(TemporalMemoryShim, cls).read(proto.baseTM)
tm.predictiveCells = set(proto.predictedState)
tm.connections = Connections.read(proto.conncetions) |
Populate serialization proto instance. | def write(self, proto):
"""Populate serialization proto instance.
:param proto: (TemporalMemoryShimProto) the proto instance to populate
"""
super(TemporalMemoryShim, self).write(proto.baseTM)
proto.connections.write(self.connections)
proto.predictiveCells = self.predictiveCells |
Print a message to the console. | def cPrint(self, level, message, *args, **kw):
"""Print a message to the console.
Prints only if level <= self.consolePrinterVerbosity
Printing with level 0 is equivalent to using a print statement,
and should normally be avoided.
:param level: (int) indicating the urgency of the message with
... |
profiling performance of TemporalMemory ( TM ) using the python cProfile module and ordered by cumulative time see how to run on command - line above. | def profileTM(tmClass, tmDim, nRuns):
"""
profiling performance of TemporalMemory (TM)
using the python cProfile module and ordered by cumulative time,
see how to run on command-line above.
@param tmClass implementation of TM (cpp, py, ..)
@param tmDim number of columns in TM
@param nRuns number of calls... |
The main function of the RunPermutations utility. This utility will automatically generate and run multiple prediction framework experiments that are permutations of a base experiment via the Grok engine. For example if you have an experiment that you want to test with 3 possible values of variable A and 2 possible val... | def runPermutations(args):
"""
The main function of the RunPermutations utility.
This utility will automatically generate and run multiple prediction framework
experiments that are permutations of a base experiment via the Grok engine.
For example, if you have an experiment that you want to test with 3 possib... |
Generate a simple dataset. This contains a bunch of non - overlapping sequences. Parameters: ---------------------------------------------------- filename: name of the file to produce including extension. It will be created in a datasets sub - directory within the directory containing this script. numSequences: how man... | def _generateCategory(filename="simple.csv", numSequences=2, elementsPerSeq=1,
numRepeats=10, resets=False):
""" Generate a simple dataset. This contains a bunch of non-overlapping
sequences.
Parameters:
----------------------------------------------------
filename: name of the ... |
See nupic. encoders. base. Encoder for more information. | def encodeIntoArray(self, inputData, output):
"""
See `nupic.encoders.base.Encoder` for more information.
:param: inputData (tuple) Contains speed (float), longitude (float),
latitude (float), altitude (float)
:param: output (numpy.array) Stores encoded SDR in this numpy ar... |
Returns coordinate for given GPS position. | def coordinateForPosition(self, longitude, latitude, altitude=None):
"""
Returns coordinate for given GPS position.
:param: longitude (float) Longitude of position
:param: latitude (float) Latitude of position
:param: altitude (float) Altitude of position
:returns: (numpy.array) Coordinate that... |
Returns radius for given speed. | def radiusForSpeed(self, speed):
"""
Returns radius for given speed.
Tries to get the encodings of consecutive readings to be
adjacent with some overlap.
:param: speed (float) Speed (in meters per second)
:returns: (int) Radius for given speed
"""
overlap = 1.5
coordinatesPerTimest... |
This method returns search description. See the following file for the schema of the dictionary this method returns: py/ nupic/ swarming/ exp_generator/ experimentDescriptionSchema. json The streamDef element defines the stream for this model. The schema for this element can be found at: py/ nupicengine/ cluster/ datab... | def getSearch(rootDir):
""" This method returns search description. See the following file for the
schema of the dictionary this method returns:
py/nupic/swarming/exp_generator/experimentDescriptionSchema.json
The streamDef element defines the stream for this model. The schema for this
element can be f... |
See method description in base. py | def encodeIntoArray(self, value, output):
""" See method description in base.py """
denseInput = numpy.zeros(output.shape)
try:
denseInput[value] = 1
except IndexError:
if isinstance(value, numpy.ndarray):
raise ValueError(
"Numpy array must have integer dtype but got {}"... |
Read serialized object from file. | def readFromFile(cls, f, packed=True):
"""
Read serialized object from file.
:param f: input file
:param packed: If true, will assume content is packed
:return: first-class instance initialized from proto obj
"""
# Get capnproto schema from instance
schema = cls.getSchema()
# Read ... |
Write serialized object to file. | def writeToFile(self, f, packed=True):
"""
Write serialized object to file.
:param f: output file
:param packed: If true, will pack contents.
"""
# Get capnproto schema from instance
schema = self.getSchema()
# Construct new message, otherwise refered to as `proto`
proto = schema.n... |
: param proto: capnp TwoGramModelProto message reader | def read(cls, proto):
"""
:param proto: capnp TwoGramModelProto message reader
"""
instance = object.__new__(cls)
super(TwoGramModel, instance).__init__(proto=proto.modelBase)
instance._logger = opf_utils.initLogger(instance)
instance._reset = proto.reset
instance._hashToValueDict = {x... |
: param proto: capnp TwoGramModelProto message builder | def write(self, proto):
"""
:param proto: capnp TwoGramModelProto message builder
"""
super(TwoGramModel, self).writeBaseToProto(proto.modelBase)
proto.reset = self._reset
proto.learningEnabled = self._learningEnabled
proto.prevValues = self._prevValues
self._encoder.write(proto.encoder... |
Decorator for functions that require anomaly models. | def requireAnomalyModel(func):
"""
Decorator for functions that require anomaly models.
"""
@wraps(func)
def _decorator(self, *args, **kwargs):
if not self.getInferenceType() == InferenceType.TemporalAnomaly:
raise RuntimeError("Method required a TemporalAnomaly model.")
if self._getAnomalyClass... |
Remove labels from the anomaly classifier within this model. Removes all records if labelFilter == None otherwise only removes the labels equal to labelFilter. | def anomalyRemoveLabels(self, start, end, labelFilter):
"""
Remove labels from the anomaly classifier within this model. Removes all
records if ``labelFilter==None``, otherwise only removes the labels equal to
``labelFilter``.
:param start: (int) index to start removing labels
:param end: (int)... |
Add labels from the anomaly classifier within this model. | def anomalyAddLabel(self, start, end, labelName):
"""
Add labels from the anomaly classifier within this model.
:param start: (int) index to start label
:param end: (int) index to end label
:param labelName: (string) name of label
"""
self._getAnomalyClassifier().getSelf().addLabel(start, e... |
Get labels from the anomaly classifier within this model. | def anomalyGetLabels(self, start, end):
"""
Get labels from the anomaly classifier within this model.
:param start: (int) index to start getting labels
:param end: (int) index to end getting labels
"""
return self._getAnomalyClassifier().getSelf().getLabels(start, end) |
inputRecord - dict containing the input to the sensor | def _getSensorInputRecord(self, inputRecord):
"""
inputRecord - dict containing the input to the sensor
Return a 'SensorInput' object, which represents the 'parsed'
representation of the input record
"""
sensor = self._getSensorRegion()
dataRow = copy.deepcopy(sensor.getSelf().getOutputValu... |
inputRecord - dict containing the input to the sensor | def _getClassifierInputRecord(self, inputRecord):
"""
inputRecord - dict containing the input to the sensor
Return a 'ClassifierInput' object, which contains the mapped
bucket index for input Record
"""
absoluteValue = None
bucketIdx = None
if self._predictedFieldName is not None and s... |
Compute Anomaly score if required | def _anomalyCompute(self):
"""
Compute Anomaly score, if required
"""
inferenceType = self.getInferenceType()
inferences = {}
sp = self._getSPRegion()
score = None
if inferenceType == InferenceType.NontemporalAnomaly:
score = sp.getOutputData("anomalyScore")[0] #TODO move from SP ... |
Handle the CLA Classifier compute logic when implementing multi - step prediction. This is where the patternNZ is associated with one of the other fields from the dataset 0 to N steps in the future. This method is used by each type of network ( encoder only SP only SP + TM ) to handle the compute logic through the CLA ... | def _handleSDRClassifierMultiStep(self, patternNZ,
inputTSRecordIdx,
rawInput):
""" Handle the CLA Classifier compute logic when implementing multi-step
prediction. This is where the patternNZ is associated with one of the
other fields ... |
Remove entries with 0 likelihood or likelihood less than minLikelihoodThreshold but don t leave an empty dict. | def _removeUnlikelyPredictions(cls, likelihoodsDict, minLikelihoodThreshold,
maxPredictionsPerStep):
"""Remove entries with 0 likelihood or likelihood less than
minLikelihoodThreshold, but don't leave an empty dict.
"""
maxVal = (None, None)
for (k, v) in likelihoods... |
Only returns data for a stat called numRunCalls.: return: | def getRuntimeStats(self):
"""
Only returns data for a stat called ``numRunCalls``.
:return:
"""
ret = {"numRunCalls" : self.__numRunCalls}
#--------------------------------------------------
# Query temporal network stats
temporalStats = dict()
if self._hasTP:
for stat in sel... |
Returns reference to the network s Classifier region | def _getClassifierRegion(self):
"""
Returns reference to the network's Classifier region
"""
if (self._netInfo.net is not None and
"Classifier" in self._netInfo.net.regions):
return self._netInfo.net.regions["Classifier"]
else:
return None |
Create a CLA network and return it. | def __createHTMNetwork(self, sensorParams, spEnable, spParams, tmEnable,
tmParams, clEnable, clParams, anomalyParams):
""" Create a CLA network and return it.
description: HTMPredictionModel description dictionary (TODO: define schema)
Returns: NetworkInfo instance;
"""
... |
: param proto: capnp HTMPredictionModelProto message builder | def write(self, proto):
"""
:param proto: capnp HTMPredictionModelProto message builder
"""
super(HTMPredictionModel, self).writeBaseToProto(proto.modelBase)
proto.numRunCalls = self.__numRunCalls
proto.minLikelihoodThreshold = self._minLikelihoodThreshold
proto.maxPredictionsPerStep = self... |
: param proto: capnp HTMPredictionModelProto message reader | def read(cls, proto):
"""
:param proto: capnp HTMPredictionModelProto message reader
"""
obj = object.__new__(cls)
# model.capnp
super(HTMPredictionModel, obj).__init__(proto=proto.modelBase)
# HTMPredictionModelProto.capnp
obj._minLikelihoodThreshold = round(proto.minLikelihoodThreshol... |
[ virtual method override ] This method is called during serialization with an external directory path that can be used to bypass pickle for saving large binary states. | def _serializeExtraData(self, extraDataDir):
""" [virtual method override] This method is called during serialization
with an external directory path that can be used to bypass pickle for saving
large binary states.
extraDataDir:
Model's extra data directory path
"""
makeDirec... |
[ virtual method override ] This method is called during deserialization ( after __setstate__ ) with an external directory path that can be used to bypass pickle for loading large binary states. | def _deSerializeExtraData(self, extraDataDir):
""" [virtual method override] This method is called during deserialization
(after __setstate__) with an external directory path that can be used to
bypass pickle for loading large binary states.
extraDataDir:
Model's extra data directory ... |
Attaches an AnomalyClassifier region to the network. Will remove current AnomalyClassifier region if it exists. | def _addAnomalyClassifierRegion(self, network, params, spEnable, tmEnable):
"""
Attaches an 'AnomalyClassifier' region to the network. Will remove current
'AnomalyClassifier' region if it exists.
Parameters
-----------
network - network to add the AnomalyClassifier region
params - parameter... |
extraDataDir: Model s extra data directory path Returns: Absolute directory path for saving CLA Network | def __getNetworkStateDirectory(self, extraDataDir):
"""
extraDataDir:
Model's extra data directory path
Returns: Absolute directory path for saving CLA Network
"""
if self.__restoringFromV1:
if self.getInferenceType() == InferenceType.TemporalNextStep:
leafName =... |
Mangles the given mangled ( private ) member name ; a mangled member name is one whose name begins with two or more underscores and ends with one or zero underscores. | def __manglePrivateMemberName(self, privateMemberName, skipCheck=False):
""" Mangles the given mangled (private) member name; a mangled member name
is one whose name begins with two or more underscores and ends with one
or zero underscores.
privateMemberName:
The private member name (... |
Set the radius resolution and range. These values are updated when minval and/ or maxval change. | def _setEncoderParams(self):
"""
Set the radius, resolution and range. These values are updated when minval
and/or maxval change.
"""
self.rangeInternal = float(self.maxval - self.minval)
self.resolution = float(self.rangeInternal) / (self.n - self.w)
self.radius = self.w * self.resolution... |
TODO: document | def setFieldStats(self, fieldName, fieldStats):
"""
TODO: document
"""
#If the stats are not fully formed, ignore.
if fieldStats[fieldName]['min'] == None or \
fieldStats[fieldName]['max'] == None:
return
self.minval = fieldStats[fieldName]['min']
self.maxval = fieldStats[field... |
Potentially change the minval and maxval using input. ** The learn flag is currently not supported by cla regions. ** | def _setMinAndMax(self, input, learn):
"""
Potentially change the minval and maxval using input.
**The learn flag is currently not supported by cla regions.**
"""
self.slidingWindow.next(input)
if self.minval is None and self.maxval is None:
self.minval = input
self.maxval = input+... |
[ overrides nupic. encoders. scalar. ScalarEncoder. getBucketIndices ] | def getBucketIndices(self, input, learn=None):
"""
[overrides nupic.encoders.scalar.ScalarEncoder.getBucketIndices]
"""
self.recordNum +=1
if learn is None:
learn = self._learningEnabled
if type(input) is float and math.isnan(input):
input = SENTINEL_VALUE_FOR_MISSING_DATA
if ... |
[ overrides nupic. encoders. scalar. ScalarEncoder. encodeIntoArray ] | def encodeIntoArray(self, input, output,learn=None):
"""
[overrides nupic.encoders.scalar.ScalarEncoder.encodeIntoArray]
"""
self.recordNum +=1
if learn is None:
learn = self._learningEnabled
if input == SENTINEL_VALUE_FOR_MISSING_DATA:
output[0:self.n] = 0
elif not math.isnan... |
[ overrides nupic. encoders. scalar. ScalarEncoder. getBucketInfo ] | def getBucketInfo(self, buckets):
"""
[overrides nupic.encoders.scalar.ScalarEncoder.getBucketInfo]
"""
if self.minval is None or self.maxval is None:
return [EncoderResult(value=0, scalar=0,
encoding=numpy.zeros(self.n))]
return super(AdaptiveScalarEncoder, self).... |
[ overrides nupic. encoders. scalar. ScalarEncoder. topDownCompute ] | def topDownCompute(self, encoded):
"""
[overrides nupic.encoders.scalar.ScalarEncoder.topDownCompute]
"""
if self.minval is None or self.maxval is None:
return [EncoderResult(value=0, scalar=0,
encoding=numpy.zeros(self.n))]
return super(AdaptiveScalarEncoder, self)... |
Record the best score for a swarm s generation index ( x ) Returns list of swarmIds to terminate. | def recordDataPoint(self, swarmId, generation, errScore):
"""Record the best score for a swarm's generation index (x)
Returns list of swarmIds to terminate.
"""
terminatedSwarms = []
# Append score to existing swarm.
if swarmId in self.swarmScores:
entry = self.swarmScores[swarmId]
... |
See comments in base class. | def getState(self):
"""See comments in base class."""
return dict(_position = self._position,
position = self.getPosition(),
velocity = self._velocity,
bestPosition = self._bestPosition,
bestResult = self._bestResult) |
See comments in base class. | def setState(self, state):
"""See comments in base class."""
self._position = state['_position']
self._velocity = state['velocity']
self._bestPosition = state['bestPosition']
self._bestResult = state['bestResult'] |
See comments in base class. | def getPosition(self):
"""See comments in base class."""
if self.stepSize is None:
return self._position
# Find nearest step
numSteps = (self._position - self.min) / self.stepSize
numSteps = int(round(numSteps))
position = self.min + (numSteps * self.stepSize)
position = max(self.min... |
See comments in base class. | def agitate(self):
"""See comments in base class."""
# Increase velocity enough that it will be higher the next time
# newPosition() is called. We know that newPosition multiplies by inertia,
# so take that into account.
self._velocity *= 1.5 / self._inertia
# Clip velocity
maxV = (self.max... |
See comments in base class. | def newPosition(self, globalBestPosition, rng):
"""See comments in base class."""
# First, update the velocity. The new velocity is given as:
# v = (inertia * v) + (cogRate * r1 * (localBest-pos))
# + (socRate * r2 * (globalBest-pos))
#
# where r1 and r2 are random numbers be... |
See comments in base class. | def pushAwayFrom(self, otherPositions, rng):
"""See comments in base class."""
# If min and max are the same, nothing to do
if self.max == self.min:
return
# How many potential other positions to evaluate?
numPositions = len(otherPositions) * 4
if numPositions == 0:
return
# As... |
See comments in base class. | def resetVelocity(self, rng):
"""See comments in base class."""
maxVelocity = (self.max - self.min) / 5.0
self._velocity = maxVelocity #min(abs(self._velocity), maxVelocity)
self._velocity *= rng.choice([1, -1]) |
See comments in base class. | def getPosition(self):
"""See comments in base class."""
position = super(PermuteInt, self).getPosition()
position = int(round(position))
return position |
See comments in base class. | def getState(self):
"""See comments in base class."""
return dict(_position = self.getPosition(),
position = self.getPosition(),
velocity = None,
bestPosition = self.choices[self._bestPositionIdx],
bestResult = self._bestResult) |
See comments in base class. | def setState(self, state):
"""See comments in base class."""
self._positionIdx = self.choices.index(state['_position'])
self._bestPositionIdx = self.choices.index(state['bestPosition'])
self._bestResult = state['bestResult'] |
Setup our resultsPerChoice history based on the passed in resultsPerChoice. | def setResultsPerChoice(self, resultsPerChoice):
"""Setup our resultsPerChoice history based on the passed in
resultsPerChoice.
For example, if this variable has the following choices:
['a', 'b', 'c']
resultsPerChoice will have up to 3 elements, each element is a tuple
containing (choiceValu... |
See comments in base class. | def newPosition(self, globalBestPosition, rng):
"""See comments in base class."""
# Compute the mean score per choice.
numChoices = len(self.choices)
meanScorePerChoice = []
overallSum = 0
numResults = 0
for i in range(numChoices):
if len(self._resultsPerChoice[i]) > 0:
data =... |
See comments in base class. | def pushAwayFrom(self, otherPositions, rng):
"""See comments in base class."""
# Get the count of how many in each position
positions = [self.choices.index(x) for x in otherPositions]
positionCounts = [0] * len(self.choices)
for pos in positions:
positionCounts[pos] += 1
self._positionId... |
Return a dict that can be used to construct this encoder. This dict can be passed directly to the addMultipleEncoders () method of the multi encoder. | def getDict(self, encoderName, flattenedChosenValues):
""" Return a dict that can be used to construct this encoder. This dict
can be passed directly to the addMultipleEncoders() method of the
multi encoder.
Parameters:
----------------------------------------------------------------------
enco... |
Translates the given metrics value to JSON string | def _translateMetricsToJSON(self, metrics, label):
""" Translates the given metrics value to JSON string
metrics: A list of dictionaries per OPFTaskDriver.getMetrics():
Returns: JSON string representing the given metrics object.
"""
# Transcode the MetricValueElement values into JSO... |
Open the data file and write the header row | def __openDatafile(self, modelResult):
"""Open the data file and write the header row"""
# Write reset bit
resetFieldMeta = FieldMetaInfo(
name="reset",
type=FieldMetaType.integer,
special = FieldMetaSpecial.reset)
self.__outputFieldsMeta.append(resetFieldMeta)
# --------------... |
Tell the writer which metrics should be written | def setLoggedMetrics(self, metricNames):
""" Tell the writer which metrics should be written
Parameters:
-----------------------------------------------------------------------
metricsNames: A list of metric lables to be written
"""
if metricNames is None:
self.__metricNames = set([])
... |
Get field metadata information for inferences that are of list type TODO: Right now we assume list inferences are associated with the input field metadata | def __getListMetaInfo(self, inferenceElement):
""" Get field metadata information for inferences that are of list type
TODO: Right now we assume list inferences are associated with the input field
metadata
"""
fieldMetaInfo = []
inferenceLabel = InferenceElement.getLabel(inferenceElement)
f... |
Get field metadate information for inferences that are of dict type | def __getDictMetaInfo(self, inferenceElement, inferenceDict):
"""Get field metadate information for inferences that are of dict type"""
fieldMetaInfo = []
inferenceLabel = InferenceElement.getLabel(inferenceElement)
if InferenceElement.getInputElement(inferenceElement):
fieldMetaInfo.append(Field... |
[ virtual method override ] Emits a single prediction as input versus predicted. | def append(self, modelResult):
""" [virtual method override] Emits a single prediction as input versus
predicted.
modelResult: An opf_utils.ModelResult object that contains the model input
and output for the current timestep.
"""
#print "DEBUG: _BasicPredictionWriter: writin... |
[ virtual method override ] Save a checkpoint of the prediction output stream. The checkpoint comprises up to maxRows of the most recent inference records. | def checkpoint(self, checkpointSink, maxRows):
""" [virtual method override] Save a checkpoint of the prediction output
stream. The checkpoint comprises up to maxRows of the most recent inference
records.
Parameters:
----------------------------------------------------------------------
checkpo... |
Queue up the T ( i + 1 ) prediction value and emit a T ( i ) input/ prediction pair if possible. E. g. if the previous T ( i - 1 ) iteration was learn - only then we would not have a T ( i ) prediction in our FIFO and would not be able to emit a meaningful input/ prediction pair. | def update(self, modelResult):
""" Queue up the T(i+1) prediction value and emit a T(i)
input/prediction pair, if possible. E.g., if the previous T(i-1)
iteration was learn-only, then we would not have a T(i) prediction in our
FIFO and would not be able to emit a meaningful input/prediction
pair.
... |
Creates the inference output directory for the given experiment | def createExperimentInferenceDir(cls, experimentDir):
""" Creates the inference output directory for the given experiment
experimentDir: experiment directory path that contains description.py
Returns: path of the inference output directory
"""
path = cls.getExperimentInferenceDirPath(experimentD... |
Generate the initial first order and second order transition probabilities for model0. For this model we generate the following set of sequences: 1 - 2 - 3 ( 4X ) 1 - 2 - 4 ( 1X ) 5 - 2 - 3 ( 1X ) 5 - 2 - 4 ( 4X ) Parameters: ---------------------------------------------------------------------- numCategories: Number o... | def _generateModel0(numCategories):
""" Generate the initial, first order, and second order transition
probabilities for 'model0'. For this model, we generate the following
set of sequences:
1-2-3 (4X)
1-2-4 (1X)
5-2-3 (1X)
5-2-4 (4X)
Parameters:
--------------------------------------... |
Generate the initial first order and second order transition probabilities for model1. For this model we generate the following set of sequences: 0 - 10 - 15 ( 1X ) 0 - 11 - 16 ( 1X ) 0 - 12 - 17 ( 1X ) 0 - 13 - 18 ( 1X ) 0 - 14 - 19 ( 1X ) | def _generateModel1(numCategories):
""" Generate the initial, first order, and second order transition
probabilities for 'model1'. For this model, we generate the following
set of sequences:
0-10-15 (1X)
0-11-16 (1X)
0-12-17 (1X)
0-13-18 (1X)
0-14-19 (1X)
1-10-20 (1X)
1-11-21 (1X)
1-12-22 (1X)... |
Generate the initial first order and second order transition probabilities for model2. For this model we generate peaked random transitions using dirichlet distributions. Parameters: ---------------------------------------------------------------------- numCategories: Number of categories alpha: Determines the peakedne... | def _generateModel2(numCategories, alpha=0.25):
""" Generate the initial, first order, and second order transition
probabilities for 'model2'. For this model, we generate peaked random
transitions using dirichlet distributions.
Parameters:
-----------------------------------------------------------------... |
Generate a set of records reflecting a set of probabilities. Parameters: ---------------------------------------------------------------- filename: name of. csv file to generate numRecords: number of records to generate categoryList: list of category names initProb: Initial probability for each category. This is a vect... | def _generateFile(filename, numRecords, categoryList, initProb,
firstOrderProb, secondOrderProb, seqLen, numNoise=0, resetsEvery=None):
""" Generate a set of records reflecting a set of probabilities.
Parameters:
----------------------------------------------------------------
filename: name o... |
A decorator that maintains the attribute lock state of an object | def _allow_new_attributes(f):
"""A decorator that maintains the attribute lock state of an object
It coperates with the LockAttributesMetaclass (see bellow) that replaces
the __setattr__ method with a custom one that checks the _canAddAttributes
counter and allows setting new attributes only if _canAddAttribut... |
trivial init method that just calls base class s __init__ () | def _simple_init(self, *args, **kw):
"""trivial init method that just calls base class's __init__()
This method is attached to classes that don't define __init__(). It is needed
because LockAttributesMetaclass must decorate the __init__() method of
its target class.
"""
type(self).__base__.__init__(self, *... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.