Search is not available for this dataset
text stringlengths 75 104k |
|---|
def getOptimizationMetricInfo(cls, searchJobParams):
"""Retrives the optimization key name and optimization function.
Parameters:
---------------------------------------------------------
searchJobParams:
Parameter for passing as the searchParams arg to
Hypersear... |
def getModelDescription(self):
"""
Parameters:
----------------------------------------------------------------------
retval: Printable description of the model.
"""
params = self.__unwrapParams()
if "experimentName" in params:
return params["experimentName"]
else:
... |
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.
... |
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... |
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... |
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... |
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 |
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
... |
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 `... |
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... |
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._... |
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
... |
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... |
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] |
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.... |
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... |
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... |
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 ... |
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) |
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 |
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 |
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... |
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: ... |
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:... |
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 = ... |
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)... |
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(... |
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... |
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... |
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) |
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 |
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
... |
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... |
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... |
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 ... |
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... |
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... |
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... |
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... |
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 {}"... |
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 ... |
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... |
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... |
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... |
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... |
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)... |
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... |
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) |
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... |
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... |
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 ... |
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 ... |
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... |
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... |
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 |
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;
"""
... |
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... |
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... |
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... |
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 ... |
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... |
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 =... |
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 (... |
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... |
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... |
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+... |
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 ... |
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... |
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).... |
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)... |
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]
... |
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) |
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'] |
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... |
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... |
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... |
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... |
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]) |
def getPosition(self):
"""See comments in base class."""
position = super(PermuteInt, self).getPosition()
position = int(round(position))
return position |
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) |
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'] |
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... |
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 =... |
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... |
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... |
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... |
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)
# --------------... |
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([])
... |
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... |
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... |
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... |
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... |
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.
... |
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... |
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:
--------------------------------------... |
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)... |
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:
-----------------------------------------------------------------... |
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... |
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... |
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.