Sequence Memory¶
Temporal Memory¶
Temporal Memory implementation in Python. See numenta.com for details.
-
class
nupic.algorithms.temporal_memory.
TemporalMemory
(columnDimensions=(2048, ), cellsPerColumn=32, activationThreshold=13, initialPermanence=0.21, connectedPermanence=0.5, minThreshold=10, maxNewSynapseCount=20, permanenceIncrement=0.1, permanenceDecrement=0.1, predictedSegmentDecrement=0.0, maxSegmentsPerCell=255, maxSynapsesPerSegment=255, seed=42, **kwargs)¶ Bases:
nupic.serializable.Serializable
Class implementing the Temporal Memory algorithm.
Note
predictedSegmentDecrement
: A good value is just a bit larger than (the column-level sparsity * permanenceIncrement). So, if column-level sparsity is 2% and permanenceIncrement is 0.01, this parameter should be something like 4% * 0.01 = 0.0004).Parameters: - columnDimensions – (list or tuple) Dimensions of the column space.
Default value
[2048]
. - cellsPerColumn – (int) Number of cells per column. Default value
32
. - activationThreshold – (int) If the number of active connected synapses
on a segment is at least this threshold, the segment is said to be
active. Default value
13
. - initialPermanence – (float) Initial permanence of a new synapse. Default
value
0.21
. - connectedPermanence – (float) If the permanence value for a synapse is
greater than this value, it is said to be connected. Default value
0.5
. - minThreshold – (int) If the number of potential synapses active on a
segment is at least this threshold, it is said to be “matching” and
is eligible for learning. Default value
10
. - maxNewSynapseCount – (int) The maximum number of synapses added to a
segment during learning. Default value
20
. - permanenceIncrement – (float) Amount by which permanences of synapses
are incremented during learning. Default value
0.1
. - permanenceDecrement – (float) Amount by which permanences of synapses
are decremented during learning. Default value
0.1
. - predictedSegmentDecrement – (float) Amount by which segments are
punished for incorrect predictions. Default value
0.0
. - seed – (int) Seed for the random number generator. Default value
42
. - maxSegmentsPerCell – (int) The maximum number of segments per cell.
Default value
255
. - maxSynapsesPerSegment – (int) The maximum number of synapses per
segment. Default value
255
.
-
activateCells
(activeColumns, learn=True)¶ Calculate the active cells, using the current active columns and dendrite segments. Grow and reinforce synapses.
Parameters: - activeColumns – (iter) A sorted list of active column indices.
- learn –
(bool) If true, reinforce / punish / grow synapses.
Pseudocode:
for each column if column is active and has active distal dendrite segments call activatePredictedColumn if column is active and doesn't have active distal dendrite segments call burstColumn if column is inactive and has matching distal dendrite segments call punishPredictedColumn
-
activateDendrites
(learn=True)¶ Calculate dendrite segment activity, using the current active cells.
Parameters: learn – (bool) If true, segment activations will be recorded. This information is used during segment cleanup. Pseudocode:
for each distal dendrite segment with activity >= activationThreshold mark the segment as active for each distal dendrite segment with unconnected activity >= minThreshold mark the segment as matching
-
activatePredictedColumn
(column, columnActiveSegments, columnMatchingSegments, prevActiveCells, prevWinnerCells, learn)¶ Determines which cells in a predicted column should be added to winner cells list, and learns on the segments that correctly predicted this column.
Parameters: - column – (int) Index of bursting column.
- columnActiveSegments – (iter) Active segments in this column.
- columnMatchingSegments – (iter) Matching segments in this column.
- prevActiveCells – (list) Active cells in
t-1
. - prevWinnerCells – (list) Winner cells in
t-1
. - learn – (bool) If true, grow and reinforce synapses.
Returns: (list) A list of predicted cells that will be added to active cells and winner cells.
-
burstColumn
(column, columnMatchingSegments, prevActiveCells, prevWinnerCells, learn)¶ Activates all of the cells in an unpredicted active column, chooses a winner cell, and, if learning is turned on, learns on one segment, growing a new segment if necessary.
Parameters: - column – (int) Index of bursting column.
- columnMatchingSegments – (iter) Matching segments in this column, or None if there aren’t any.
- prevActiveCells – (list) Active cells in
t-1
. - prevWinnerCells – (list) Winner cells in
t-1
. - learn – (bool) Whether or not learning is enabled.
Returns: (tuple) Contains (
cells
[iter],winnerCell
[int])
-
cellsForColumn
(column)¶ Returns the indices of cells that belong to a column.
Parameters: column – (int) Column index Returns: (list) Cell indices
-
columnForCell
(cell)¶ Returns the index of the column that a cell belongs to.
Parameters: cell – (int) Cell index Returns: (int) Column index
-
compute
(activeColumns, learn=True)¶ Perform one time step of the Temporal Memory algorithm.
This method calls
activateCells()
, then callsactivateDendrites()
. UsingTemporalMemory
via itscompute()
method ensures that you’ll always be able to callgetPredictiveCells()
to get predictions for the next time step.Parameters: - activeColumns – (iter) Indices of active columns.
- learn – (bool) Whether or not learning is enabled.
-
static
connectionsFactory
(*args, **kwargs)¶ Create a
Connections
instance.TemporalMemory
subclasses may override this method to choose a differentConnections
implementation, or to augment the instance otherwise returned by the defaultConnections
implementation.See
Connections
for constructor signature and usage.Returns: Connections
instance
-
createSegment
(cell)¶ Create a
Segment
on the specified cell. This method callscreateSegment()
on the underlyingConnections
, and it does some extra bookkeeping. Unit tests should call this method, and notcreateSegment()
.Parameters: cell – (int) Index of cell to create a segment on. Returns: ( Segment
) The created segment.
-
getActivationThreshold
()¶ Returns the activation threshold.
Returns: (int) The activation threshold.
-
getActiveCells
()¶ Returns the indices of the active cells.
Returns: (list) Indices of active cells.
-
getActiveSegments
()¶ Returns the active segments.
Returns: (list) Active segments
-
static
getCellIndex
(cell)¶ Returns the index of the cell.
Parameters: cell – (int) cell to find the index of
-
classmethod
getCellIndices
(cells)¶ Returns the indices of the cells passed in.
Parameters: cells – (list) cells to find the indices of
-
getCellsPerColumn
()¶ Returns the number of cells per column.
Returns: (int) The number of cells per column.
-
getColumnDimensions
()¶ Returns the dimensions of the columns in the region.
Returns: (tuple) Column dimensions
-
getConnectedPermanence
()¶ Get the connected permanence.
Returns: (float) The connected permanence.
-
getInitialPermanence
()¶ Get the initial permanence.
Returns: (float) The initial permanence.
-
getMatchingSegments
()¶ Returns the matching segments.
Returns: (list) Matching segments
-
getMaxNewSynapseCount
()¶ Returns the max new synapse count.
Returns: (int) The max new synapse count.
-
getMaxSegmentsPerCell
()¶ Get the maximum number of segments per cell
Returns: (int) max number of segments per cell
-
getMaxSynapsesPerSegment
()¶ Get the maximum number of synapses per segment.
Returns: (int) max number of synapses per segment
-
getMinThreshold
()¶ Returns the min threshold.
Returns: (int) The min threshold.
-
getPermanenceDecrement
()¶ Get the permanence decrement.
Returns: (float) The permanence decrement.
-
getPermanenceIncrement
()¶ Get the permanence increment.
Returns: (float) The permanence increment.
-
getPredictedSegmentDecrement
()¶ Get the predicted segment decrement.
Returns: (float) The predicted segment decrement.
-
getPredictiveCells
()¶ Returns the indices of the predictive cells.
Returns: (list) Indices of predictive cells.
-
getWinnerCells
()¶ Returns the indices of the winner cells.
Returns: (list) Indices of winner cells.
-
mapCellsToColumns
(cells)¶ Maps cells to the columns they belong to.
Parameters: cells – (set) Cells Returns: (dict) Mapping from columns to their cells in cells
-
numberOfCells
()¶ Returns the number of cells in this layer.
Returns: (int) Number of cells
-
numberOfColumns
()¶ Returns the number of columns in this layer.
Returns: (int) Number of columns
-
punishPredictedColumn
(column, columnActiveSegments, columnMatchingSegments, prevActiveCells, prevWinnerCells)¶ Punishes the Segments that incorrectly predicted a column to be active.
Parameters: - column – (int) Index of bursting column.
- columnActiveSegments – (iter) Active segments for this column, or None if there aren’t any.
- columnMatchingSegments – (iter) Matching segments for this column, or None if there aren’t any.
- prevActiveCells – (list) Active cells in
t-1
. - prevWinnerCells – (list) Winner cells in
t-1
.
-
classmethod
read
(proto)¶ Reads deserialized data from proto object.
Parameters: proto – (DynamicStructBuilder) Proto object Returns: (:class:TemporalMemory) TemporalMemory instance
-
reset
()¶ Indicates the start of a new sequence. Clears any predictions and makes sure synapses don’t grow to the currently active cells in the next time step.
-
setActivationThreshold
(activationThreshold)¶ Sets the activation threshold.
Parameters: activationThreshold – (int) activation threshold.
-
setConnectedPermanence
(connectedPermanence)¶ Sets the connected permanence.
Parameters: connectedPermanence – (float) The connected permanence.
-
setInitialPermanence
(initialPermanence)¶ Sets the initial permanence.
Parameters: initialPermanence – (float) The initial permanence.
-
setMaxNewSynapseCount
(maxNewSynapseCount)¶ Sets the max new synapse count.
Parameters: maxNewSynapseCount – (int) Max new synapse count.
-
setMinThreshold
(minThreshold)¶ Sets the min threshold.
Parameters: minThreshold – (int) min threshold.
-
setPermanenceDecrement
(permanenceDecrement)¶ Sets the permanence decrement.
Parameters: permanenceDecrement – (float) The permanence decrement.
-
setPermanenceIncrement
(permanenceIncrement)¶ Sets the permanence increment.
Parameters: permanenceIncrement – (float) The permanence increment.
-
setPredictedSegmentDecrement
(predictedSegmentDecrement)¶ Sets the predicted segment decrement.
Parameters: predictedSegmentDecrement – (float) The predicted segment decrement.
-
write
(proto)¶ Writes serialized data to proto object.
Parameters: proto – (DynamicStructBuilder) Proto object
- columnDimensions – (list or tuple) Dimensions of the column space.
Default value
Backtracking Temporal Memory¶
Temporal memory implementation.
This is the Python implementation and is used as the base class for the C++
implementation in BacktrackingTMCPP
.
-
class
nupic.algorithms.backtracking_tm.
BacktrackingTM
(numberOfCols=500, cellsPerColumn=10, initialPerm=0.11, connectedPerm=0.5, minThreshold=8, newSynapseCount=15, permanenceInc=0.1, permanenceDec=0.1, permanenceMax=1.0, globalDecay=0.1, activationThreshold=12, doPooling=False, segUpdateValidDuration=5, burnIn=2, collectStats=False, seed=42, verbosity=0, checkSynapseConsistency=False, pamLength=1, maxInfBacktrack=10, maxLrnBacktrack=5, maxAge=100000, maxSeqLength=32, maxSegmentsPerCell=-1, maxSynapsesPerSegment=-1, outputType='normal')¶ Bases:
nupic.support.console_printer.ConsolePrinterMixin
,nupic.serializable.Serializable
Class implementing the temporal memory algorithm as described in BAMI. The implementation here attempts to closely match the pseudocode in the documentation. This implementation does contain several additional bells and whistles such as a column confidence measure.
Parameters: - numberOfCols – (int) Number of mini-columns in the region. This values needs to be the same as the number of columns in the SP, if one is used.
- cellsPerColumn – (int) The number of cells per mini-column.
- initialPerm – (float) Initial permanence for newly created synapses.
- connectedPerm – TODO: document
- minThreshold – (int) Minimum number of active synapses for a segment to be considered during search for the best-matching segments.
- newSynapseCount – (int) The max number of synapses added to a segment during learning.
- permanenceInc – (float) Active synapses get their permanence counts incremented by this value.
- permanenceDec – (float) All other synapses get their permanence counts decremented by this value.
- permanenceMax – TODO: document
- maxAge –
(int) Number of iterations before global decay takes effect. Also the global decay execution interval. After global decay starts, it will will run again every
maxAge
iterations. IfmaxAge==1
, global decay is applied to every iteration to every segment.Note
Using
maxAge > 1
can significantly speed up the TM when global decay is used. - globalDecay –
(float) Value to decrease permanences when the global decay process runs. Global decay will remove synapses if their permanence value reaches 0. It will also remove segments when they no longer have synapses.
Note
Global decay is applied after
maxAge
iterations, after which it will run everymaxAge
iterations. - activationThreshold – (int) Number of synapses that must be active to activate a segment.
- doPooling – (bool) If True, pooling is enabled. False is the default.
- segUpdateValidDuration – TODO: document
- burnIn – (int) Used for evaluating the prediction score. Default is 2.
- collectStats – (bool) If True, collect training / inference stats. Default is False.
- seed – (int) Random number generator seed. The seed affects the random aspects of initialization like the initial permanence values. A fixed value ensures a reproducible result.
- verbosity –
(int) Controls the verbosity of the TM diagnostic output:
- verbosity == 0: silent
- verbosity in [1..6]: increasing levels of verbosity
- pamLength –
(int) Number of time steps to remain in “Pay Attention Mode” after we detect we’ve reached the end of a learned sequence. Setting this to 0 disables PAM mode. When we are in PAM mode, we do not burst unpredicted columns during learning, which in turn prevents us from falling into a previously learned sequence for a while (until we run through another ‘pamLength’ steps).
The advantage of PAM mode is that it requires fewer presentations to learn a set of sequences which share elements. The disadvantage of PAM mode is that if a learned sequence is immediately followed by set set of elements that should be learned as a 2nd sequence, the first
pamLength
elements of that sequence will not be learned as part of that 2nd sequence. - maxInfBacktrack – (int) How many previous inputs to keep in a buffer for inference backtracking.
- maxLrnBacktrack – (int) How many previous inputs to keep in a buffer for learning backtracking.
- maxSeqLength – (int) If not 0, we will never learn more than
maxSeqLength
inputs in a row without starting over at start cells. This sets an upper bound on the length of learned sequences and thus is another means (besidesmaxAge
andglobalDecay
) by which to limit how much the TM tries to learn. - maxSegmentsPerCell – (int) The maximum number of segments allowed on a
cell. This is used to turn on “fixed size CLA” mode. When in effect,
globalDecay
is not applicable and must be set to 0 andmaxAge
must be set to 0. When this is used (> 0),maxSynapsesPerSegment
must also be > 0. - maxSynapsesPerSegment – (int) The maximum number of synapses allowed in
a segment. This is used to turn on “fixed size CLA” mode. When in
effect,
globalDecay
is not applicable and must be set to 0, andmaxAge
must be set to 0. When this is used (> 0),maxSegmentsPerCell
must also be > 0. - outputType –
(string) Can be one of the following (default
normal
):normal
: output the OR of the active and predicted state.activeState
: output only the active state.activeState1CellPerCol
: output only the active state, and at most 1 cell/column. If more than 1 cell is active in a column, the one with the highest confidence is sent up.
-
compute
(bottomUpInput, enableLearn, enableInference=None)¶ Handle one compute, possibly learning.
Note
It is an error to have both
enableLearn
andenableInference
set to FalseNote
By default, we don’t compute the inference output when learning because it slows things down, but you can override this by passing in True for
enableInference
.Parameters: - bottomUpInput – The bottom-up input as numpy list, typically from a spatial pooler.
- enableLearn – (bool) If true, perform learning
- enableInference – (bool) If None, default behavior is to disable the
inference output when
enableLearn
is on. If true, compute the inference output. If false, do not compute the inference output.
Returns: TODO: document
-
finishLearning
()¶ Called when learning has been completed. This method just calls
trimSegments()
and then clears out caches.
-
getAvgLearnedSeqLength
()¶ Returns: Moving average of learned sequence length
-
getNumCells
()¶ Returns: (int) the total number of cells
-
getNumSegments
()¶ Returns: (int) the total number of segments
-
getNumSegmentsInCell
(c, i)¶ Parameters: - c – (int) column index
- i – (int) cell index within column
Returns: (int) the total number of synapses in cell (c, i)
-
getNumSynapses
()¶ Returns: (int) the total number of synapses
-
getNumSynapsesPerSegmentAvg
()¶ Returns: (int) the average number of synapses per segment
-
getPredictedState
()¶ Returns: numpy array of predicted cells, representing the current predicted state. predictedCells[c][i]
represents the state of the i’th cell in the c’th column.
-
getSegmentInfo
(collectActiveData=False)¶ Returns information about the distribution of segments, synapses and permanence values in the current TM. If requested, also returns information regarding the number of currently active segments and synapses.
Returns: tuple described below: ( nSegments, nSynapses, nActiveSegs, nActiveSynapses, distSegSizes, distNSegsPerCell, distPermValues, distAges )
nSegments
: (int) total number of segmentsnSynapses
: (int) total number of synapsesnActiveSegs
: (int) total number of active segments (0 ifcollectActiveData
is False)
nActiveSynapses
: (int) total number of active synapses 0 ifcollectActiveData
is False
distSegSizes
: (dict) where d[n] = number of segments with n synapsesdistNSegsPerCell
: (dict) where d[n] = number of cells with n segmentsdistPermValues
: (dict) where d[p] = number of synapses with perm = p/10distAges
: (list) of tuples (ageRange
,numSegments
)
-
getSegmentOnCell
(c, i, segIdx)¶ Parameters: - c – (int) column index
- i – (int) cell index in column
- segIdx – (int) segment index to match
Returns: (list) representing the the segment on cell (c, i) with index
segIdx
.[ [segmentID, sequenceSegmentFlag, positiveActivations, totalActivations, lastActiveIteration, lastPosDutyCycle, lastPosDutyCycleIteration], [col1, idx1, perm1], [col2, idx2, perm2], ... ]
-
getStats
()¶ Return the current learning and inference stats. This returns a dict containing all the learning and inference stats we have collected since the last
resetStats()
call. IfBacktrackingTM
collectStats
parameter is False, then None is returned.Returns: (dict) The following keys are returned in the dict when collectStats
is True:nPredictions
: the number of predictions. This is the total- number of inferences excluding burn-in and the last inference.
curPredictionScore
: the score for predicting the current input- (predicted during the previous inference)
curMissing
: the number of bits in the current input that were- not predicted to be on.
curExtra
: the number of bits in the predicted output that are- not in the next input
predictionScoreTotal
: the sum of every prediction score to datepredictionScoreAvg
:predictionScoreTotal / nPredictions
pctMissingTotal
: the total number of bits that were missed over- all predictions
pctMissingAvg
:pctMissingTotal / nPredictions
prevSequenceSignature
: signature for the sequence immediately- preceding the last reset. ‘None’ if
collectSequenceStats
is False.
-
infer
(bottomUpInput)¶ TODO: document
Parameters: bottomUpInput – Returns:
-
learn
(bottomUpInput, enableInference=None)¶ TODO: document
Parameters: - bottomUpInput –
- enableInference –
Returns:
-
loadFromFile
(filePath)¶ Implemented in
nupic.algorithms.backtracking_tm_cpp.BacktrackingTMCPP.loadFromFile()
.
-
predict
(nSteps)¶ This function gives the future predictions for <nSteps> timesteps starting from the current TM state. The TM is returned to its original state at the end before returning.
- We save the TM state.
- Loop for nSteps
- Turn-on with lateral support from the current active cells
- Set the predicted cells as the next step’s active cells. This step in learn and infer methods use input here to correct the predictions. We don’t use any input here.
- Revert back the TM state to the time before prediction
Parameters: nSteps – (int) The number of future time steps to be predicted Returns: all the future predictions - a numpy array of type “float32” and shape (nSteps, numberOfCols). The ith row gives the tm prediction for each column at a future timestep (t+i+1).
-
printActiveIndices
(state, andValues=False)¶ Print the list of
[column, cellIdx]
indices for each of the active cells in state.Parameters: - state – TODO: document
- andValues – TODO: document
-
printCell
(c, i, onlyActiveSegments=False)¶ TODO: document
Parameters: - c –
- i –
- onlyActiveSegments –
Returns:
-
printCells
(predictedOnly=False)¶ TODO: document
Parameters: predictedOnly – Returns:
-
printColConfidence
(aState, maxCols=20)¶ Print up to maxCols number from a flat floating point array.
Parameters: - aState – TODO: document
- maxCols – TODO: document
-
printComputeEnd
(output, learn=False)¶ Called at the end of inference to print out various diagnostic information based on the current verbosity level.
Parameters: - output – TODO: document
- learn – TODO: document
-
printConfidence
(aState, maxCols=20)¶ Print a floating point array that is the same shape as activeState.
Parameters: - aState – TODO: document
- maxCols – TODO: document
-
printInput
(x)¶ TODO: document
Parameters: x – Returns:
-
printOutput
(y)¶ TODO: document
Parameters: y – Returns:
-
printParameters
()¶ Print the parameter settings for the TM.
-
printSegmentUpdates
()¶ TODO: document
Returns:
-
printState
(aState)¶ Print an integer array that is the same shape as activeState.
Parameters: aState – TODO: document
-
printStates
(printPrevious=True, printLearnState=True)¶ TODO: document
Parameters: - printPrevious –
- printLearnState –
Returns:
-
classmethod
read
(proto)¶ Deserialize from proto instance.
Parameters: proto – (BacktrackingTMProto) the proto instance to read from
-
reset
()¶ Reset the state of all cells.
This is normally used between sequences while training. All internal states are reset to 0.
-
resetStats
()¶ Reset the learning and inference stats. This will usually be called by user code at the start of each inference run (for a particular data set).
-
saveToFile
(filePath)¶ Implemented in
nupic.algorithms.backtracking_tm_cpp.BacktrackingTMCPP.saveToFile()
.
-
topDownCompute
()¶ For now, we will assume there is no one above us and that bottomUpOut is simply the output that corresponds to our currently stored column confidences.
Returns: the same thing as columnConfidences()
-
trimSegments
(minPermanence=None, minNumSyns=None)¶ This method deletes all synapses whose permanence is less than minPermanence and deletes any segments that have less than minNumSyns synapses remaining.
Parameters: - minPermanence – (float) Any syn whose permanence is 0 or <
minPermanence
will be deleted. If None is passed in, thenself.connectedPerm
is used. - minNumSyns – (int) Any segment with less than
minNumSyns
synapses remaining in it will be deleted. If None is passed in, thenself.activationThreshold
is used.
Returns: (tuple)
numSegsRemoved
,numSynsRemoved
- minPermanence – (float) Any syn whose permanence is 0 or <
-
write
(proto)¶ Populate serialization proto instance.
Parameters: proto – (BacktrackingTMProto) the proto instance to populate
C++ Backtracking Temporal Memory¶
Temporal memory implementation in C++ wrapped by a Python class.
BacktrackingTMCPP
wraps the C++ algorithm execution by extending
BacktrackingTM
and overriding
compute()
.
-
class
nupic.algorithms.backtracking_tm_cpp.
BacktrackingTMCPP
(numberOfCols=500, cellsPerColumn=10, initialPerm=0.11, connectedPerm=0.5, minThreshold=8, newSynapseCount=15, permanenceInc=0.1, permanenceDec=0.1, permanenceMax=1.0, globalDecay=0.1, activationThreshold=12, doPooling=False, segUpdateValidDuration=5, burnIn=2, collectStats=False, seed=42, verbosity=0, checkSynapseConsistency=False, pamLength=1, maxInfBacktrack=10, maxLrnBacktrack=5, maxAge=100000, maxSeqLength=32, maxSegmentsPerCell=-1, maxSynapsesPerSegment=-1, outputType='normal')¶ Bases:
nupic.algorithms.backtracking_tm.BacktrackingTM
-
compute
(bottomUpInput, enableLearn, enableInference=None)¶ Overrides
nupic.algorithms.backtracking_tm.BacktrackingTM.compute()
.
-
finishLearning
()¶ Overrides
nupic.algorithms.backtracking_tm.BacktrackingTM.finishLearning()
.
-
getAvgLearnedSeqLength
()¶ Overrides
nupic.algorithms.backtracking_tm.BacktrackingTM.getAvgLearnedSeqLength()
.
-
getColCellIdx
(idx)¶ Get column and cell within column from a global cell index. The global index is
idx = colIdx * nCellsPerCol() + cellIdxInCol
Parameters: idx – (int) global cell index Returns: (tuple) (colIdx, cellIdxInCol)
-
getNumSegments
()¶ Overrides
nupic.algorithms.backtracking_tm.BacktrackingTM.getNumSegments()
.
-
getNumSegmentsInCell
(c, i)¶ Overrides
nupic.algorithms.backtracking_tm.BacktrackingTM.getNumSegmentsInCell()
.
-
getNumSynapses
()¶ Overrides
nupic.algorithms.backtracking_tm.BacktrackingTM.getNumSynapses()
.
-
getSegmentInfo
(collectActiveData=False)¶ Overrides
nupic.algorithms.backtracking_tm.BacktrackingTM.getSegmentInfo()
.
-
getSegmentOnCell
(c, i, segIdx)¶ Overrides
nupic.algorithms.backtracking_tm.BacktrackingTM.getSegmentOnCell()
.
-
loadFromFile
(filePath)¶ Load Cells4 state from a file saved with
saveToFile()
.
-
printCell
(c, i, onlyActiveSegments=False)¶ Overrides
nupic.algorithms.backtracking_tm.BacktrackingTM.printCell()
.
-
printSegmentUpdates
()¶ Overrides
nupic.algorithms.backtracking_tm.BacktrackingTM.printSegmentUpdates()
.
-
classmethod
read
(proto)¶ Deserialize from proto instance.
Parameters: proto – (BacktrackingTMCppProto) the proto instance to read from
-
reset
()¶ Overrides
nupic.algorithms.backtracking_tm.BacktrackingTM.reset()
.
-
saveToFile
(filePath)¶ Save Cells4 state to a file. File can be loaded with
loadFromFile()
.
-
trimSegments
(minPermanence=None, minNumSyns=None)¶ Overrides
nupic.algorithms.backtracking_tm.BacktrackingTM.trimSegments()
.
-
write
(proto)¶ Populate serialization proto instance.
Parameters: proto – (BacktrackingTMCppProto) the proto instance to populate
-
Connections¶
-
class
nupic.algorithms.connections.
Connections
(numCells)¶ Bases:
nupic.serializable.Serializable
Class to hold data representing the connectivity of a collection of cells.
Parameters: numCells – (int) Number of cells in collection. -
computeActivity
(activePresynapticCells, connectedPermanence)¶ Compute each segment’s number of active synapses for a given input. In the returned lists, a segment’s active synapse count is stored at index
segment.flatIdx
.Parameters: - activePresynapticCells – (iter) Active cells.
- connectedPermanence – (float) Permanence threshold for a synapse to be considered connected
Returns: (tuple) (
numActiveConnectedSynapsesForSegment
[list],numActivePotentialSynapsesForSegment
[list])
-
createSegment
(cell)¶ Adds a new segment on a cell.
Parameters: cell – (int) Cell index Returns: (int) New segment index
-
createSynapse
(segment, presynapticCell, permanence)¶ Creates a new synapse on a segment.
Parameters: - segment – (
Segment
) Segment object for synapse to be synapsed to. - presynapticCell – (int) Source cell index.
- permanence – (float) Initial permanence of synapse.
Returns: (
Synapse
) created synapse- segment – (
-
dataForSegment
(segment)¶ Returns the data for a segment.
Note
This method exists to match the interface of the C++ Connections. This allows tests and tools to inspect the connections using a common interface.
:param segment (
Segment
) :returns: segment data
-
dataForSynapse
(synapse)¶ Returns the data for a synapse.
Note
This method exists to match the interface of the C++ Connections. This allows tests and tools to inspect the connections using a common interface.
Parameters: synapse – ( Synapse
)Returns: Synapse data
-
destroySegment
(segment)¶ Destroys a segment.
Parameters: segment – ( Segment
) representing the segment to be destroyed.
-
getSegment
(cell, idx)¶ Returns a
Segment
object of the specified segment using data from theself._cells
array.Parameters: - cell – (int) cell index
- idx – (int) segment index on a cell
Returns: (
Segment
) Segment object with index idx on the specified cell
-
numSegments
(cell=None)¶ Returns the number of segments.
Parameters: cell – (int) Optional parameter to get the number of segments on a cell. Returns: (int) Number of segments on all cells if cell is not specified, or on a specific specified cell
-
numSynapses
(segment=None)¶ Returns the number of Synapses.
Parameters: segment – ( Segment
) Optional parameter to get the number of synapses on a segment.Returns: (int) Number of synapses on all segments if segment is not specified, or on a specified segment.
-
classmethod
read
(proto)¶ Reads deserialized data from proto object
Parameters: proto – (DynamicStructBuilder) Proto object Returns: ( Connections
) instance
-
segmentFlatListLength
()¶ Get the needed length for a list to hold a value for every segment’s flatIdx.
Returns: (int) Required list length
-
segmentForFlatIdx
(flatIdx)¶ Get the segment with the specified flatIdx.
Parameters: flatIdx – (int) The segment’s flattened list index. Returns: ( Segment
)
-
segmentPositionSortKey
(segment)¶ Return a numeric key for sorting this segment. This can be used with the python built-in
sorted()
function.Parameters: segment – ( Segment
) within thisConnections
instance.Returns: (float) A numeric key for sorting.
-
segmentsForCell
(cell)¶ Returns the segments that belong to a cell.
Parameters: cell – (int) Cell index Returns: (list) Segment objects representing segments on the given cell.
-
synapsesForPresynapticCell
(presynapticCell)¶ Returns the synapses for the source cell that they synapse on.
Parameters: presynapticCell – (int) Source cell index Returns: (set) Synapse
objects
-
synapsesForSegment
(segment)¶ Returns the synapses on a segment.
Parameters: segment – (int) Segment index Returns: (set) Synapse objects representing synapses on the given segment.
-
updateSynapsePermanence
(synapse, permanence)¶ Updates the permanence for a synapse.
Parameters: - synapse – (class:Synapse) to be updated.
- permanence – (float) New permanence.
-
write
(proto)¶ Writes serialized data to proto object.
Parameters: proto – (DynamicStructBuilder) Proto object
-
-
class
nupic.algorithms.connections.
Segment
(cell, flatIdx, ordinal)¶ Bases:
object
Class containing minimal information to identify a unique segment.
Parameters: - cell – (int) Index of the cell that this segment is on.
- flatIdx – (int) The segment’s flattened list index.
- ordinal – (long) Used to sort segments. The sort order needs to be consistent between implementations so that tie-breaking is consistent when finding the best matching segment.
-
class
nupic.algorithms.connections.
Synapse
(segment, presynapticCell, permanence, ordinal)¶ Bases:
object
Class containing minimal information to identify a unique synapse.
Parameters: - segment – (Object) Segment object that the synapse is synapsed to.
- presynapticCell – (int) The index of the presynaptic cell of the synapse.
- permanence – (float) Permanence of the synapse from 0.0 to 1.0.
- ordinal – (long) Used to sort synapses. The sort order needs to be consistent between implementations so that tie-breaking is consistent when finding the min permanence synapse.
-
nupic.algorithms.connections.
binSearch
(arr, val)¶ Function for running binary search on a sorted list.
Parameters: - arr – (list) a sorted list of integers to search
- val – (int) a integer to search for in the sorted array
Returns: (int) the index of the element if it is found and -1 otherwise.