INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Save the vocabulary to a file so the model can be reloaded. | def save_vocab(count=None, name='vocab.txt'):
"""Save the vocabulary to a file so the model can be reloaded.
Parameters
----------
count : a list of tuple and list
count[0] is a list : the number of rare words,
count[1:] are tuples : the number of occurrence of each word,
e.g. [... |
Very basic tokenizer: split the sentence into a list of tokens. | def basic_tokenizer(sentence, _WORD_SPLIT=re.compile(b"([.,!?\"':;)(])")):
"""Very basic tokenizer: split the sentence into a list of tokens.
Parameters
-----------
sentence : tensorflow.python.platform.gfile.GFile Object
_WORD_SPLIT : regular expression for word spliting.
Examples
------... |
r Create vocabulary file ( if it does not exist yet ) from data file. | def create_vocabulary(
vocabulary_path, data_path, max_vocabulary_size, tokenizer=None, normalize_digits=True,
_DIGIT_RE=re.compile(br"\d"), _START_VOCAB=None
):
r"""Create vocabulary file (if it does not exist yet) from data file.
Data file is assumed to contain one sentence per line. Each sen... |
Initialize vocabulary from file return the word_to_id ( dictionary ) and id_to_word ( list ). | def initialize_vocabulary(vocabulary_path):
"""Initialize vocabulary from file, return the `word_to_id` (dictionary)
and `id_to_word` (list).
We assume the vocabulary is stored one-item-per-line, so a file will result in a vocabulary {"dog": 0, "cat": 1}, and this function will also return the reversed-voc... |
Convert a string to list of integers representing token - ids. | def sentence_to_token_ids(
sentence, vocabulary, tokenizer=None, normalize_digits=True, UNK_ID=3, _DIGIT_RE=re.compile(br"\d")
):
"""Convert a string to list of integers representing token-ids.
For example, a sentence "I have a dog" may become tokenized into
["I", "have", "a", "dog"] and with vocab... |
Tokenize data file and turn into token - ids using given vocabulary file. | def data_to_token_ids(
data_path, target_path, vocabulary_path, tokenizer=None, normalize_digits=True, UNK_ID=3,
_DIGIT_RE=re.compile(br"\d")
):
"""Tokenize data file and turn into token-ids using given vocabulary file.
This function loads data line-by-line from data_path, calls the above
s... |
Calculate the bleu score for hypotheses and references using the MOSES ulti - bleu. perl script. | def moses_multi_bleu(hypotheses, references, lowercase=False):
"""Calculate the bleu score for hypotheses and references
using the MOSES ulti-bleu.perl script.
Parameters
------------
hypotheses : numpy.array.string
A numpy array of strings where each string is a single example.
referen... |
Returns the integer id of a word string. | def word_to_id(self, word):
"""Returns the integer id of a word string."""
if word in self._vocab:
return self._vocab[word]
else:
return self._unk_id |
Returns the integer word id of a word string. | def word_to_id(self, word):
"""Returns the integer word id of a word string."""
if word in self.vocab:
return self.vocab[word]
else:
return self.unk_id |
Returns the word string of an integer word id. | def id_to_word(self, word_id):
"""Returns the word string of an integer word id."""
if word_id >= len(self.reverse_vocab):
return self.reverse_vocab[self.unk_id]
else:
return self.reverse_vocab[word_id] |
Tokenization/ string cleaning for a datasets. | def basic_clean_str(string):
"""Tokenization/string cleaning for a datasets."""
string = re.sub(r"\n", " ", string) # '\n' --> ' '
string = re.sub(r"\'s", " \'s", string) # it's --> it 's
string = re.sub(r"\’s", " \'s", string)
string = re.sub(r"\'ve", " have", string) # they've --> t... |
How to use Embedding layer and how to convert IDs to vector IDs to words etc. | def main_restore_embedding_layer():
"""How to use Embedding layer, and how to convert IDs to vector,
IDs to words, etc.
"""
# Step 1: Build the embedding matrix and load the existing embedding matrix.
vocabulary_size = 50000
embedding_size = 128
model_file_name = "model_word2vec_50k_128"
... |
Generate text by Synced sequence input and output. | def main_lstm_generate_text():
"""Generate text by Synced sequence input and output."""
# rnn model and update (describtion: see tutorial_ptb_lstm.py)
init_scale = 0.1
learning_rate = 1.0
max_grad_norm = 5
sequence_length = 20
hidden_size = 200
max_epoch = 4
max_max_epoch = 100
... |
Create and start a swarm job. | def createAndStartSwarm(client, clientInfo="", clientKey="", params="",
minimumWorkers=None, maximumWorkers=None,
alreadyRunning=False):
"""Create and start a swarm job.
Args:
client - A string identifying the calling client. There is a small limit
for th... |
Retrieve the Engine - level model params from a Swarm model | def getSwarmModelParams(modelID):
"""Retrieve the Engine-level model params from a Swarm model
Args:
modelID - Engine-level model ID of the Swarm model
Returns:
JSON-encoded string containing Model Params
"""
# TODO: the use of nupic.frameworks.opf.helpers.loadExperimentDescriptionScriptFromDir whe... |
Enable the diagnostic feature for debugging unexpected concurrency in acquiring ConnectionWrapper instances. | def enableConcurrencyChecks(maxConcurrency, raiseException=True):
""" Enable the diagnostic feature for debugging unexpected concurrency in
acquiring ConnectionWrapper instances.
NOTE: This MUST be done early in your application's execution, BEFORE any
accesses to ConnectionFactory or connection policies from ... |
Returns a dictionary of arguments for DBUtils. SteadyDB. SteadyDBConnection constructor. | def _getCommonSteadyDBArgsDict():
""" Returns a dictionary of arguments for DBUtils.SteadyDB.SteadyDBConnection
constructor.
"""
return dict(
creator = pymysql,
host = Configuration.get('nupic.cluster.database.host'),
port = int(Configuration.get('nupic.cluster.database.port')),
user = ... |
Gets a logger for the given class in this module | def _getLogger(cls, logLevel=None):
""" Gets a logger for the given class in this module
"""
logger = logging.getLogger(
".".join(['com.numenta', _MODULE_NAME, cls.__name__]))
if logLevel is not None:
logger.setLevel(logLevel)
return logger |
Acquire a ConnectionWrapper instance that represents a connection to the SQL server per nupic. cluster. database. * configuration settings. | def get(cls):
""" Acquire a ConnectionWrapper instance that represents a connection
to the SQL server per nupic.cluster.database.* configuration settings.
NOTE: caller is responsible for calling the ConnectionWrapper instance's
release() method after using the connection in order to release resources.
... |
[ private ] Create the default database connection policy instance | def _createDefaultPolicy(cls):
""" [private] Create the default database connection policy instance
Parameters:
----------------------------------------------------------------
retval: The default database connection policy instance
"""
logger = _getLogger(cls)
logger.debug(
... |
Release the database connection and cursor | def release(self):
""" Release the database connection and cursor
The receiver of the Connection instance MUST call this method in order
to reclaim resources
"""
self._logger.debug("Releasing: %r", self)
# Discard self from set of outstanding instances
if self._addedToInstanceSet:
t... |
Check for concurrency violation and add self to _clsOutstandingInstances. | def _trackInstanceAndCheckForConcurrencyViolation(self):
""" Check for concurrency violation and add self to
_clsOutstandingInstances.
ASSUMPTION: Called from constructor BEFORE _clsNumOutstanding is
incremented
"""
global g_max_concurrency, g_max_concurrency_raise_exception
assert g_max_c... |
Close the policy instance and its shared database connection. | def close(self):
""" Close the policy instance and its shared database connection. """
self._logger.info("Closing")
if self._conn is not None:
self._conn.close()
self._conn = None
else:
self._logger.warning(
"close() called, but connection policy was alredy closed")
return |
Get a Connection instance. | def acquireConnection(self):
""" Get a Connection instance.
Parameters:
----------------------------------------------------------------
retval: A ConnectionWrapper instance. NOTE: Caller
is responsible for calling the ConnectionWrapper
instance's release(... |
Close the policy instance and its database connection pool. | def close(self):
""" Close the policy instance and its database connection pool. """
self._logger.info("Closing")
if self._pool is not None:
self._pool.close()
self._pool = None
else:
self._logger.warning(
"close() called, but connection policy was alredy closed")
return |
Get a connection from the pool. | def acquireConnection(self):
""" Get a connection from the pool.
Parameters:
----------------------------------------------------------------
retval: A ConnectionWrapper instance. NOTE: Caller
is responsible for calling the ConnectionWrapper
instance's rel... |
Close the policy instance. | def close(self):
""" Close the policy instance. """
self._logger.info("Closing")
if self._opened:
self._opened = False
else:
self._logger.warning(
"close() called, but connection policy was alredy closed")
return |
Create a Connection instance. | def acquireConnection(self):
""" Create a Connection instance.
Parameters:
----------------------------------------------------------------
retval: A ConnectionWrapper instance. NOTE: Caller
is responsible for calling the ConnectionWrapper
instance's relea... |
Release database connection and cursor ; passed as a callback to ConnectionWrapper | def _releaseConnection(self, dbConn, cursor):
""" Release database connection and cursor; passed as a callback to
ConnectionWrapper
"""
self._logger.debug("Releasing connection")
# Close the cursor
cursor.close()
# ... then close the database connection
dbConn.close()
return |
Overrides: meth: nupic. bindings. regions. PyRegion. PyRegion. getSpec. | def getSpec(cls):
"""
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getSpec`.
"""
ns = dict(
description=KNNAnomalyClassifierRegion.__doc__,
singleNodeOnly=True,
inputs=dict(
spBottomUpOut=dict(
description="""The output signal generated from the... |
Overrides: meth: nupic. bindings. regions. PyRegion. PyRegion. getParameter. | def getParameter(self, name, index=-1):
"""
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getParameter`.
"""
if name == "trainRecords":
return self.trainRecords
elif name == "anomalyThreshold":
return self.anomalyThreshold
elif name == "activeColumnCount":
return se... |
Overrides: meth: nupic. bindings. regions. PyRegion. PyRegion. setParameter. | def setParameter(self, name, index, value):
"""
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.setParameter`.
"""
if name == "trainRecords":
# Ensure that the trainRecords can only be set to minimum of the ROWID in
# the saved states
if not (isinstance(value, float) or isins... |
Process one input sample. This method is called by the runtime engine. | def compute(self, inputs, outputs):
"""
Process one input sample.
This method is called by the runtime engine.
"""
record = self._constructClassificationRecord(inputs)
#Classify this point after waiting the classification delay
if record.ROWID >= self.getParameter('trainRecords'):
sel... |
Reclassifies given state. | def _classifyState(self, state):
"""
Reclassifies given state.
"""
# Record is before wait period do not classifiy
if state.ROWID < self.getParameter('trainRecords'):
if not state.setByUser:
state.anomalyLabel = []
self._deleteRecordsFromKNN([state])
return
label = K... |
Construct a _HTMClassificationRecord based on the state of the model passed in through the inputs. | def _constructClassificationRecord(self, inputs):
"""
Construct a _HTMClassificationRecord based on the state of the model
passed in through the inputs.
Types for self.classificationVectorType:
1 - TM active cells in learn state
2 - SP columns concatenated with error from TM column predicti... |
Adds the record to the KNN classifier. | def _addRecordToKNN(self, record):
"""
Adds the record to the KNN classifier.
"""
knn = self._knnclassifier._knn
prototype_idx = self._knnclassifier.getParameter('categoryRecencyList')
category = self._labelListToCategoryNumber(record.anomalyLabel)
# If record is already in the classifier,... |
Removes the given records from the classifier. | def _deleteRecordsFromKNN(self, recordsToDelete):
"""
Removes the given records from the classifier.
parameters
------------
recordsToDelete - list of records to delete from the classififier
"""
prototype_idx = self._knnclassifier.getParameter('categoryRecencyList')
idsToDelete = ([r.R... |
Removes any stored records within the range from start to end. Noninclusive of end. | def _deleteRangeFromKNN(self, start=0, end=None):
"""
Removes 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 of the end of the... |
returns the classified labeling of record | def _recomputeRecordFromKNN(self, record):
"""
returns the classified labeling of record
"""
inputs = {
"categoryIn": [None],
"bottomUpIn": self._getStateAnomalyVector(record),
}
outputs = {"categoriesOut": numpy.zeros((1,)),
"bestPrototypeIndices":numpy.zeros((1,)),
... |
Since the KNN Classifier stores categories as numbers we must store each label as a number. This method converts from a label to a unique number. Each label is assigned a unique bit so multiple labels may be assigned to a single record. | def _labelToCategoryNumber(self, label):
"""
Since the KNN Classifier stores categories as numbers, we must store each
label as a number. This method converts from a label to a unique number.
Each label is assigned a unique bit so multiple labels may be assigned to
a single record.
"""
if la... |
This method takes a list of labels and returns a unique category number. This enables this class to store a list of categories for each point since the KNN classifier only stores a single number category for each record. | def _labelListToCategoryNumber(self, labelList):
"""
This method takes a list of labels and returns a unique category number.
This enables this class to store a list of categories for each point since
the KNN classifier only stores a single number category for each record.
"""
categoryNumber = 0... |
Converts a category number into a list of labels | def _categoryToLabelList(self, category):
"""
Converts a category number into a list of labels
"""
if category is None:
return []
labelList = []
labelNum = 0
while category > 0:
if category % 2 == 1:
labelList.append(self.saved_categories[labelNum])
labelNum += 1
... |
Returns a state s anomaly vertor converting it from spare to dense | def _getStateAnomalyVector(self, state):
"""
Returns a state's anomaly vertor converting it from spare to dense
"""
vector = numpy.zeros(self._anomalyVectorLength)
vector[state.anomalyVector] = 1
return vector |
Get the labels on classified points within range start to end. Not inclusive of end. | def getLabels(self, start=None, end=None):
"""
Get the labels on classified points within range start to end. Not inclusive
of end.
:returns: (dict) with format:
::
{
'isProcessing': boolean,
'recordLabels': list of results
}
``isProcessing`` - current... |
Add the label labelName to each record with record ROWID in range from start to end noninclusive of end. | 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.
:param start: (int) sta... |
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 equal to labelFilter. | 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 equal to
``labelFilter``.
This will r... |
Returns True if the record matches any of the provided filters | def match(self, record):
'''
Returns True if the record matches any of the provided filters
'''
for field, meta in self.filterDict.iteritems():
index = meta['index']
categories = meta['categories']
for category in categories:
# Record might be blank, handle this
if not... |
Wraps replaceSparseRow () | def replace(self, columnIndex, bitmap):
""" Wraps replaceSparseRow()"""
return super(_SparseMatrixCorticalColumnAdapter, self).replaceSparseRow(
columnIndex, bitmap
) |
Wraps setRowFromDense () | def update(self, columnIndex, vector):
""" Wraps setRowFromDense()"""
return super(_SparseMatrixCorticalColumnAdapter, self).setRowFromDense(
columnIndex, vector
) |
Sets the local area density. Invalidates the numActiveColumnsPerInhArea parameter: param localAreaDensity: ( float ) value to set | def setLocalAreaDensity(self, localAreaDensity):
"""
Sets the local area density. Invalidates the 'numActiveColumnsPerInhArea'
parameter
:param localAreaDensity: (float) value to set
"""
assert(localAreaDensity > 0 and localAreaDensity <= 1)
self._localAreaDensity = localAreaDensity
... |
: param columnIndex: ( int ) column index to get potential for.: param potential: ( list ) will be overwritten with column potentials. Must match the number of inputs. | def getPotential(self, columnIndex, potential):
"""
:param columnIndex: (int) column index to get potential for.
:param potential: (list) will be overwritten with column potentials. Must
match the number of inputs.
"""
assert(columnIndex < self._numColumns)
potential[:] = self._poten... |
Sets the potential mapping for a given column. potential size must match the number of inputs and must be greater than stimulusThreshold.: param columnIndex: ( int ) column index to set potential for.: param potential: ( list ) value to set. | def setPotential(self, columnIndex, potential):
"""
Sets the potential mapping for a given column. ``potential`` size must match
the number of inputs, and must be greater than ``stimulusThreshold``.
:param columnIndex: (int) column index to set potential for.
:param potential: (list) value to ... |
Returns the permanence values for a given column. permanence size must match the number of inputs.: param columnIndex: ( int ) column index to get permanence for.: param permanence: ( list ) will be overwritten with permanences. | def getPermanence(self, columnIndex, permanence):
"""
Returns the permanence values for a given column. ``permanence`` size
must match the number of inputs.
:param columnIndex: (int) column index to get permanence for.
:param permanence: (list) will be overwritten with permanences.
"""
... |
Sets the permanence values for a given column. permanence size must match the number of inputs.: param columnIndex: ( int ) column index to set permanence for.: param permanence: ( list ) value to set. | def setPermanence(self, columnIndex, permanence):
"""
Sets the permanence values for a given column. ``permanence`` size must
match the number of inputs.
:param columnIndex: (int) column index to set permanence for.
:param permanence: (list) value to set.
"""
assert(columnIndex < self... |
: param connectedSynapses: ( list ) will be overwritten: returns: ( iter ) the connected synapses for a given column. connectedSynapses size must match the number of inputs | def getConnectedSynapses(self, columnIndex, connectedSynapses):
"""
:param connectedSynapses: (list) will be overwritten
:returns: (iter) the connected synapses for a given column.
``connectedSynapses`` size must match the number of inputs"""
assert(columnIndex < self._numColumns)
conn... |
Removes the set of columns who have never been active from the set of active columns selected in the inhibition round. Such columns cannot represent learned pattern and are therefore meaningless if only inference is required. This should not be done when using a random unlearned SP since you would end up with no active... | def stripUnlearnedColumns(self, activeArray):
"""
Removes the set of columns who have never been active from the set of
active columns selected in the inhibition round. Such columns cannot
represent learned pattern and are therefore meaningless if only inference
is required. This should not be done ... |
Updates the minimum duty cycles defining normal activity for a column. A column with activity duty cycle below this minimum threshold is boosted. | def _updateMinDutyCycles(self):
"""
Updates the minimum duty cycles defining normal activity for a column. A
column with activity duty cycle below this minimum threshold is boosted.
"""
if self._globalInhibition or self._inhibitionRadius > self._numInputs:
self._updateMinDutyCyclesGlobal()
... |
Updates the minimum duty cycles in a global fashion. Sets the minimum duty cycles for the overlap all columns to be a percent of the maximum in the region specified by minPctOverlapDutyCycle. Functionality it is equivalent to _updateMinDutyCyclesLocal but this function exploits the globality of the computation to perfo... | def _updateMinDutyCyclesGlobal(self):
"""
Updates the minimum duty cycles in a global fashion. Sets the minimum duty
cycles for the overlap all columns to be a percent of the maximum in the
region, specified by minPctOverlapDutyCycle. Functionality it is equivalent
to _updateMinDutyCyclesLocal, but ... |
Updates the minimum duty cycles. The minimum duty cycles are determined locally. Each column s minimum duty cycles are set to be a percent of the maximum duty cycles in the column s neighborhood. Unlike _updateMinDutyCyclesGlobal here the values can be quite different for different columns. | def _updateMinDutyCyclesLocal(self):
"""
Updates the minimum duty cycles. The minimum duty cycles are determined
locally. Each column's minimum duty cycles are set to be a percent of the
maximum duty cycles in the column's neighborhood. Unlike
_updateMinDutyCyclesGlobal, here the values can be quite... |
Updates the duty cycles for each column. The OVERLAP duty cycle is a moving average of the number of inputs which overlapped with the each column. The ACTIVITY duty cycles is a moving average of the frequency of activation for each column. | def _updateDutyCycles(self, overlaps, activeColumns):
"""
Updates the duty cycles for each column. The OVERLAP duty cycle is a moving
average of the number of inputs which overlapped with the each column. The
ACTIVITY duty cycles is a moving average of the frequency of activation for
each column.
... |
Update the inhibition radius. The inhibition radius is a measure of the square ( or hypersquare ) of columns that each a column is connected to on average. Since columns are are not connected to each other directly we determine this quantity by first figuring out how many * inputs * a column is connected to and then mu... | def _updateInhibitionRadius(self):
"""
Update the inhibition radius. The inhibition radius is a measure of the
square (or hypersquare) of columns that each a column is "connected to"
on average. Since columns are are not connected to each other directly, we
determine this quantity by first figuring ... |
The average number of columns per input taking into account the topology of the inputs and columns. This value is used to calculate the inhibition radius. This function supports an arbitrary number of dimensions. If the number of column dimensions does not match the number of input dimensions we treat the missing or ph... | def _avgColumnsPerInput(self):
"""
The average number of columns per input, taking into account the topology
of the inputs and columns. This value is used to calculate the inhibition
radius. This function supports an arbitrary number of dimensions. If the
number of column dimensions does not match t... |
The range of connected synapses for column. This is used to calculate the inhibition radius. This variation of the function only supports a 1 dimensional column topology. | def _avgConnectedSpanForColumn1D(self, columnIndex):
"""
The range of connected synapses for column. This is used to
calculate the inhibition radius. This variation of the function only
supports a 1 dimensional column topology.
Parameters:
----------------------------
:param columnIndex: ... |
The range of connectedSynapses per column averaged for each dimension. This value is used to calculate the inhibition radius. This variation of the function only supports a 2 dimensional column topology. | def _avgConnectedSpanForColumn2D(self, columnIndex):
"""
The range of connectedSynapses per column, averaged for each dimension.
This value is used to calculate the inhibition radius. This variation of
the function only supports a 2 dimensional column topology.
Parameters:
--------------------... |
This method increases the permanence values of synapses of columns whose activity level has been too low. Such columns are identified by having an overlap duty cycle that drops too much below those of their peers. The permanence values for such columns are increased. | def _bumpUpWeakColumns(self):
"""
This method increases the permanence values of synapses of columns whose
activity level has been too low. Such columns are identified by having an
overlap duty cycle that drops too much below those of their peers. The
permanence values for such columns are increased... |
This method ensures that each column has enough connections to input bits to allow it to become active. Since a column must have at least self. _stimulusThreshold overlaps in order to be considered during the inhibition phase columns without such minimal number of connections even if all the input bits they are connect... | def _raisePermanenceToThreshold(self, perm, mask):
"""
This method ensures that each column has enough connections to input bits
to allow it to become active. Since a column must have at least
'self._stimulusThreshold' overlaps in order to be considered during the
inhibition phase, columns without s... |
This method updates the permanence matrix with a column s new permanence values. The column is identified by its index which reflects the row in the matrix and the permanence is given in dense form i. e. a full array containing all the zeros as well as the non - zero values. It is in charge of implementing clipping - e... | def _updatePermanencesForColumn(self, perm, columnIndex, raisePerm=True):
"""
This method updates the permanence matrix with a column's new permanence
values. The column is identified by its index, which reflects the row in
the matrix, and the permanence is given in 'dense' form, i.e. a full
array c... |
Returns a randomly generated permanence value for a synapses that is initialized in a connected state. The basic idea here is to initialize permanence values very close to synPermConnected so that a small number of learning steps could make it disconnected or connected. | def _initPermConnected(self):
"""
Returns a randomly generated permanence value for a synapses that is
initialized in a connected state. The basic idea here is to initialize
permanence values very close to synPermConnected so that a small number of
learning steps could make it disconnected or connec... |
Returns a randomly generated permanence value for a synapses that is to be initialized in a non - connected state. | def _initPermNonConnected(self):
"""
Returns a randomly generated permanence value for a synapses that is to be
initialized in a non-connected state.
"""
p = self._synPermConnected * self._random.getReal64()
# Ensure we don't have too much unnecessary precision. A full 64 bits of
# precisio... |
Initializes the permanences of a column. The method returns a 1 - D array the size of the input where each entry in the array represents the initial permanence value between the input bit at the particular index in the array and the column represented by the index parameter. | def _initPermanence(self, potential, connectedPct):
"""
Initializes the permanences of a column. The method
returns a 1-D array the size of the input, where each entry in the
array represents the initial permanence value between the input bit
at the particular index in the array, and the column repr... |
Maps a column to its respective input index keeping to the topology of the region. It takes the index of the column as an argument and determines what is the index of the flattened input vector that is to be the center of the column s potential pool. It distributes the columns over the inputs uniformly. The return valu... | def _mapColumn(self, index):
"""
Maps a column to its respective input index, keeping to the topology of
the region. It takes the index of the column as an argument and determines
what is the index of the flattened input vector that is to be the center of
the column's potential pool. It distributes ... |
Maps a column to its input bits. This method encapsulates the topology of the region. It takes the index of the column as an argument and determines what are the indices of the input vector that are located within the column s potential pool. The return value is a list containing the indices of the input bits. The curr... | def _mapPotential(self, index):
"""
Maps a column to its input bits. This method encapsulates the topology of
the region. It takes the index of the column as an argument and determines
what are the indices of the input vector that are located within the
column's potential pool. The return value is a... |
Update boost factors when global inhibition is used | def _updateBoostFactorsGlobal(self):
"""
Update boost factors when global inhibition is used
"""
# When global inhibition is enabled, the target activation level is
# the sparsity of the spatial pooler
if (self._localAreaDensity > 0):
targetDensity = self._localAreaDensity
else:
... |
Update boost factors when local inhibition is used | def _updateBoostFactorsLocal(self):
"""
Update boost factors when local inhibition is used
"""
# Determine the target activation level for each column
# The targetDensity is the average activeDutyCycles of the neighboring
# columns of each column.
targetDensity = numpy.zeros(self._numColumns... |
This function determines each column s overlap with the current input vector. The overlap of a column is the number of synapses for that column that are connected ( permanence value is greater than _synPermConnected ) to input bits which are turned on. The implementation takes advantage of the SparseBinaryMatrix class ... | def _calculateOverlap(self, inputVector):
"""
This function determines each column's overlap with the current input
vector. The overlap of a column is the number of synapses for that column
that are connected (permanence value is greater than '_synPermConnected')
to input bits which are turned on. T... |
Performs inhibition. This method calculates the necessary values needed to actually perform inhibition and then delegates the task of picking the active columns to helper functions. | def _inhibitColumns(self, overlaps):
"""
Performs inhibition. This method calculates the necessary values needed to
actually perform inhibition and then delegates the task of picking the
active columns to helper functions.
Parameters:
----------------------------
:param overlaps: an array c... |
Perform global inhibition. Performing global inhibition entails picking the top numActive columns with the highest overlap score in the entire region. At most half of the columns in a local neighborhood are allowed to be active. Columns with an overlap score below the stimulusThreshold are always inhibited. | def _inhibitColumnsGlobal(self, overlaps, density):
"""
Perform global inhibition. Performing global inhibition entails picking the
top 'numActive' columns with the highest overlap score in the entire
region. At most half of the columns in a local neighborhood are allowed to
be active. Columns with ... |
Performs local inhibition. Local inhibition is performed on a column by column basis. Each column observes the overlaps of its neighbors and is selected if its overlap score is within the top numActive in its local neighborhood. At most half of the columns in a local neighborhood are allowed to be active. Columns with ... | def _inhibitColumnsLocal(self, overlaps, density):
"""
Performs local inhibition. Local inhibition is performed on a column by
column basis. Each column observes the overlaps of its neighbors and is
selected if its overlap score is within the top 'numActive' in its local
neighborhood. At most half o... |
Gets a neighborhood of columns. | def _getColumnNeighborhood(self, centerColumn):
"""
Gets a neighborhood of columns.
Simply calls topology.neighborhood or topology.wrappingNeighborhood
A subclass can insert different topology behavior by overriding this method.
:param centerColumn (int)
The center of the neighborhood.
@... |
Gets a neighborhood of inputs. | def _getInputNeighborhood(self, centerInput):
"""
Gets a neighborhood of inputs.
Simply calls topology.wrappingNeighborhood or topology.neighborhood.
A subclass can insert different topology behavior by overriding this method.
:param centerInput (int)
The center of the neighborhood.
@ret... |
Initialize the random seed | def _seed(self, seed=-1):
"""
Initialize the random seed
"""
if seed != -1:
self._random = NupicRandom(seed)
else:
self._random = NupicRandom() |
This method overrides ValueGetterBase s pure virtual method. It returns the referenced value. The derived class is NOT responsible for fully resolving the reference d value in the event the value resolves to another ValueGetterBase - based instance -- this is handled automatically within ValueGetterBase implementation. | def handleGetValue(self, topContainer):
""" This method overrides ValueGetterBase's "pure virtual" method. It
returns the referenced value. The derived class is NOT responsible for
fully resolving the reference'd value in the event the value resolves to
another ValueGetterBase-based instance -- this i... |
Factory function that creates typed Array or ArrayRef objects | def Array(dtype, size=None, ref=False):
"""Factory function that creates typed Array or ArrayRef objects
dtype - the data type of the array (as string).
Supported types are: Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Real32, Real64
size - the size of the array. Must be positive integer.
"""
def... |
Returns list of input names in spec. | def getInputNames(self):
"""
Returns list of input names in spec.
"""
inputs = self.getSpec().inputs
return [inputs.getByIndex(i)[0] for i in xrange(inputs.getCount())] |
Returns list of output names in spec. | def getOutputNames(self):
"""
Returns list of output names in spec.
"""
outputs = self.getSpec().outputs
return [outputs.getByIndex(i)[0] for i in xrange(outputs.getCount())] |
Returns functions to set/ get the parameter. These are the strongly typed functions get/ setParameterUInt32 etc. The return value is a pair: setfunc getfunc If the parameter is not available on this region setfunc/ getfunc are None. | def _getParameterMethods(self, paramName):
"""Returns functions to set/get the parameter. These are
the strongly typed functions get/setParameterUInt32, etc.
The return value is a pair:
setfunc, getfunc
If the parameter is not available on this region, setfunc/getfunc
are None. """
if pa... |
Get parameter value | def getParameter(self, paramName):
"""Get parameter value"""
(setter, getter) = self._getParameterMethods(paramName)
if getter is None:
import exceptions
raise exceptions.Exception(
"getParameter -- parameter name '%s' does not exist in region %s of type %s"
% (paramName, sel... |
Set parameter value | def setParameter(self, paramName, value):
"""Set parameter value"""
(setter, getter) = self._getParameterMethods(paramName)
if setter is None:
import exceptions
raise exceptions.Exception(
"setParameter -- parameter name '%s' does not exist in region %s of type %s"
% (paramNa... |
Get the collection of regions in a network | def _getRegions(self):
"""Get the collection of regions in a network
This is a tricky one. The collection of regions returned from
from the internal network is a collection of internal regions.
The desired collection is a collelcion of net.Region objects
that also points to this network (net.networ... |
Gets all region instances of a given class ( for example nupic. regions. sp_region. SPRegion ). | def getRegionsByType(self, regionClass):
"""
Gets all region instances of a given class
(for example, nupic.regions.sp_region.SPRegion).
"""
regions = []
for region in self.regions.values():
if type(region.getSelf()) is regionClass:
regions.append(region)
return regions |
Overrides: meth: nupic. bindings. regions. PyRegion. PyRegion. getSpec. | def getSpec(cls):
"""
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getSpec`.
"""
ns = dict(
description=SDRClassifierRegion.__doc__,
singleNodeOnly=True,
inputs=dict(
actValueIn=dict(
description="Actual value of the field to predict. Only taken "
... |
Overrides: meth: nupic. bindings. regions. PyRegion. PyRegion. initialize. | def initialize(self):
"""
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.initialize`.
Is called once by NuPIC before the first call to compute().
Initializes self._sdrClassifier if it is not already initialized.
"""
if self._sdrClassifier is None:
self._sdrClassifier = SDRClass... |
Overrides: meth: nupic. bindings. regions. PyRegion. PyRegion. setParameter. | def setParameter(self, name, index, value):
"""
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.setParameter`.
"""
if name == "learningMode":
self.learningMode = bool(int(value))
elif name == "inferenceMode":
self.inferenceMode = bool(int(value))
else:
return PyRegion... |
Write state to proto object. | def writeToProto(self, proto):
"""
Write state to proto object.
:param proto: SDRClassifierRegionProto capnproto object
"""
proto.implementation = self.implementation
proto.steps = self.steps
proto.alpha = self.alpha
proto.verbosity = self.verbosity
proto.maxCategoryCount = self.max... |
Read state from proto object. | def readFromProto(cls, proto):
"""
Read state from proto object.
:param proto: SDRClassifierRegionProto capnproto object
"""
instance = cls()
instance.implementation = proto.implementation
instance.steps = proto.steps
instance.stepsList = [int(i) for i in proto.steps.split(",")]
in... |
Process one input sample. This method is called by the runtime engine. | def compute(self, inputs, outputs):
"""
Process one input sample.
This method is called by the runtime engine.
: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 v... |
Just return the inference value from one input sample. The actual learning happens in compute () -- if and only if learning is enabled -- which is called when you run the network. | def customCompute(self, recordNum, patternNZ, classification):
"""
Just return the inference value from one input sample. The actual
learning happens in compute() -- if, and only if learning is enabled --
which is called when you run the network.
.. warning:: This method is deprecated and exists on... |
Overrides: meth: nupic. bindings. regions. PyRegion. PyRegion. getOutputElementCount. | def getOutputElementCount(self, outputName):
"""
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getOutputElementCount`.
"""
if outputName == "categoriesOut":
return len(self.stepsList)
elif outputName == "probabilities":
return len(self.stepsList) * self.maxCategoryCount
e... |
Runs the OPF Model | def run(self):
""" Runs the OPF Model
Parameters:
-------------------------------------------------------------------------
retval: (completionReason, completionMsg)
where completionReason is one of the ClientJobsDAO.CMPL_REASON_XXX
equates.
"""
# ----------------... |
Main loop of the OPF Model Runner. | def __runTaskMainLoop(self, numIters, learningOffAt=None):
""" Main loop of the OPF Model Runner.
Parameters:
-----------------------------------------------------------------------
recordIterator: Iterator for counting number of records (see _runTask)
learningOffAt: If not None, learning i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.