repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
numenta/htmresearch
projects/energy_based_pooling/energy_based_models/foldiak.py
SparseCoder._seed
def _seed(self, seed=-1): """ Initialize the random seed """ if seed != -1: self._random = np.random.RandomState(seed) else: self._random = np.random.RandomState()
python
def _seed(self, seed=-1): """ Initialize the random seed """ if seed != -1: self._random = np.random.RandomState(seed) else: self._random = np.random.RandomState()
[ "def", "_seed", "(", "self", ",", "seed", "=", "-", "1", ")", ":", "if", "seed", "!=", "-", "1", ":", "self", ".", "_random", "=", "np", ".", "random", ".", "RandomState", "(", "seed", ")", "else", ":", "self", ".", "_random", "=", "np", ".", ...
Initialize the random seed
[ "Initialize", "the", "random", "seed" ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/energy_based_pooling/energy_based_models/foldiak.py#L87-L94
train
198,800
numenta/htmresearch
projects/energy_based_pooling/energy_based_models/foldiak.py
SparseCoder.initialize_weights
def initialize_weights(self): """Randomly initializes the visible-to-hidden connections.""" n = self._outputSize m = self._inputSize self._Q = self._random.sample((n,m)) # Normalize the weights of each units for i in range(n): self._Q[i] /= np.sqrt( np.dot(self._Q[i], self._Q[i]) )
python
def initialize_weights(self): """Randomly initializes the visible-to-hidden connections.""" n = self._outputSize m = self._inputSize self._Q = self._random.sample((n,m)) # Normalize the weights of each units for i in range(n): self._Q[i] /= np.sqrt( np.dot(self._Q[i], self._Q[i]) )
[ "def", "initialize_weights", "(", "self", ")", ":", "n", "=", "self", ".", "_outputSize", "m", "=", "self", ".", "_inputSize", "self", ".", "_Q", "=", "self", ".", "_random", ".", "sample", "(", "(", "n", ",", "m", ")", ")", "# Normalize the weights of...
Randomly initializes the visible-to-hidden connections.
[ "Randomly", "initializes", "the", "visible", "-", "to", "-", "hidden", "connections", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/energy_based_pooling/energy_based_models/foldiak.py#L97-L105
train
198,801
numenta/htmresearch
htmresearch/algorithms/lateral_pooler.py
LateralPooler._inhibitColumnsWithLateral
def _inhibitColumnsWithLateral(self, overlaps, lateralConnections): """ Performs an experimentatl local inhibition. Local inhibition is iteratively performed on a column by column basis. """ n,m = self.shape y = np.zeros(n) s = self.sparsity L = lateralConnections desiredWeight = self.codeWeight inhSignal = np.zeros(n) sortedIndices = np.argsort(overlaps, kind='mergesort')[::-1] currentWeight = 0 for i in sortedIndices: if overlaps[i] < self._stimulusThreshold: break inhTooStrong = ( inhSignal[i] >= s ) if not inhTooStrong: y[i] = 1. currentWeight += 1 inhSignal[:] += L[i,:] if self.enforceDesiredWeight and currentWeight == desiredWeight: break activeColumns = np.where(y==1.0)[0] return activeColumns
python
def _inhibitColumnsWithLateral(self, overlaps, lateralConnections): """ Performs an experimentatl local inhibition. Local inhibition is iteratively performed on a column by column basis. """ n,m = self.shape y = np.zeros(n) s = self.sparsity L = lateralConnections desiredWeight = self.codeWeight inhSignal = np.zeros(n) sortedIndices = np.argsort(overlaps, kind='mergesort')[::-1] currentWeight = 0 for i in sortedIndices: if overlaps[i] < self._stimulusThreshold: break inhTooStrong = ( inhSignal[i] >= s ) if not inhTooStrong: y[i] = 1. currentWeight += 1 inhSignal[:] += L[i,:] if self.enforceDesiredWeight and currentWeight == desiredWeight: break activeColumns = np.where(y==1.0)[0] return activeColumns
[ "def", "_inhibitColumnsWithLateral", "(", "self", ",", "overlaps", ",", "lateralConnections", ")", ":", "n", ",", "m", "=", "self", ".", "shape", "y", "=", "np", ".", "zeros", "(", "n", ")", "s", "=", "self", ".", "sparsity", "L", "=", "lateralConnecti...
Performs an experimentatl local inhibition. Local inhibition is iteratively performed on a column by column basis.
[ "Performs", "an", "experimentatl", "local", "inhibition", ".", "Local", "inhibition", "is", "iteratively", "performed", "on", "a", "column", "by", "column", "basis", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/lateral_pooler.py#L67-L98
train
198,802
numenta/htmresearch
htmresearch/algorithms/lateral_pooler.py
LateralPooler.compute
def compute(self, inputVector, learn, activeArray, applyLateralInhibition=True): """ This is the primary public method of the LateralPooler class. This function takes a input vector and outputs the indices of the active columns. If 'learn' is set to True, this method also updates the permanences of the columns and their lateral inhibitory connection weights. """ if not isinstance(inputVector, np.ndarray): raise TypeError("Input vector must be a numpy array, not %s" % str(type(inputVector))) if inputVector.size != self._numInputs: raise ValueError( "Input vector dimensions don't match. Expecting %s but got %s" % ( inputVector.size, self._numInputs)) self._updateBookeepingVars(learn) inputVector = np.array(inputVector, dtype=realDType) inputVector.reshape(-1) self._overlaps = self._calculateOverlap(inputVector) # Apply boosting when learning is on if learn: self._boostedOverlaps = self._boostFactors * self._overlaps else: self._boostedOverlaps = self._overlaps # Apply inhibition to determine the winning columns if applyLateralInhibition == True: activeColumns = self._inhibitColumnsWithLateral(self._boostedOverlaps, self.lateralConnections) else: activeColumns = self._inhibitColumns(self._boostedOverlaps) activeArray.fill(0) activeArray[activeColumns] = 1.0 if learn: self._adaptSynapses(inputVector, activeColumns, self._boostedOverlaps) self._updateDutyCycles(self._overlaps, activeColumns) self._bumpUpWeakColumns() self._updateBoostFactors() self._updateAvgActivityPairs(activeArray) epsilon = self.lateralLearningRate if epsilon > 0: self._updateLateralConnections(epsilon, self.avgActivityPairs) if self._isUpdateRound(): self._updateInhibitionRadius() self._updateMinDutyCycles() return activeArray
python
def compute(self, inputVector, learn, activeArray, applyLateralInhibition=True): """ This is the primary public method of the LateralPooler class. This function takes a input vector and outputs the indices of the active columns. If 'learn' is set to True, this method also updates the permanences of the columns and their lateral inhibitory connection weights. """ if not isinstance(inputVector, np.ndarray): raise TypeError("Input vector must be a numpy array, not %s" % str(type(inputVector))) if inputVector.size != self._numInputs: raise ValueError( "Input vector dimensions don't match. Expecting %s but got %s" % ( inputVector.size, self._numInputs)) self._updateBookeepingVars(learn) inputVector = np.array(inputVector, dtype=realDType) inputVector.reshape(-1) self._overlaps = self._calculateOverlap(inputVector) # Apply boosting when learning is on if learn: self._boostedOverlaps = self._boostFactors * self._overlaps else: self._boostedOverlaps = self._overlaps # Apply inhibition to determine the winning columns if applyLateralInhibition == True: activeColumns = self._inhibitColumnsWithLateral(self._boostedOverlaps, self.lateralConnections) else: activeColumns = self._inhibitColumns(self._boostedOverlaps) activeArray.fill(0) activeArray[activeColumns] = 1.0 if learn: self._adaptSynapses(inputVector, activeColumns, self._boostedOverlaps) self._updateDutyCycles(self._overlaps, activeColumns) self._bumpUpWeakColumns() self._updateBoostFactors() self._updateAvgActivityPairs(activeArray) epsilon = self.lateralLearningRate if epsilon > 0: self._updateLateralConnections(epsilon, self.avgActivityPairs) if self._isUpdateRound(): self._updateInhibitionRadius() self._updateMinDutyCycles() return activeArray
[ "def", "compute", "(", "self", ",", "inputVector", ",", "learn", ",", "activeArray", ",", "applyLateralInhibition", "=", "True", ")", ":", "if", "not", "isinstance", "(", "inputVector", ",", "np", ".", "ndarray", ")", ":", "raise", "TypeError", "(", "\"Inp...
This is the primary public method of the LateralPooler class. This function takes a input vector and outputs the indices of the active columns. If 'learn' is set to True, this method also updates the permanences of the columns and their lateral inhibitory connection weights.
[ "This", "is", "the", "primary", "public", "method", "of", "the", "LateralPooler", "class", ".", "This", "function", "takes", "a", "input", "vector", "and", "outputs", "the", "indices", "of", "the", "active", "columns", ".", "If", "learn", "is", "set", "to"...
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/lateral_pooler.py#L132-L182
train
198,803
numenta/htmresearch
htmresearch/algorithms/lateral_pooler.py
LateralPooler.feedforward
def feedforward(self): """ Soon to be depriciated. Needed to make the SP implementation compatible with some older code. """ m = self._numInputs n = self._numColumns W = np.zeros((n, m)) for i in range(self._numColumns): self.getPermanence(i, W[i, :]) return W
python
def feedforward(self): """ Soon to be depriciated. Needed to make the SP implementation compatible with some older code. """ m = self._numInputs n = self._numColumns W = np.zeros((n, m)) for i in range(self._numColumns): self.getPermanence(i, W[i, :]) return W
[ "def", "feedforward", "(", "self", ")", ":", "m", "=", "self", ".", "_numInputs", "n", "=", "self", ".", "_numColumns", "W", "=", "np", ".", "zeros", "(", "(", "n", ",", "m", ")", ")", "for", "i", "in", "range", "(", "self", ".", "_numColumns", ...
Soon to be depriciated. Needed to make the SP implementation compatible with some older code.
[ "Soon", "to", "be", "depriciated", ".", "Needed", "to", "make", "the", "SP", "implementation", "compatible", "with", "some", "older", "code", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/lateral_pooler.py#L201-L213
train
198,804
numenta/htmresearch
projects/union_path_integration/multi_column/multi_column_convergence.py
MultiColumnExperiment.learn
def learn(self): """ Learn all objects on every column. Each column will learn all the features of every object and store the the object's L2 representation to be later used in the inference stage """ self.setLearning(True) for obj in self.objects: self.sendReset() previousLocation = [None] * self.numColumns displacement = [0., 0.] features = obj["features"] numOfFeatures = len(features) # Randomize touch sequences touchSequence = np.random.permutation(numOfFeatures) for sensation in xrange(numOfFeatures): for col in xrange(self.numColumns): # Shift the touch sequence for each column colSequence = np.roll(touchSequence, col) feature = features[colSequence[sensation]] # Move the sensor to the center of the object locationOnObject = np.array([feature["top"] + feature["height"] / 2., feature["left"] + feature["width"] / 2.]) # Calculate displacement from previous location if previousLocation[col] is not None: displacement = locationOnObject - previousLocation[col] previousLocation[col] = locationOnObject # learn each pattern multiple times activeColumns = self.featureSDR[col][feature["name"]] for _ in xrange(self.numLearningPoints): # Sense feature at location self.motorInput[col].addDataToQueue(displacement) self.sensorInput[col].addDataToQueue(activeColumns, False, 0) # Only move to the location on the first sensation. displacement = [0, 0] self.network.run(numOfFeatures * self.numLearningPoints) # update L2 representations for the object self.learnedObjects[obj["name"]] = self.getL2Representations()
python
def learn(self): """ Learn all objects on every column. Each column will learn all the features of every object and store the the object's L2 representation to be later used in the inference stage """ self.setLearning(True) for obj in self.objects: self.sendReset() previousLocation = [None] * self.numColumns displacement = [0., 0.] features = obj["features"] numOfFeatures = len(features) # Randomize touch sequences touchSequence = np.random.permutation(numOfFeatures) for sensation in xrange(numOfFeatures): for col in xrange(self.numColumns): # Shift the touch sequence for each column colSequence = np.roll(touchSequence, col) feature = features[colSequence[sensation]] # Move the sensor to the center of the object locationOnObject = np.array([feature["top"] + feature["height"] / 2., feature["left"] + feature["width"] / 2.]) # Calculate displacement from previous location if previousLocation[col] is not None: displacement = locationOnObject - previousLocation[col] previousLocation[col] = locationOnObject # learn each pattern multiple times activeColumns = self.featureSDR[col][feature["name"]] for _ in xrange(self.numLearningPoints): # Sense feature at location self.motorInput[col].addDataToQueue(displacement) self.sensorInput[col].addDataToQueue(activeColumns, False, 0) # Only move to the location on the first sensation. displacement = [0, 0] self.network.run(numOfFeatures * self.numLearningPoints) # update L2 representations for the object self.learnedObjects[obj["name"]] = self.getL2Representations()
[ "def", "learn", "(", "self", ")", ":", "self", ".", "setLearning", "(", "True", ")", "for", "obj", "in", "self", ".", "objects", ":", "self", ".", "sendReset", "(", ")", "previousLocation", "=", "[", "None", "]", "*", "self", ".", "numColumns", "disp...
Learn all objects on every column. Each column will learn all the features of every object and store the the object's L2 representation to be later used in the inference stage
[ "Learn", "all", "objects", "on", "every", "column", ".", "Each", "column", "will", "learn", "all", "the", "features", "of", "every", "object", "and", "store", "the", "the", "object", "s", "L2", "representation", "to", "be", "later", "used", "in", "the", ...
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/union_path_integration/multi_column/multi_column_convergence.py#L181-L225
train
198,805
numenta/htmresearch
htmresearch/frameworks/layers/l2456_network_creation.py
createL2456Columns
def createL2456Columns(network, networkConfig): """ Create a network consisting of multiple L2456 columns as described in the file comments above. """ # Create each column numCorticalColumns = networkConfig["numCorticalColumns"] for i in xrange(numCorticalColumns): networkConfigCopy = copy.deepcopy(networkConfig) randomSeedBase = networkConfigCopy["randomSeedBase"] networkConfigCopy["L2Params"]["seed"] = randomSeedBase + i networkConfigCopy["L4Params"]["seed"] = randomSeedBase + i networkConfigCopy["L5Params"]["seed"] = randomSeedBase + i networkConfigCopy["L6Params"]["seed"] = randomSeedBase + i networkConfigCopy["L2Params"][ "numOtherCorticalColumns"] = numCorticalColumns - 1 networkConfigCopy["L5Params"][ "numOtherCorticalColumns"] = numCorticalColumns - 1 suffix = "_" + str(i) network = _createL2456Column(network, networkConfigCopy, suffix) # Now connect the L2 columns laterally to every other L2 column, and # the same for L5 columns. for i in range(networkConfig["numCorticalColumns"]): suffixSrc = "_" + str(i) for j in range(networkConfig["numCorticalColumns"]): if i != j: suffixDest = "_" + str(j) network.link( "L2Column" + suffixSrc, "L2Column" + suffixDest, "UniformLink", "", srcOutput="feedForwardOutput", destInput="lateralInput") network.link( "L5Column" + suffixSrc, "L5Column" + suffixDest, "UniformLink", "", srcOutput="feedForwardOutput", destInput="lateralInput") enableProfiling(network) return network
python
def createL2456Columns(network, networkConfig): """ Create a network consisting of multiple L2456 columns as described in the file comments above. """ # Create each column numCorticalColumns = networkConfig["numCorticalColumns"] for i in xrange(numCorticalColumns): networkConfigCopy = copy.deepcopy(networkConfig) randomSeedBase = networkConfigCopy["randomSeedBase"] networkConfigCopy["L2Params"]["seed"] = randomSeedBase + i networkConfigCopy["L4Params"]["seed"] = randomSeedBase + i networkConfigCopy["L5Params"]["seed"] = randomSeedBase + i networkConfigCopy["L6Params"]["seed"] = randomSeedBase + i networkConfigCopy["L2Params"][ "numOtherCorticalColumns"] = numCorticalColumns - 1 networkConfigCopy["L5Params"][ "numOtherCorticalColumns"] = numCorticalColumns - 1 suffix = "_" + str(i) network = _createL2456Column(network, networkConfigCopy, suffix) # Now connect the L2 columns laterally to every other L2 column, and # the same for L5 columns. for i in range(networkConfig["numCorticalColumns"]): suffixSrc = "_" + str(i) for j in range(networkConfig["numCorticalColumns"]): if i != j: suffixDest = "_" + str(j) network.link( "L2Column" + suffixSrc, "L2Column" + suffixDest, "UniformLink", "", srcOutput="feedForwardOutput", destInput="lateralInput") network.link( "L5Column" + suffixSrc, "L5Column" + suffixDest, "UniformLink", "", srcOutput="feedForwardOutput", destInput="lateralInput") enableProfiling(network) return network
[ "def", "createL2456Columns", "(", "network", ",", "networkConfig", ")", ":", "# Create each column", "numCorticalColumns", "=", "networkConfig", "[", "\"numCorticalColumns\"", "]", "for", "i", "in", "xrange", "(", "numCorticalColumns", ")", ":", "networkConfigCopy", "...
Create a network consisting of multiple L2456 columns as described in the file comments above.
[ "Create", "a", "network", "consisting", "of", "multiple", "L2456", "columns", "as", "described", "in", "the", "file", "comments", "above", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/l2456_network_creation.py#L244-L285
train
198,806
numenta/htmresearch
htmresearch/support/apical_tm_pair_monitor_mixin.py
ApicalTMPairMonitorMixin._mmComputeTransitionTraces
def _mmComputeTransitionTraces(self): """ Computes the transition traces, if necessary. Transition traces are the following: predicted => active cells predicted => inactive cells predicted => active columns predicted => inactive columns unpredicted => active columns """ if not self._mmTransitionTracesStale: return self._mmData["predictedActiveCellsForSequence"] = defaultdict(set) self._mmTraces["predictedActiveCells"] = IndicesTrace(self, "predicted => active cells (correct)") self._mmTraces["predictedInactiveCells"] = IndicesTrace(self, "predicted => inactive cells (extra)") self._mmTraces["predictedActiveColumns"] = IndicesTrace(self, "predicted => active columns (correct)") self._mmTraces["predictedInactiveColumns"] = IndicesTrace(self, "predicted => inactive columns (extra)") self._mmTraces["unpredictedActiveColumns"] = IndicesTrace(self, "unpredicted => active columns (bursting)") predictedCellsTrace = self._mmTraces["predictedCells"] for i, activeColumns in enumerate(self.mmGetTraceActiveColumns().data): predictedActiveCells = set() predictedInactiveCells = set() predictedActiveColumns = set() predictedInactiveColumns = set() for predictedCell in predictedCellsTrace.data[i]: predictedColumn = self.columnForCell(predictedCell) if predictedColumn in activeColumns: predictedActiveCells.add(predictedCell) predictedActiveColumns.add(predictedColumn) sequenceLabel = self.mmGetTraceSequenceLabels().data[i] if sequenceLabel is not None: self._mmData["predictedActiveCellsForSequence"][sequenceLabel].add( predictedCell) else: predictedInactiveCells.add(predictedCell) predictedInactiveColumns.add(predictedColumn) unpredictedActiveColumns = set(activeColumns) - set(predictedActiveColumns) self._mmTraces["predictedActiveCells"].data.append(predictedActiveCells) self._mmTraces["predictedInactiveCells"].data.append(predictedInactiveCells) self._mmTraces["predictedActiveColumns"].data.append(predictedActiveColumns) self._mmTraces["predictedInactiveColumns"].data.append( predictedInactiveColumns) self._mmTraces["unpredictedActiveColumns"].data.append( unpredictedActiveColumns) self._mmTransitionTracesStale = False
python
def _mmComputeTransitionTraces(self): """ Computes the transition traces, if necessary. Transition traces are the following: predicted => active cells predicted => inactive cells predicted => active columns predicted => inactive columns unpredicted => active columns """ if not self._mmTransitionTracesStale: return self._mmData["predictedActiveCellsForSequence"] = defaultdict(set) self._mmTraces["predictedActiveCells"] = IndicesTrace(self, "predicted => active cells (correct)") self._mmTraces["predictedInactiveCells"] = IndicesTrace(self, "predicted => inactive cells (extra)") self._mmTraces["predictedActiveColumns"] = IndicesTrace(self, "predicted => active columns (correct)") self._mmTraces["predictedInactiveColumns"] = IndicesTrace(self, "predicted => inactive columns (extra)") self._mmTraces["unpredictedActiveColumns"] = IndicesTrace(self, "unpredicted => active columns (bursting)") predictedCellsTrace = self._mmTraces["predictedCells"] for i, activeColumns in enumerate(self.mmGetTraceActiveColumns().data): predictedActiveCells = set() predictedInactiveCells = set() predictedActiveColumns = set() predictedInactiveColumns = set() for predictedCell in predictedCellsTrace.data[i]: predictedColumn = self.columnForCell(predictedCell) if predictedColumn in activeColumns: predictedActiveCells.add(predictedCell) predictedActiveColumns.add(predictedColumn) sequenceLabel = self.mmGetTraceSequenceLabels().data[i] if sequenceLabel is not None: self._mmData["predictedActiveCellsForSequence"][sequenceLabel].add( predictedCell) else: predictedInactiveCells.add(predictedCell) predictedInactiveColumns.add(predictedColumn) unpredictedActiveColumns = set(activeColumns) - set(predictedActiveColumns) self._mmTraces["predictedActiveCells"].data.append(predictedActiveCells) self._mmTraces["predictedInactiveCells"].data.append(predictedInactiveCells) self._mmTraces["predictedActiveColumns"].data.append(predictedActiveColumns) self._mmTraces["predictedInactiveColumns"].data.append( predictedInactiveColumns) self._mmTraces["unpredictedActiveColumns"].data.append( unpredictedActiveColumns) self._mmTransitionTracesStale = False
[ "def", "_mmComputeTransitionTraces", "(", "self", ")", ":", "if", "not", "self", ".", "_mmTransitionTracesStale", ":", "return", "self", ".", "_mmData", "[", "\"predictedActiveCellsForSequence\"", "]", "=", "defaultdict", "(", "set", ")", "self", ".", "_mmTraces",...
Computes the transition traces, if necessary. Transition traces are the following: predicted => active cells predicted => inactive cells predicted => active columns predicted => inactive columns unpredicted => active columns
[ "Computes", "the", "transition", "traces", "if", "necessary", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/apical_tm_pair_monitor_mixin.py#L274-L335
train
198,807
numenta/htmresearch
htmresearch/frameworks/poirazi_neuron_model/data_tools.py
get_biased_correlations
def get_biased_correlations(data, threshold= 10): """ Gets the highest few correlations for each bit, across the entirety of the data. Meant to provide a comparison point for the pairwise correlations reported in the literature, which are typically between neighboring neurons tuned to the same inputs. We would expect these neurons to be among the most correlated in any region, so pairwise correlations between most likely do not provide an unbiased estimator of correlations between arbitrary neurons. """ data = data.toDense() correlations = numpy.corrcoef(data, rowvar = False) highest_correlations = [] for row in correlations: highest_correlations += sorted(row, reverse = True)[1:threshold+1] return numpy.mean(highest_correlations)
python
def get_biased_correlations(data, threshold= 10): """ Gets the highest few correlations for each bit, across the entirety of the data. Meant to provide a comparison point for the pairwise correlations reported in the literature, which are typically between neighboring neurons tuned to the same inputs. We would expect these neurons to be among the most correlated in any region, so pairwise correlations between most likely do not provide an unbiased estimator of correlations between arbitrary neurons. """ data = data.toDense() correlations = numpy.corrcoef(data, rowvar = False) highest_correlations = [] for row in correlations: highest_correlations += sorted(row, reverse = True)[1:threshold+1] return numpy.mean(highest_correlations)
[ "def", "get_biased_correlations", "(", "data", ",", "threshold", "=", "10", ")", ":", "data", "=", "data", ".", "toDense", "(", ")", "correlations", "=", "numpy", ".", "corrcoef", "(", "data", ",", "rowvar", "=", "False", ")", "highest_correlations", "=", ...
Gets the highest few correlations for each bit, across the entirety of the data. Meant to provide a comparison point for the pairwise correlations reported in the literature, which are typically between neighboring neurons tuned to the same inputs. We would expect these neurons to be among the most correlated in any region, so pairwise correlations between most likely do not provide an unbiased estimator of correlations between arbitrary neurons.
[ "Gets", "the", "highest", "few", "correlations", "for", "each", "bit", "across", "the", "entirety", "of", "the", "data", ".", "Meant", "to", "provide", "a", "comparison", "point", "for", "the", "pairwise", "correlations", "reported", "in", "the", "literature",...
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/poirazi_neuron_model/data_tools.py#L27-L41
train
198,808
numenta/htmresearch
htmresearch/frameworks/poirazi_neuron_model/data_tools.py
get_pattern_correlations
def get_pattern_correlations(data): """ Gets the average correlation between all bits in patterns, across the entire dataset. Assumes input is a sparse matrix. Weighted by pattern rather than by bit; this is the average pairwise correlation for every pattern in the data, and is not the average pairwise correlation for all bits that ever cooccur. This is a subtle but important difference. """ patterns = [data.rowNonZeros(i)[0] for i in range(data.nRows())] dense_data = data.toDense() correlations = numpy.corrcoef(dense_data, rowvar = False) correlations = numpy.nan_to_num(correlations) pattern_correlations = [] for pattern in patterns: pattern_correlations.append([correlations[i, j] for i in pattern for j in pattern if i != j]) return numpy.mean(pattern_correlations)
python
def get_pattern_correlations(data): """ Gets the average correlation between all bits in patterns, across the entire dataset. Assumes input is a sparse matrix. Weighted by pattern rather than by bit; this is the average pairwise correlation for every pattern in the data, and is not the average pairwise correlation for all bits that ever cooccur. This is a subtle but important difference. """ patterns = [data.rowNonZeros(i)[0] for i in range(data.nRows())] dense_data = data.toDense() correlations = numpy.corrcoef(dense_data, rowvar = False) correlations = numpy.nan_to_num(correlations) pattern_correlations = [] for pattern in patterns: pattern_correlations.append([correlations[i, j] for i in pattern for j in pattern if i != j]) return numpy.mean(pattern_correlations)
[ "def", "get_pattern_correlations", "(", "data", ")", ":", "patterns", "=", "[", "data", ".", "rowNonZeros", "(", "i", ")", "[", "0", "]", "for", "i", "in", "range", "(", "data", ".", "nRows", "(", ")", ")", "]", "dense_data", "=", "data", ".", "toD...
Gets the average correlation between all bits in patterns, across the entire dataset. Assumes input is a sparse matrix. Weighted by pattern rather than by bit; this is the average pairwise correlation for every pattern in the data, and is not the average pairwise correlation for all bits that ever cooccur. This is a subtle but important difference.
[ "Gets", "the", "average", "correlation", "between", "all", "bits", "in", "patterns", "across", "the", "entire", "dataset", ".", "Assumes", "input", "is", "a", "sparse", "matrix", ".", "Weighted", "by", "pattern", "rather", "than", "by", "bit", ";", "this", ...
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/poirazi_neuron_model/data_tools.py#L43-L60
train
198,809
numenta/htmresearch
htmresearch/frameworks/poirazi_neuron_model/data_tools.py
generate_correlated_data
def generate_correlated_data(dim = 2000, num_active = 40, num_samples = 1000, num_cells_per_cluster_size = [2000]*8, cluster_sizes = range(2, 10)): """ Generates a set of data drawn from a uniform distribution, but with bits clustered to force correlation between neurons. Clusters are randomly chosen to form an activation pattern, in such a way as to maintain sparsity. The number of clusters of each size is defined by num_cells_per_cluster_size, as cluster_size*num_clusters = num_cells. This parameter can be thought of as indicating how thoroughly the clusters "cover" the space. Typical values are 1-3 times the total dimension. These are specificied independently for each cluster size, to allow for more variation. """ # Chooses clusters to clusters = [] cells = set(range(dim)) # Associate cluster sizes with how many cells they should have, then generate # clusters. for size, num_cells in zip(cluster_sizes, num_cells_per_cluster_size): # Must have (num_cells/size) clusters in order to have num_cells cells # across all clusters with this size. for i in range(int(1.*num_cells/size)): cluster = tuple(numpy.random.choice(dim, size, replace = False)) clusters.append(cluster) # Now generate a list of num_samples SDRs datapoints = [] for sample in range(num_samples): # This conditional is necessary in the case that very, very few clusters are # created, as otherwise numpy.random.choice can attempt to choose more # clusters than is possible. Typically this case will not occur, but it is # possible if we are attempting to generate extremely correlated data. if len(clusters) > num_active/2: chosen_clusters = numpy.random.choice(len(clusters), num_active/2, replace = False) current_clusters = [clusters[i] for i in chosen_clusters] else: current_clusters = clusters # Pick clusters until doing so would exceed our target num_active. current_cells = set() for cluster in current_clusters: if len(current_cells) + len(cluster) < num_active: current_cells |= set(cluster) else: break # Add random cells to the SDR if we still don't have enough active. if len(current_cells) < num_active: possible_cells = cells - current_cells new_cells = numpy.random.choice(tuple(possible_cells), num_active - len(current_cells), replace = False) current_cells |= set(new_cells) datapoints.append(list(current_cells)) data = SM32() data.reshape(num_samples, dim) for sample, datapoint in enumerate(datapoints): for i in datapoint: data[sample, i] = 1. return data
python
def generate_correlated_data(dim = 2000, num_active = 40, num_samples = 1000, num_cells_per_cluster_size = [2000]*8, cluster_sizes = range(2, 10)): """ Generates a set of data drawn from a uniform distribution, but with bits clustered to force correlation between neurons. Clusters are randomly chosen to form an activation pattern, in such a way as to maintain sparsity. The number of clusters of each size is defined by num_cells_per_cluster_size, as cluster_size*num_clusters = num_cells. This parameter can be thought of as indicating how thoroughly the clusters "cover" the space. Typical values are 1-3 times the total dimension. These are specificied independently for each cluster size, to allow for more variation. """ # Chooses clusters to clusters = [] cells = set(range(dim)) # Associate cluster sizes with how many cells they should have, then generate # clusters. for size, num_cells in zip(cluster_sizes, num_cells_per_cluster_size): # Must have (num_cells/size) clusters in order to have num_cells cells # across all clusters with this size. for i in range(int(1.*num_cells/size)): cluster = tuple(numpy.random.choice(dim, size, replace = False)) clusters.append(cluster) # Now generate a list of num_samples SDRs datapoints = [] for sample in range(num_samples): # This conditional is necessary in the case that very, very few clusters are # created, as otherwise numpy.random.choice can attempt to choose more # clusters than is possible. Typically this case will not occur, but it is # possible if we are attempting to generate extremely correlated data. if len(clusters) > num_active/2: chosen_clusters = numpy.random.choice(len(clusters), num_active/2, replace = False) current_clusters = [clusters[i] for i in chosen_clusters] else: current_clusters = clusters # Pick clusters until doing so would exceed our target num_active. current_cells = set() for cluster in current_clusters: if len(current_cells) + len(cluster) < num_active: current_cells |= set(cluster) else: break # Add random cells to the SDR if we still don't have enough active. if len(current_cells) < num_active: possible_cells = cells - current_cells new_cells = numpy.random.choice(tuple(possible_cells), num_active - len(current_cells), replace = False) current_cells |= set(new_cells) datapoints.append(list(current_cells)) data = SM32() data.reshape(num_samples, dim) for sample, datapoint in enumerate(datapoints): for i in datapoint: data[sample, i] = 1. return data
[ "def", "generate_correlated_data", "(", "dim", "=", "2000", ",", "num_active", "=", "40", ",", "num_samples", "=", "1000", ",", "num_cells_per_cluster_size", "=", "[", "2000", "]", "*", "8", ",", "cluster_sizes", "=", "range", "(", "2", ",", "10", ")", "...
Generates a set of data drawn from a uniform distribution, but with bits clustered to force correlation between neurons. Clusters are randomly chosen to form an activation pattern, in such a way as to maintain sparsity. The number of clusters of each size is defined by num_cells_per_cluster_size, as cluster_size*num_clusters = num_cells. This parameter can be thought of as indicating how thoroughly the clusters "cover" the space. Typical values are 1-3 times the total dimension. These are specificied independently for each cluster size, to allow for more variation.
[ "Generates", "a", "set", "of", "data", "drawn", "from", "a", "uniform", "distribution", "but", "with", "bits", "clustered", "to", "force", "correlation", "between", "neurons", ".", "Clusters", "are", "randomly", "chosen", "to", "form", "an", "activation", "pat...
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/poirazi_neuron_model/data_tools.py#L62-L129
train
198,810
numenta/htmresearch
htmresearch/frameworks/poirazi_neuron_model/data_tools.py
apply_noise
def apply_noise(data, noise): """ Applies noise to a sparse matrix. Noise can be an integer between 0 and 100, indicating the percentage of ones in the original input to move, or a float in [0, 1), indicating the same thing. The input matrix is modified in-place, and nothing is returned. This operation does not affect the sparsity of the matrix, or of any individual datapoint. """ if noise >= 1: noise = noise/100. for i in range(data.nRows()): ones = data.rowNonZeros(i)[0] replace_indices = numpy.random.choice(ones, size = int(len(ones)*noise), replace = False) for index in replace_indices: data[i, index] = 0 new_indices = numpy.random.choice(data.nCols(), size = int(len(ones)*noise), replace = False) for index in new_indices: while data[i, index] == 1: index = numpy.random.randint(0, data.nCols()) data[i, index] = 1
python
def apply_noise(data, noise): """ Applies noise to a sparse matrix. Noise can be an integer between 0 and 100, indicating the percentage of ones in the original input to move, or a float in [0, 1), indicating the same thing. The input matrix is modified in-place, and nothing is returned. This operation does not affect the sparsity of the matrix, or of any individual datapoint. """ if noise >= 1: noise = noise/100. for i in range(data.nRows()): ones = data.rowNonZeros(i)[0] replace_indices = numpy.random.choice(ones, size = int(len(ones)*noise), replace = False) for index in replace_indices: data[i, index] = 0 new_indices = numpy.random.choice(data.nCols(), size = int(len(ones)*noise), replace = False) for index in new_indices: while data[i, index] == 1: index = numpy.random.randint(0, data.nCols()) data[i, index] = 1
[ "def", "apply_noise", "(", "data", ",", "noise", ")", ":", "if", "noise", ">=", "1", ":", "noise", "=", "noise", "/", "100.", "for", "i", "in", "range", "(", "data", ".", "nRows", "(", ")", ")", ":", "ones", "=", "data", ".", "rowNonZeros", "(", ...
Applies noise to a sparse matrix. Noise can be an integer between 0 and 100, indicating the percentage of ones in the original input to move, or a float in [0, 1), indicating the same thing. The input matrix is modified in-place, and nothing is returned. This operation does not affect the sparsity of the matrix, or of any individual datapoint.
[ "Applies", "noise", "to", "a", "sparse", "matrix", ".", "Noise", "can", "be", "an", "integer", "between", "0", "and", "100", "indicating", "the", "percentage", "of", "ones", "in", "the", "original", "input", "to", "move", "or", "a", "float", "in", "[", ...
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/poirazi_neuron_model/data_tools.py#L131-L156
train
198,811
numenta/htmresearch
htmresearch/frameworks/poirazi_neuron_model/data_tools.py
shuffle_sparse_matrix_and_labels
def shuffle_sparse_matrix_and_labels(matrix, labels): """ Shuffles a sparse matrix and set of labels together. Resorts to densifying and then re-sparsifying the matrix, for convenience. Still very fast. """ print "Shuffling data" new_matrix = matrix.toDense() rng_state = numpy.random.get_state() numpy.random.shuffle(new_matrix) numpy.random.set_state(rng_state) numpy.random.shuffle(labels) print "Data shuffled" return SM32(new_matrix), numpy.asarray(labels)
python
def shuffle_sparse_matrix_and_labels(matrix, labels): """ Shuffles a sparse matrix and set of labels together. Resorts to densifying and then re-sparsifying the matrix, for convenience. Still very fast. """ print "Shuffling data" new_matrix = matrix.toDense() rng_state = numpy.random.get_state() numpy.random.shuffle(new_matrix) numpy.random.set_state(rng_state) numpy.random.shuffle(labels) print "Data shuffled" return SM32(new_matrix), numpy.asarray(labels)
[ "def", "shuffle_sparse_matrix_and_labels", "(", "matrix", ",", "labels", ")", ":", "print", "\"Shuffling data\"", "new_matrix", "=", "matrix", ".", "toDense", "(", ")", "rng_state", "=", "numpy", ".", "random", ".", "get_state", "(", ")", "numpy", ".", "random...
Shuffles a sparse matrix and set of labels together. Resorts to densifying and then re-sparsifying the matrix, for convenience. Still very fast.
[ "Shuffles", "a", "sparse", "matrix", "and", "set", "of", "labels", "together", ".", "Resorts", "to", "densifying", "and", "then", "re", "-", "sparsifying", "the", "matrix", "for", "convenience", ".", "Still", "very", "fast", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/poirazi_neuron_model/data_tools.py#L158-L172
train
198,812
numenta/htmresearch
htmresearch/frameworks/poirazi_neuron_model/data_tools.py
split_sparse_matrix
def split_sparse_matrix(matrix, num_categories): """ An analog of numpy.split for our sparse matrix. If the number of categories does not divide the number of rows in the matrix, all overflow is placed in the final bin. In the event that there are more categories than rows, all later categories are considered to be an empty sparse matrix. """ if matrix.nRows() < num_categories: return [matrix.getSlice(i, i+1, 0, matrix.nCols()) for i in range(matrix.nRows())] + [SM32() for i in range(num_categories - matrix.nRows())] else: inc = matrix.nRows()/num_categories divisions = [matrix.getSlice(i*inc, (i+1)*inc, 0, matrix.nCols()) for i in range(num_categories - 1)] # Handle the last bin separately. All overflow goes into it. divisions.append(matrix.getSlice((num_categories - 1)*inc, matrix.nRows(), 0, matrix.nCols())) return divisions
python
def split_sparse_matrix(matrix, num_categories): """ An analog of numpy.split for our sparse matrix. If the number of categories does not divide the number of rows in the matrix, all overflow is placed in the final bin. In the event that there are more categories than rows, all later categories are considered to be an empty sparse matrix. """ if matrix.nRows() < num_categories: return [matrix.getSlice(i, i+1, 0, matrix.nCols()) for i in range(matrix.nRows())] + [SM32() for i in range(num_categories - matrix.nRows())] else: inc = matrix.nRows()/num_categories divisions = [matrix.getSlice(i*inc, (i+1)*inc, 0, matrix.nCols()) for i in range(num_categories - 1)] # Handle the last bin separately. All overflow goes into it. divisions.append(matrix.getSlice((num_categories - 1)*inc, matrix.nRows(), 0, matrix.nCols())) return divisions
[ "def", "split_sparse_matrix", "(", "matrix", ",", "num_categories", ")", ":", "if", "matrix", ".", "nRows", "(", ")", "<", "num_categories", ":", "return", "[", "matrix", ".", "getSlice", "(", "i", ",", "i", "+", "1", ",", "0", ",", "matrix", ".", "n...
An analog of numpy.split for our sparse matrix. If the number of categories does not divide the number of rows in the matrix, all overflow is placed in the final bin. In the event that there are more categories than rows, all later categories are considered to be an empty sparse matrix.
[ "An", "analog", "of", "numpy", ".", "split", "for", "our", "sparse", "matrix", ".", "If", "the", "number", "of", "categories", "does", "not", "divide", "the", "number", "of", "rows", "in", "the", "matrix", "all", "overflow", "is", "placed", "in", "the", ...
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/poirazi_neuron_model/data_tools.py#L174-L196
train
198,813
numenta/htmresearch
htmresearch/frameworks/poirazi_neuron_model/data_tools.py
generate_phase_1
def generate_phase_1(dim = 40): """ The first step in creating datapoints in the Poirazi & Mel model. This returns a vector of dimension dim, with the last four values set to 1 and the rest drawn from a normal distribution. """ phase_1 = numpy.random.normal(0, 1, dim) for i in range(dim - 4, dim): phase_1[i] = 1.0 return phase_1
python
def generate_phase_1(dim = 40): """ The first step in creating datapoints in the Poirazi & Mel model. This returns a vector of dimension dim, with the last four values set to 1 and the rest drawn from a normal distribution. """ phase_1 = numpy.random.normal(0, 1, dim) for i in range(dim - 4, dim): phase_1[i] = 1.0 return phase_1
[ "def", "generate_phase_1", "(", "dim", "=", "40", ")", ":", "phase_1", "=", "numpy", ".", "random", ".", "normal", "(", "0", ",", "1", ",", "dim", ")", "for", "i", "in", "range", "(", "dim", "-", "4", ",", "dim", ")", ":", "phase_1", "[", "i", ...
The first step in creating datapoints in the Poirazi & Mel model. This returns a vector of dimension dim, with the last four values set to 1 and the rest drawn from a normal distribution.
[ "The", "first", "step", "in", "creating", "datapoints", "in", "the", "Poirazi", "&", "Mel", "model", ".", "This", "returns", "a", "vector", "of", "dimension", "dim", "with", "the", "last", "four", "values", "set", "to", "1", "and", "the", "rest", "drawn"...
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/poirazi_neuron_model/data_tools.py#L281-L290
train
198,814
numenta/htmresearch
htmresearch/frameworks/poirazi_neuron_model/data_tools.py
generate_phase_2
def generate_phase_2(phase_1, dim = 40): """ The second step in creating datapoints in the Poirazi & Mel model. This takes a phase 1 vector, and creates a phase 2 vector where each point is the product of four elements of the phase 1 vector, randomly drawn with replacement. """ phase_2 = [] for i in range(dim): indices = [numpy.random.randint(0, dim) for i in range(4)] phase_2.append(numpy.prod([phase_1[i] for i in indices])) return phase_2
python
def generate_phase_2(phase_1, dim = 40): """ The second step in creating datapoints in the Poirazi & Mel model. This takes a phase 1 vector, and creates a phase 2 vector where each point is the product of four elements of the phase 1 vector, randomly drawn with replacement. """ phase_2 = [] for i in range(dim): indices = [numpy.random.randint(0, dim) for i in range(4)] phase_2.append(numpy.prod([phase_1[i] for i in indices])) return phase_2
[ "def", "generate_phase_2", "(", "phase_1", ",", "dim", "=", "40", ")", ":", "phase_2", "=", "[", "]", "for", "i", "in", "range", "(", "dim", ")", ":", "indices", "=", "[", "numpy", ".", "random", ".", "randint", "(", "0", ",", "dim", ")", "for", ...
The second step in creating datapoints in the Poirazi & Mel model. This takes a phase 1 vector, and creates a phase 2 vector where each point is the product of four elements of the phase 1 vector, randomly drawn with replacement.
[ "The", "second", "step", "in", "creating", "datapoints", "in", "the", "Poirazi", "&", "Mel", "model", ".", "This", "takes", "a", "phase", "1", "vector", "and", "creates", "a", "phase", "2", "vector", "where", "each", "point", "is", "the", "product", "of"...
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/poirazi_neuron_model/data_tools.py#L292-L303
train
198,815
numenta/htmresearch
htmresearch/frameworks/poirazi_neuron_model/data_tools.py
bin_number
def bin_number(datapoint, intervals): """ Given a datapoint and intervals representing bins, returns the number represented in binned form, where the bin including the value is set to 1 and all others are 0. """ index = numpy.searchsorted(intervals, datapoint) return [0 if index != i else 1 for i in range(len(intervals) + 1)]
python
def bin_number(datapoint, intervals): """ Given a datapoint and intervals representing bins, returns the number represented in binned form, where the bin including the value is set to 1 and all others are 0. """ index = numpy.searchsorted(intervals, datapoint) return [0 if index != i else 1 for i in range(len(intervals) + 1)]
[ "def", "bin_number", "(", "datapoint", ",", "intervals", ")", ":", "index", "=", "numpy", ".", "searchsorted", "(", "intervals", ",", "datapoint", ")", "return", "[", "0", "if", "index", "!=", "i", "else", "1", "for", "i", "in", "range", "(", "len", ...
Given a datapoint and intervals representing bins, returns the number represented in binned form, where the bin including the value is set to 1 and all others are 0.
[ "Given", "a", "datapoint", "and", "intervals", "representing", "bins", "returns", "the", "number", "represented", "in", "binned", "form", "where", "the", "bin", "including", "the", "value", "is", "set", "to", "1", "and", "all", "others", "are", "0", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/poirazi_neuron_model/data_tools.py#L331-L339
train
198,816
numenta/htmresearch
htmresearch/frameworks/poirazi_neuron_model/data_tools.py
bin_data
def bin_data(data, dim = 40, num_bins = 10): """ Fully bins the data generated by generate_data, using generate_RF_bins and bin_number. """ intervals = generate_RF_bins(data, dim, num_bins) binned_data = [numpy.concatenate([bin_number(data[x][i], intervals[i]) for i in range(len(data[x]))]) for x in range(len(data))] return binned_data
python
def bin_data(data, dim = 40, num_bins = 10): """ Fully bins the data generated by generate_data, using generate_RF_bins and bin_number. """ intervals = generate_RF_bins(data, dim, num_bins) binned_data = [numpy.concatenate([bin_number(data[x][i], intervals[i]) for i in range(len(data[x]))]) for x in range(len(data))] return binned_data
[ "def", "bin_data", "(", "data", ",", "dim", "=", "40", ",", "num_bins", "=", "10", ")", ":", "intervals", "=", "generate_RF_bins", "(", "data", ",", "dim", ",", "num_bins", ")", "binned_data", "=", "[", "numpy", ".", "concatenate", "(", "[", "bin_numbe...
Fully bins the data generated by generate_data, using generate_RF_bins and bin_number.
[ "Fully", "bins", "the", "data", "generated", "by", "generate_data", "using", "generate_RF_bins", "and", "bin_number", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/poirazi_neuron_model/data_tools.py#L341-L349
train
198,817
numenta/htmresearch
projects/sequence_prediction/discrete_sequences/elm/suite.py
Suite.killCells
def killCells(self, killCellPercent): """ kill a fraction of cells from the network """ if killCellPercent <= 0: return numHiddenNeurons = self.net.numHiddenNeurons numDead = round(killCellPercent * numHiddenNeurons) zombiePermutation = numpy.random.permutation(numHiddenNeurons) deadCells = zombiePermutation[0:numDead] liveCells = zombiePermutation[numDead:] self.net.inputWeights = self.net.inputWeights[liveCells, :] self.net.bias = self.net.bias[:, liveCells] self.net.beta = self.net.beta[liveCells, :] self.net.M = self.net.M[liveCells, liveCells] self.net.numHiddenNeurons = numHiddenNeurons - numDead
python
def killCells(self, killCellPercent): """ kill a fraction of cells from the network """ if killCellPercent <= 0: return numHiddenNeurons = self.net.numHiddenNeurons numDead = round(killCellPercent * numHiddenNeurons) zombiePermutation = numpy.random.permutation(numHiddenNeurons) deadCells = zombiePermutation[0:numDead] liveCells = zombiePermutation[numDead:] self.net.inputWeights = self.net.inputWeights[liveCells, :] self.net.bias = self.net.bias[:, liveCells] self.net.beta = self.net.beta[liveCells, :] self.net.M = self.net.M[liveCells, liveCells] self.net.numHiddenNeurons = numHiddenNeurons - numDead
[ "def", "killCells", "(", "self", ",", "killCellPercent", ")", ":", "if", "killCellPercent", "<=", "0", ":", "return", "numHiddenNeurons", "=", "self", ".", "net", ".", "numHiddenNeurons", "numDead", "=", "round", "(", "killCellPercent", "*", "numHiddenNeurons", ...
kill a fraction of cells from the network
[ "kill", "a", "fraction", "of", "cells", "from", "the", "network" ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sequence_prediction/discrete_sequences/elm/suite.py#L308-L326
train
198,818
numenta/htmresearch
projects/cio_sdr/cio_bit_frequency.py
printFrequencyStatistics
def printFrequencyStatistics(counts, frequencies, numWords, size): """ Print interesting statistics regarding the counts and frequency matrices """ avgBits = float(counts.sum())/numWords print "Retina width=128, height=128" print "Total number of words processed=",numWords print "Average number of bits per word=",avgBits, print "avg sparsity=",avgBits/size print "counts matrix sum=",counts.sum(), print "max=",counts.max(), "min=",counts.min(), print "mean=",counts.sum()/float(size) print "frequency matrix sum=",frequencies.sum(), print "max=",frequencies.max(), "min=",frequencies.min(), print "mean=",frequencies.sum()/float(size) print "Number of bits with zero entries",frequencies.nZeroCols()
python
def printFrequencyStatistics(counts, frequencies, numWords, size): """ Print interesting statistics regarding the counts and frequency matrices """ avgBits = float(counts.sum())/numWords print "Retina width=128, height=128" print "Total number of words processed=",numWords print "Average number of bits per word=",avgBits, print "avg sparsity=",avgBits/size print "counts matrix sum=",counts.sum(), print "max=",counts.max(), "min=",counts.min(), print "mean=",counts.sum()/float(size) print "frequency matrix sum=",frequencies.sum(), print "max=",frequencies.max(), "min=",frequencies.min(), print "mean=",frequencies.sum()/float(size) print "Number of bits with zero entries",frequencies.nZeroCols()
[ "def", "printFrequencyStatistics", "(", "counts", ",", "frequencies", ",", "numWords", ",", "size", ")", ":", "avgBits", "=", "float", "(", "counts", ".", "sum", "(", ")", ")", "/", "numWords", "print", "\"Retina width=128, height=128\"", "print", "\"Total numbe...
Print interesting statistics regarding the counts and frequency matrices
[ "Print", "interesting", "statistics", "regarding", "the", "counts", "and", "frequency", "matrices" ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/cio_sdr/cio_bit_frequency.py#L38-L53
train
198,819
numenta/htmresearch
projects/cio_sdr/cio_bit_frequency.py
countRandomBitFrequencies
def countRandomBitFrequencies(numTerms = 100000, percentSparsity = 0.01): """Create a uniformly random counts matrix through sampling.""" # Accumulate counts by inplace-adding sparse matrices counts = SparseMatrix() size = 128*128 counts.resize(1, size) # Pre-allocate buffer sparse matrix sparseBitmap = SparseMatrix() sparseBitmap.resize(1, size) random.seed(42) # Accumulate counts for each bit for each word numWords=0 for term in xrange(numTerms): bitmap = random.sample(xrange(size), int(size*percentSparsity)) bitmap.sort() sparseBitmap.setRowFromSparse(0, bitmap, [1]*len(bitmap)) counts += sparseBitmap numWords += 1 # Compute normalized version of counts as a separate matrix frequencies = SparseMatrix() frequencies.resize(1, size) frequencies.copy(counts) frequencies.divide(float(numWords)) # Wrap up by printing some statistics and then saving the normalized version printFrequencyStatistics(counts, frequencies, numWords, size) frequencyFilename = "bit_frequencies_random.pkl" print "Saving frequency matrix in",frequencyFilename with open(frequencyFilename, "wb") as frequencyPickleFile: pickle.dump(frequencies, frequencyPickleFile) return counts
python
def countRandomBitFrequencies(numTerms = 100000, percentSparsity = 0.01): """Create a uniformly random counts matrix through sampling.""" # Accumulate counts by inplace-adding sparse matrices counts = SparseMatrix() size = 128*128 counts.resize(1, size) # Pre-allocate buffer sparse matrix sparseBitmap = SparseMatrix() sparseBitmap.resize(1, size) random.seed(42) # Accumulate counts for each bit for each word numWords=0 for term in xrange(numTerms): bitmap = random.sample(xrange(size), int(size*percentSparsity)) bitmap.sort() sparseBitmap.setRowFromSparse(0, bitmap, [1]*len(bitmap)) counts += sparseBitmap numWords += 1 # Compute normalized version of counts as a separate matrix frequencies = SparseMatrix() frequencies.resize(1, size) frequencies.copy(counts) frequencies.divide(float(numWords)) # Wrap up by printing some statistics and then saving the normalized version printFrequencyStatistics(counts, frequencies, numWords, size) frequencyFilename = "bit_frequencies_random.pkl" print "Saving frequency matrix in",frequencyFilename with open(frequencyFilename, "wb") as frequencyPickleFile: pickle.dump(frequencies, frequencyPickleFile) return counts
[ "def", "countRandomBitFrequencies", "(", "numTerms", "=", "100000", ",", "percentSparsity", "=", "0.01", ")", ":", "# Accumulate counts by inplace-adding sparse matrices", "counts", "=", "SparseMatrix", "(", ")", "size", "=", "128", "*", "128", "counts", ".", "resiz...
Create a uniformly random counts matrix through sampling.
[ "Create", "a", "uniformly", "random", "counts", "matrix", "through", "sampling", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/cio_sdr/cio_bit_frequency.py#L56-L93
train
198,820
numenta/htmresearch
projects/cio_sdr/cio_bit_frequency.py
plotlyFrequencyHistogram
def plotlyFrequencyHistogram(counts): """ x-axis is a count of how many times a bit was active y-axis is number of bits that have that frequency """ data = [ go.Histogram( x=tuple(count for _, _, count in counts.getNonZerosSorted()) ) ] py.plot(data, filename=os.environ.get("HEATMAP_NAME", str(datetime.datetime.now())))
python
def plotlyFrequencyHistogram(counts): """ x-axis is a count of how many times a bit was active y-axis is number of bits that have that frequency """ data = [ go.Histogram( x=tuple(count for _, _, count in counts.getNonZerosSorted()) ) ] py.plot(data, filename=os.environ.get("HEATMAP_NAME", str(datetime.datetime.now())))
[ "def", "plotlyFrequencyHistogram", "(", "counts", ")", ":", "data", "=", "[", "go", ".", "Histogram", "(", "x", "=", "tuple", "(", "count", "for", "_", ",", "_", ",", "count", "in", "counts", ".", "getNonZerosSorted", "(", ")", ")", ")", "]", "py", ...
x-axis is a count of how many times a bit was active y-axis is number of bits that have that frequency
[ "x", "-", "axis", "is", "a", "count", "of", "how", "many", "times", "a", "bit", "was", "active", "y", "-", "axis", "is", "number", "of", "bits", "that", "have", "that", "frequency" ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/cio_sdr/cio_bit_frequency.py#L167-L178
train
198,821
numenta/htmresearch
projects/sdr_paper/scalar_sdrs.py
getSparseTensor
def getSparseTensor(numNonzeros, inputSize, outputSize, onlyPositive=False, fixedRange=1.0/24): """ Return a random tensor that is initialized like a weight matrix Size is outputSize X inputSize, where weightSparsity% of each row is non-zero """ # Initialize weights in the typical fashion. w = torch.Tensor(outputSize, inputSize, ) if onlyPositive: w.data.uniform_(0, fixedRange) else: w.data.uniform_(-fixedRange, fixedRange) # Zero out weights for sparse weight matrices if numNonzeros < inputSize: numZeros = inputSize - numNonzeros outputIndices = np.arange(outputSize) inputIndices = np.array([np.random.permutation(inputSize)[:numZeros] for _ in outputIndices], dtype=np.long) # Create tensor indices for all non-zero weights zeroIndices = np.empty((outputSize, numZeros, 2), dtype=np.long) zeroIndices[:, :, 0] = outputIndices[:, None] zeroIndices[:, :, 1] = inputIndices zeroIndices = torch.LongTensor(zeroIndices.reshape(-1, 2)) zeroWts = (zeroIndices[:, 0], zeroIndices[:, 1]) w.data[zeroWts] = 0.0 return w
python
def getSparseTensor(numNonzeros, inputSize, outputSize, onlyPositive=False, fixedRange=1.0/24): """ Return a random tensor that is initialized like a weight matrix Size is outputSize X inputSize, where weightSparsity% of each row is non-zero """ # Initialize weights in the typical fashion. w = torch.Tensor(outputSize, inputSize, ) if onlyPositive: w.data.uniform_(0, fixedRange) else: w.data.uniform_(-fixedRange, fixedRange) # Zero out weights for sparse weight matrices if numNonzeros < inputSize: numZeros = inputSize - numNonzeros outputIndices = np.arange(outputSize) inputIndices = np.array([np.random.permutation(inputSize)[:numZeros] for _ in outputIndices], dtype=np.long) # Create tensor indices for all non-zero weights zeroIndices = np.empty((outputSize, numZeros, 2), dtype=np.long) zeroIndices[:, :, 0] = outputIndices[:, None] zeroIndices[:, :, 1] = inputIndices zeroIndices = torch.LongTensor(zeroIndices.reshape(-1, 2)) zeroWts = (zeroIndices[:, 0], zeroIndices[:, 1]) w.data[zeroWts] = 0.0 return w
[ "def", "getSparseTensor", "(", "numNonzeros", ",", "inputSize", ",", "outputSize", ",", "onlyPositive", "=", "False", ",", "fixedRange", "=", "1.0", "/", "24", ")", ":", "# Initialize weights in the typical fashion.", "w", "=", "torch", ".", "Tensor", "(", "outp...
Return a random tensor that is initialized like a weight matrix Size is outputSize X inputSize, where weightSparsity% of each row is non-zero
[ "Return", "a", "random", "tensor", "that", "is", "initialized", "like", "a", "weight", "matrix", "Size", "is", "outputSize", "X", "inputSize", "where", "weightSparsity%", "of", "each", "row", "is", "non", "-", "zero" ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sdr_paper/scalar_sdrs.py#L67-L99
train
198,822
numenta/htmresearch
projects/sdr_paper/scalar_sdrs.py
getPermutedTensors
def getPermutedTensors(W, kw, n, m2, noisePct): """ Generate m2 noisy versions of W. Noisy version of W is generated by randomly permuting noisePct of the non-zero components to other components. :param W: :param n: :param m2: :param noisePct: :return: """ W2 = W.repeat(m2, 1) nz = W[0].nonzero() numberToZero = int(round(noisePct * kw)) for i in range(m2): indices = np.random.permutation(kw)[0:numberToZero] for j in indices: W2[i,nz[j]] = 0 return W2
python
def getPermutedTensors(W, kw, n, m2, noisePct): """ Generate m2 noisy versions of W. Noisy version of W is generated by randomly permuting noisePct of the non-zero components to other components. :param W: :param n: :param m2: :param noisePct: :return: """ W2 = W.repeat(m2, 1) nz = W[0].nonzero() numberToZero = int(round(noisePct * kw)) for i in range(m2): indices = np.random.permutation(kw)[0:numberToZero] for j in indices: W2[i,nz[j]] = 0 return W2
[ "def", "getPermutedTensors", "(", "W", ",", "kw", ",", "n", ",", "m2", ",", "noisePct", ")", ":", "W2", "=", "W", ".", "repeat", "(", "m2", ",", "1", ")", "nz", "=", "W", "[", "0", "]", ".", "nonzero", "(", ")", "numberToZero", "=", "int", "(...
Generate m2 noisy versions of W. Noisy version of W is generated by randomly permuting noisePct of the non-zero components to other components. :param W: :param n: :param m2: :param noisePct: :return:
[ "Generate", "m2", "noisy", "versions", "of", "W", ".", "Noisy", "version", "of", "W", "is", "generated", "by", "randomly", "permuting", "noisePct", "of", "the", "non", "-", "zero", "components", "to", "other", "components", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sdr_paper/scalar_sdrs.py#L102-L122
train
198,823
numenta/htmresearch
projects/sdr_paper/scalar_sdrs.py
getTheta
def getTheta(k, nTrials=100000): """ Estimate a reasonable value of theta for this k. """ theDots = np.zeros(nTrials) w1 = getSparseTensor(k, k, nTrials, fixedRange=1.0/k) for i in range(nTrials): theDots[i] = w1[i].dot(w1[i]) dotMean = theDots.mean() print("k=", k, "min/mean/max diag of w dot products", theDots.min(), dotMean, theDots.max()) theta = dotMean / 2.0 print("Using theta as mean / 2.0 = ", theta) return theta, theDots
python
def getTheta(k, nTrials=100000): """ Estimate a reasonable value of theta for this k. """ theDots = np.zeros(nTrials) w1 = getSparseTensor(k, k, nTrials, fixedRange=1.0/k) for i in range(nTrials): theDots[i] = w1[i].dot(w1[i]) dotMean = theDots.mean() print("k=", k, "min/mean/max diag of w dot products", theDots.min(), dotMean, theDots.max()) theta = dotMean / 2.0 print("Using theta as mean / 2.0 = ", theta) return theta, theDots
[ "def", "getTheta", "(", "k", ",", "nTrials", "=", "100000", ")", ":", "theDots", "=", "np", ".", "zeros", "(", "nTrials", ")", "w1", "=", "getSparseTensor", "(", "k", ",", "k", ",", "nTrials", ",", "fixedRange", "=", "1.0", "/", "k", ")", "for", ...
Estimate a reasonable value of theta for this k.
[ "Estimate", "a", "reasonable", "value", "of", "theta", "for", "this", "k", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sdr_paper/scalar_sdrs.py#L136-L152
train
198,824
numenta/htmresearch
projects/sdr_paper/scalar_sdrs.py
returnFalseNegatives
def returnFalseNegatives(kw, noisePct, n, theta): """ Generate a weight vector W, with kw non-zero components. Generate 1000 noisy versions of W and return the match statistics. Noisy version of W is generated by randomly setting noisePct of the non-zero components to zero. :param kw: k for the weight vectors :param noisePct: percent noise, from 0 to 1 :param n: dimensionality of input vector :param theta: threshold for matching after dot product :return: percent that matched, number that matched, total match comparisons """ W = getSparseTensor(kw, n, 1, fixedRange=1.0 / kw) # Get permuted versions of W and see how many match m2 = 10 inputVectors = getPermutedTensors(W, kw, n, m2, noisePct) dot = inputVectors.matmul(W.t()) numMatches = ((dot >= theta).sum()).item() pctMatches = numMatches / float(m2) return pctMatches, numMatches, m2
python
def returnFalseNegatives(kw, noisePct, n, theta): """ Generate a weight vector W, with kw non-zero components. Generate 1000 noisy versions of W and return the match statistics. Noisy version of W is generated by randomly setting noisePct of the non-zero components to zero. :param kw: k for the weight vectors :param noisePct: percent noise, from 0 to 1 :param n: dimensionality of input vector :param theta: threshold for matching after dot product :return: percent that matched, number that matched, total match comparisons """ W = getSparseTensor(kw, n, 1, fixedRange=1.0 / kw) # Get permuted versions of W and see how many match m2 = 10 inputVectors = getPermutedTensors(W, kw, n, m2, noisePct) dot = inputVectors.matmul(W.t()) numMatches = ((dot >= theta).sum()).item() pctMatches = numMatches / float(m2) return pctMatches, numMatches, m2
[ "def", "returnFalseNegatives", "(", "kw", ",", "noisePct", ",", "n", ",", "theta", ")", ":", "W", "=", "getSparseTensor", "(", "kw", ",", "n", ",", "1", ",", "fixedRange", "=", "1.0", "/", "kw", ")", "# Get permuted versions of W and see how many match", "m2...
Generate a weight vector W, with kw non-zero components. Generate 1000 noisy versions of W and return the match statistics. Noisy version of W is generated by randomly setting noisePct of the non-zero components to zero. :param kw: k for the weight vectors :param noisePct: percent noise, from 0 to 1 :param n: dimensionality of input vector :param theta: threshold for matching after dot product :return: percent that matched, number that matched, total match comparisons
[ "Generate", "a", "weight", "vector", "W", "with", "kw", "non", "-", "zero", "components", ".", "Generate", "1000", "noisy", "versions", "of", "W", "and", "return", "the", "match", "statistics", ".", "Noisy", "version", "of", "W", "is", "generated", "by", ...
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sdr_paper/scalar_sdrs.py#L182-L206
train
198,825
numenta/htmresearch
projects/sdr_paper/scalar_sdrs.py
computeScaledProbabilities
def computeScaledProbabilities( listOfScales=[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0], listofkValues=[64, 128, 256], kw=32, n=1000, numWorkers=10, nTrials=1000, ): """ Compute the impact of S on match probabilities for a fixed value of n. """ # Create arguments for the possibilities we want to test args = [] theta, _ = getTheta(kw) for ki, k in enumerate(listofkValues): for si, s in enumerate(listOfScales): args.append({ "k": k, "kw": kw, "n": n, "theta": theta, "nTrials": nTrials, "inputScaling": s, "errorIndex": [ki, si], }) result = computeMatchProbabilityParallel(args, numWorkers) errors = np.zeros((len(listofkValues), len(listOfScales))) for r in result: errors[r["errorIndex"][0], r["errorIndex"][1]] = r["pctMatches"] print("Errors using scaled inputs, for kw=", kw) print(repr(errors)) plotScaledMatches(listofkValues, listOfScales, errors, "images/scalar_effect_of_scale_kw" + str(kw) + ".pdf")
python
def computeScaledProbabilities( listOfScales=[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0], listofkValues=[64, 128, 256], kw=32, n=1000, numWorkers=10, nTrials=1000, ): """ Compute the impact of S on match probabilities for a fixed value of n. """ # Create arguments for the possibilities we want to test args = [] theta, _ = getTheta(kw) for ki, k in enumerate(listofkValues): for si, s in enumerate(listOfScales): args.append({ "k": k, "kw": kw, "n": n, "theta": theta, "nTrials": nTrials, "inputScaling": s, "errorIndex": [ki, si], }) result = computeMatchProbabilityParallel(args, numWorkers) errors = np.zeros((len(listofkValues), len(listOfScales))) for r in result: errors[r["errorIndex"][0], r["errorIndex"][1]] = r["pctMatches"] print("Errors using scaled inputs, for kw=", kw) print(repr(errors)) plotScaledMatches(listofkValues, listOfScales, errors, "images/scalar_effect_of_scale_kw" + str(kw) + ".pdf")
[ "def", "computeScaledProbabilities", "(", "listOfScales", "=", "[", "1.0", ",", "1.5", ",", "2.0", ",", "2.5", ",", "3.0", ",", "3.5", ",", "4.0", "]", ",", "listofkValues", "=", "[", "64", ",", "128", ",", "256", "]", ",", "kw", "=", "32", ",", ...
Compute the impact of S on match probabilities for a fixed value of n.
[ "Compute", "the", "impact", "of", "S", "on", "match", "probabilities", "for", "a", "fixed", "value", "of", "n", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sdr_paper/scalar_sdrs.py#L389-L420
train
198,826
numenta/htmresearch
projects/sdr_paper/scalar_sdrs.py
computeMatchProbabilityOmega
def computeMatchProbabilityOmega(k, bMax, theta, nTrials=100): """ The Omega match probability estimates the probability of matching when both vectors have exactly b components in common. This function computes this probability for b=1 to bMax. For each value of b this function: 1) Creates nTrials instances of Xw(b) which are vectors with b components where each component is uniform in [-1/k, 1/k]. 2) Creates nTrials instances of Xi(b) which are vectors with b components where each component is uniform in [0, 2/k]. 3) Does every possible dot product of Xw(b) dot Xi(b), i.e. nTrials * nTrials dot products. 4) Counts the fraction of cases where Xw(b) dot Xi(b) >= theta Returns an array with bMax entries, where each entry contains the probability computed in 4). """ omegaProb = np.zeros(bMax+1) for b in range(1, bMax+1): xwb = getSparseTensor(b, b, nTrials, fixedRange=1.0/k) xib = getSparseTensor(b, b, nTrials, onlyPositive=True, fixedRange=2.0/k) r = xwb.matmul(xib.t()) numMatches = ((r >= theta).sum()).item() omegaProb[b] = numMatches / float(nTrials * nTrials) print(omegaProb) return omegaProb
python
def computeMatchProbabilityOmega(k, bMax, theta, nTrials=100): """ The Omega match probability estimates the probability of matching when both vectors have exactly b components in common. This function computes this probability for b=1 to bMax. For each value of b this function: 1) Creates nTrials instances of Xw(b) which are vectors with b components where each component is uniform in [-1/k, 1/k]. 2) Creates nTrials instances of Xi(b) which are vectors with b components where each component is uniform in [0, 2/k]. 3) Does every possible dot product of Xw(b) dot Xi(b), i.e. nTrials * nTrials dot products. 4) Counts the fraction of cases where Xw(b) dot Xi(b) >= theta Returns an array with bMax entries, where each entry contains the probability computed in 4). """ omegaProb = np.zeros(bMax+1) for b in range(1, bMax+1): xwb = getSparseTensor(b, b, nTrials, fixedRange=1.0/k) xib = getSparseTensor(b, b, nTrials, onlyPositive=True, fixedRange=2.0/k) r = xwb.matmul(xib.t()) numMatches = ((r >= theta).sum()).item() omegaProb[b] = numMatches / float(nTrials * nTrials) print(omegaProb) return omegaProb
[ "def", "computeMatchProbabilityOmega", "(", "k", ",", "bMax", ",", "theta", ",", "nTrials", "=", "100", ")", ":", "omegaProb", "=", "np", ".", "zeros", "(", "bMax", "+", "1", ")", "for", "b", "in", "range", "(", "1", ",", "bMax", "+", "1", ")", "...
The Omega match probability estimates the probability of matching when both vectors have exactly b components in common. This function computes this probability for b=1 to bMax. For each value of b this function: 1) Creates nTrials instances of Xw(b) which are vectors with b components where each component is uniform in [-1/k, 1/k]. 2) Creates nTrials instances of Xi(b) which are vectors with b components where each component is uniform in [0, 2/k]. 3) Does every possible dot product of Xw(b) dot Xi(b), i.e. nTrials * nTrials dot products. 4) Counts the fraction of cases where Xw(b) dot Xi(b) >= theta Returns an array with bMax entries, where each entry contains the probability computed in 4).
[ "The", "Omega", "match", "probability", "estimates", "the", "probability", "of", "matching", "when", "both", "vectors", "have", "exactly", "b", "components", "in", "common", ".", "This", "function", "computes", "this", "probability", "for", "b", "=", "1", "to"...
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sdr_paper/scalar_sdrs.py#L424-L458
train
198,827
numenta/htmresearch
projects/sdr_paper/scalar_sdrs.py
plotMatches2
def plotMatches2(listofNValues, errors, listOfScales, scaleErrors, fileName = "images/scalar_matches.pdf"): """ Plot two figures side by side in an aspect ratio appropriate for the paper. """ w, h = figaspect(0.4) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(w,h)) plotMatches(listofNValues, errors, fileName=None, fig=fig, ax=ax1) plotScaledMatches(listOfScales, scaleErrors, fileName=None, fig=fig, ax=ax2) plt.savefig(fileName) plt.close()
python
def plotMatches2(listofNValues, errors, listOfScales, scaleErrors, fileName = "images/scalar_matches.pdf"): """ Plot two figures side by side in an aspect ratio appropriate for the paper. """ w, h = figaspect(0.4) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(w,h)) plotMatches(listofNValues, errors, fileName=None, fig=fig, ax=ax1) plotScaledMatches(listOfScales, scaleErrors, fileName=None, fig=fig, ax=ax2) plt.savefig(fileName) plt.close()
[ "def", "plotMatches2", "(", "listofNValues", ",", "errors", ",", "listOfScales", ",", "scaleErrors", ",", "fileName", "=", "\"images/scalar_matches.pdf\"", ")", ":", "w", ",", "h", "=", "figaspect", "(", "0.4", ")", "fig", ",", "(", "ax1", ",", "ax2", ")",...
Plot two figures side by side in an aspect ratio appropriate for the paper.
[ "Plot", "two", "figures", "side", "by", "side", "in", "an", "aspect", "ratio", "appropriate", "for", "the", "paper", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sdr_paper/scalar_sdrs.py#L570-L583
train
198,828
numenta/htmresearch
projects/sdr_paper/scalar_sdrs.py
createPregeneratedGraphs
def createPregeneratedGraphs(): """ Creates graphs based on previous runs of the scripts. Useful for editing graph format for writeups. """ # Graph for computeMatchProbabilities(kw=32, nTrials=3000) listofNValues = [250, 500, 1000, 1500, 2000, 2500] kw = 32 errors = np.array([ [3.65083333e-03, 3.06166667e-04, 1.89166667e-05, 4.16666667e-06, 1.50000000e-06, 9.16666667e-07], [2.44633333e-02, 3.64491667e-03, 3.16083333e-04, 6.93333333e-05, 2.16666667e-05, 8.66666667e-06], [7.61641667e-02, 2.42496667e-02, 3.75608333e-03, 9.78333333e-04, 3.33250000e-04, 1.42250000e-04], [2.31302500e-02, 2.38609167e-02, 2.28072500e-02, 2.33225000e-02, 2.30650000e-02, 2.33988333e-02] ]) # Graph for computeScaledProbabilities(nTrials=3000) listOfScales = [1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0] scaleErrors = np.array([ [1.94166667e-05, 1.14900000e-03, 7.20725000e-03, 1.92405833e-02, 3.60794167e-02, 5.70276667e-02, 7.88510833e-02], [3.12500000e-04, 7.07616667e-03, 2.71600000e-02, 5.72415833e-02, 8.95497500e-02, 1.21294333e-01, 1.50582500e-01], [3.97708333e-03, 3.31468333e-02, 8.04755833e-02, 1.28687750e-01, 1.71220000e-01, 2.07019250e-01, 2.34703167e-01] ]) plotMatches2(listofNValues, errors, listOfScales, scaleErrors, "images/scalar_matches_kw" + str(kw) + ".pdf")
python
def createPregeneratedGraphs(): """ Creates graphs based on previous runs of the scripts. Useful for editing graph format for writeups. """ # Graph for computeMatchProbabilities(kw=32, nTrials=3000) listofNValues = [250, 500, 1000, 1500, 2000, 2500] kw = 32 errors = np.array([ [3.65083333e-03, 3.06166667e-04, 1.89166667e-05, 4.16666667e-06, 1.50000000e-06, 9.16666667e-07], [2.44633333e-02, 3.64491667e-03, 3.16083333e-04, 6.93333333e-05, 2.16666667e-05, 8.66666667e-06], [7.61641667e-02, 2.42496667e-02, 3.75608333e-03, 9.78333333e-04, 3.33250000e-04, 1.42250000e-04], [2.31302500e-02, 2.38609167e-02, 2.28072500e-02, 2.33225000e-02, 2.30650000e-02, 2.33988333e-02] ]) # Graph for computeScaledProbabilities(nTrials=3000) listOfScales = [1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0] scaleErrors = np.array([ [1.94166667e-05, 1.14900000e-03, 7.20725000e-03, 1.92405833e-02, 3.60794167e-02, 5.70276667e-02, 7.88510833e-02], [3.12500000e-04, 7.07616667e-03, 2.71600000e-02, 5.72415833e-02, 8.95497500e-02, 1.21294333e-01, 1.50582500e-01], [3.97708333e-03, 3.31468333e-02, 8.04755833e-02, 1.28687750e-01, 1.71220000e-01, 2.07019250e-01, 2.34703167e-01] ]) plotMatches2(listofNValues, errors, listOfScales, scaleErrors, "images/scalar_matches_kw" + str(kw) + ".pdf")
[ "def", "createPregeneratedGraphs", "(", ")", ":", "# Graph for computeMatchProbabilities(kw=32, nTrials=3000)", "listofNValues", "=", "[", "250", ",", "500", ",", "1000", ",", "1500", ",", "2000", ",", "2500", "]", "kw", "=", "32", "errors", "=", "np", ".", "a...
Creates graphs based on previous runs of the scripts. Useful for editing graph format for writeups.
[ "Creates", "graphs", "based", "on", "previous", "runs", "of", "the", "scripts", ".", "Useful", "for", "editing", "graph", "format", "for", "writeups", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sdr_paper/scalar_sdrs.py#L587-L620
train
198,829
numenta/htmresearch
htmresearch/algorithms/location_modules.py
ThresholdedGaussian2DLocationModule._learn
def _learn(connections, rng, learningSegments, activeInput, potentialOverlaps, initialPermanence, sampleSize, permanenceIncrement, permanenceDecrement, maxSynapsesPerSegment): """ Adjust synapse permanences, grow new synapses, and grow new segments. @param learningActiveSegments (numpy array) @param learningMatchingSegments (numpy array) @param segmentsToPunish (numpy array) @param activeInput (numpy array) @param potentialOverlaps (numpy array) """ # Learn on existing segments connections.adjustSynapses(learningSegments, activeInput, permanenceIncrement, -permanenceDecrement) # Grow new synapses. Calculate "maxNew", the maximum number of synapses to # grow per segment. "maxNew" might be a number or it might be a list of # numbers. if sampleSize == -1: maxNew = len(activeInput) else: maxNew = sampleSize - potentialOverlaps[learningSegments] if maxSynapsesPerSegment != -1: synapseCounts = connections.mapSegmentsToSynapseCounts( learningSegments) numSynapsesToReachMax = maxSynapsesPerSegment - synapseCounts maxNew = np.where(maxNew <= numSynapsesToReachMax, maxNew, numSynapsesToReachMax) connections.growSynapsesToSample(learningSegments, activeInput, maxNew, initialPermanence, rng)
python
def _learn(connections, rng, learningSegments, activeInput, potentialOverlaps, initialPermanence, sampleSize, permanenceIncrement, permanenceDecrement, maxSynapsesPerSegment): """ Adjust synapse permanences, grow new synapses, and grow new segments. @param learningActiveSegments (numpy array) @param learningMatchingSegments (numpy array) @param segmentsToPunish (numpy array) @param activeInput (numpy array) @param potentialOverlaps (numpy array) """ # Learn on existing segments connections.adjustSynapses(learningSegments, activeInput, permanenceIncrement, -permanenceDecrement) # Grow new synapses. Calculate "maxNew", the maximum number of synapses to # grow per segment. "maxNew" might be a number or it might be a list of # numbers. if sampleSize == -1: maxNew = len(activeInput) else: maxNew = sampleSize - potentialOverlaps[learningSegments] if maxSynapsesPerSegment != -1: synapseCounts = connections.mapSegmentsToSynapseCounts( learningSegments) numSynapsesToReachMax = maxSynapsesPerSegment - synapseCounts maxNew = np.where(maxNew <= numSynapsesToReachMax, maxNew, numSynapsesToReachMax) connections.growSynapsesToSample(learningSegments, activeInput, maxNew, initialPermanence, rng)
[ "def", "_learn", "(", "connections", ",", "rng", ",", "learningSegments", ",", "activeInput", ",", "potentialOverlaps", ",", "initialPermanence", ",", "sampleSize", ",", "permanenceIncrement", ",", "permanenceDecrement", ",", "maxSynapsesPerSegment", ")", ":", "# Lear...
Adjust synapse permanences, grow new synapses, and grow new segments. @param learningActiveSegments (numpy array) @param learningMatchingSegments (numpy array) @param segmentsToPunish (numpy array) @param activeInput (numpy array) @param potentialOverlaps (numpy array)
[ "Adjust", "synapse", "permanences", "grow", "new", "synapses", "and", "grow", "new", "segments", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/location_modules.py#L314-L346
train
198,830
numenta/htmresearch
htmresearch/algorithms/location_modules.py
BodyToSpecificObjectModule2D.compute
def compute(self, sensorToBodyByColumn, sensorToSpecificObjectByColumn): """ Compute the "body's location relative to a specific object" from an array of "sensor's location relative to a specific object" and an array of "sensor's location relative to body" These arrays consist of one module per cortical column. This is a metric computation, similar to that of the SensorToSpecificObjectModule, but with voting. In effect, the columns vote on "the body's location relative to a specific object". Note: Each column can vote for an arbitrary number of cells, but it can't vote for a single cell more than once. This is necessary because we don't want ambiguity in a column to cause some cells to get extra votes. There are a few ways that this could be biologically plausible: - Explanation 1: Nearby dendritic segments are independent coincidence detectors, but perhaps their dendritic spikes don't sum. Meanwhile, maybe dendritic spikes from far away dendritic segments do sum. - Explanation 2: Dendritic spikes from different columns are separated temporally, not spatially. All the spikes from one column "arrive" at the cell at the same time, but the dendritic spikes from other columns arrive at other times. With each of these temporally-separated dendritic spikes, the unsupported cells are inhibited, or the spikes' effects are summed. - Explanation 3: Another population of cells within the cortical column might calculate the "body's location relative to a specific object" in this same "metric" way, but without tallying any votes. Then it relays this SDR subcortically, voting 0 or 1 times for each cell. @param sensorToBodyInputs (list of numpy arrays) The "sensor's location relative to the body" input from each cortical column @param sensorToSpecificObjectInputs (list of numpy arrays) The "sensor's location relative to specific object" input from each cortical column """ votesByCell = np.zeros(self.cellCount, dtype="int") self.activeSegmentsByColumn = [] for (connections, activeSensorToBodyCells, activeSensorToSpecificObjectCells) in zip(self.connectionsByColumn, sensorToBodyByColumn, sensorToSpecificObjectByColumn): overlaps = connections.computeActivity({ "sensorToBody": activeSensorToBodyCells, "sensorToSpecificObject": activeSensorToSpecificObjectCells, }) activeSegments = np.where(overlaps >= 2)[0] votes = connections.mapSegmentsToCells(activeSegments) votes = np.unique(votes) # Only allow a column to vote for a cell once. votesByCell[votes] += 1 self.activeSegmentsByColumn.append(activeSegments) candidates = np.where(votesByCell == np.max(votesByCell))[0] # If possible, select only from current active cells. # # If we were to always activate all candidates, there would be an explosive # back-and-forth between this layer and the sensorToSpecificObject layer. self.activeCells = np.intersect1d(self.activeCells, candidates) if self.activeCells.size == 0: # Otherwise, activate all cells with the maximum number of active # segments. self.activeCells = candidates self.inhibitedCells = np.setdiff1d(np.where(votesByCell > 0)[0], self.activeCells)
python
def compute(self, sensorToBodyByColumn, sensorToSpecificObjectByColumn): """ Compute the "body's location relative to a specific object" from an array of "sensor's location relative to a specific object" and an array of "sensor's location relative to body" These arrays consist of one module per cortical column. This is a metric computation, similar to that of the SensorToSpecificObjectModule, but with voting. In effect, the columns vote on "the body's location relative to a specific object". Note: Each column can vote for an arbitrary number of cells, but it can't vote for a single cell more than once. This is necessary because we don't want ambiguity in a column to cause some cells to get extra votes. There are a few ways that this could be biologically plausible: - Explanation 1: Nearby dendritic segments are independent coincidence detectors, but perhaps their dendritic spikes don't sum. Meanwhile, maybe dendritic spikes from far away dendritic segments do sum. - Explanation 2: Dendritic spikes from different columns are separated temporally, not spatially. All the spikes from one column "arrive" at the cell at the same time, but the dendritic spikes from other columns arrive at other times. With each of these temporally-separated dendritic spikes, the unsupported cells are inhibited, or the spikes' effects are summed. - Explanation 3: Another population of cells within the cortical column might calculate the "body's location relative to a specific object" in this same "metric" way, but without tallying any votes. Then it relays this SDR subcortically, voting 0 or 1 times for each cell. @param sensorToBodyInputs (list of numpy arrays) The "sensor's location relative to the body" input from each cortical column @param sensorToSpecificObjectInputs (list of numpy arrays) The "sensor's location relative to specific object" input from each cortical column """ votesByCell = np.zeros(self.cellCount, dtype="int") self.activeSegmentsByColumn = [] for (connections, activeSensorToBodyCells, activeSensorToSpecificObjectCells) in zip(self.connectionsByColumn, sensorToBodyByColumn, sensorToSpecificObjectByColumn): overlaps = connections.computeActivity({ "sensorToBody": activeSensorToBodyCells, "sensorToSpecificObject": activeSensorToSpecificObjectCells, }) activeSegments = np.where(overlaps >= 2)[0] votes = connections.mapSegmentsToCells(activeSegments) votes = np.unique(votes) # Only allow a column to vote for a cell once. votesByCell[votes] += 1 self.activeSegmentsByColumn.append(activeSegments) candidates = np.where(votesByCell == np.max(votesByCell))[0] # If possible, select only from current active cells. # # If we were to always activate all candidates, there would be an explosive # back-and-forth between this layer and the sensorToSpecificObject layer. self.activeCells = np.intersect1d(self.activeCells, candidates) if self.activeCells.size == 0: # Otherwise, activate all cells with the maximum number of active # segments. self.activeCells = candidates self.inhibitedCells = np.setdiff1d(np.where(votesByCell > 0)[0], self.activeCells)
[ "def", "compute", "(", "self", ",", "sensorToBodyByColumn", ",", "sensorToSpecificObjectByColumn", ")", ":", "votesByCell", "=", "np", ".", "zeros", "(", "self", ".", "cellCount", ",", "dtype", "=", "\"int\"", ")", "self", ".", "activeSegmentsByColumn", "=", "...
Compute the "body's location relative to a specific object" from an array of "sensor's location relative to a specific object" and an array of "sensor's location relative to body" These arrays consist of one module per cortical column. This is a metric computation, similar to that of the SensorToSpecificObjectModule, but with voting. In effect, the columns vote on "the body's location relative to a specific object". Note: Each column can vote for an arbitrary number of cells, but it can't vote for a single cell more than once. This is necessary because we don't want ambiguity in a column to cause some cells to get extra votes. There are a few ways that this could be biologically plausible: - Explanation 1: Nearby dendritic segments are independent coincidence detectors, but perhaps their dendritic spikes don't sum. Meanwhile, maybe dendritic spikes from far away dendritic segments do sum. - Explanation 2: Dendritic spikes from different columns are separated temporally, not spatially. All the spikes from one column "arrive" at the cell at the same time, but the dendritic spikes from other columns arrive at other times. With each of these temporally-separated dendritic spikes, the unsupported cells are inhibited, or the spikes' effects are summed. - Explanation 3: Another population of cells within the cortical column might calculate the "body's location relative to a specific object" in this same "metric" way, but without tallying any votes. Then it relays this SDR subcortically, voting 0 or 1 times for each cell. @param sensorToBodyInputs (list of numpy arrays) The "sensor's location relative to the body" input from each cortical column @param sensorToSpecificObjectInputs (list of numpy arrays) The "sensor's location relative to specific object" input from each cortical column
[ "Compute", "the", "body", "s", "location", "relative", "to", "a", "specific", "object", "from", "an", "array", "of", "sensor", "s", "location", "relative", "to", "a", "specific", "object", "and", "an", "array", "of", "sensor", "s", "location", "relative", ...
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/location_modules.py#L985-L1060
train
198,831
numenta/htmresearch
htmresearch/algorithms/location_modules.py
SensorToSpecificObjectModule.metricCompute
def metricCompute(self, sensorToBody, bodyToSpecificObject): """ Compute the "sensor's location relative to a specific object" from the "body's location relative to a specific object" and the "sensor's location relative to body" @param sensorToBody (numpy array) Active cells of a single module that represents the sensor's location relative to the body @param bodyToSpecificObject (numpy array) Active cells of a single module that represents the body's location relative to a specific object """ overlaps = self.metricConnections.computeActivity({ "bodyToSpecificObject": bodyToSpecificObject, "sensorToBody": sensorToBody, }) self.activeMetricSegments = np.where(overlaps >= 2)[0] self.activeCells = np.unique( self.metricConnections.mapSegmentsToCells( self.activeMetricSegments))
python
def metricCompute(self, sensorToBody, bodyToSpecificObject): """ Compute the "sensor's location relative to a specific object" from the "body's location relative to a specific object" and the "sensor's location relative to body" @param sensorToBody (numpy array) Active cells of a single module that represents the sensor's location relative to the body @param bodyToSpecificObject (numpy array) Active cells of a single module that represents the body's location relative to a specific object """ overlaps = self.metricConnections.computeActivity({ "bodyToSpecificObject": bodyToSpecificObject, "sensorToBody": sensorToBody, }) self.activeMetricSegments = np.where(overlaps >= 2)[0] self.activeCells = np.unique( self.metricConnections.mapSegmentsToCells( self.activeMetricSegments))
[ "def", "metricCompute", "(", "self", ",", "sensorToBody", ",", "bodyToSpecificObject", ")", ":", "overlaps", "=", "self", ".", "metricConnections", ".", "computeActivity", "(", "{", "\"bodyToSpecificObject\"", ":", "bodyToSpecificObject", ",", "\"sensorToBody\"", ":",...
Compute the "sensor's location relative to a specific object" from the "body's location relative to a specific object" and the "sensor's location relative to body" @param sensorToBody (numpy array) Active cells of a single module that represents the sensor's location relative to the body @param bodyToSpecificObject (numpy array) Active cells of a single module that represents the body's location relative to a specific object
[ "Compute", "the", "sensor", "s", "location", "relative", "to", "a", "specific", "object", "from", "the", "body", "s", "location", "relative", "to", "a", "specific", "object", "and", "the", "sensor", "s", "location", "relative", "to", "body" ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/location_modules.py#L1138-L1163
train
198,832
numenta/htmresearch
htmresearch/algorithms/location_modules.py
SensorToSpecificObjectModule.anchorCompute
def anchorCompute(self, anchorInput, learn): """ Compute the "sensor's location relative to a specific object" from the feature-location pair. @param anchorInput (numpy array) Active cells in the feature-location pair layer @param learn (bool) If true, maintain current cell activity and learn this input on the currently active cells """ if learn: self._anchorComputeLearningMode(anchorInput) else: overlaps = self.anchorConnections.computeActivity( anchorInput, self.connectedPermanence) self.activeSegments = np.where(overlaps >= self.activationThreshold)[0] self.activeCells = np.unique( self.anchorConnections.mapSegmentsToCells(self.activeSegments))
python
def anchorCompute(self, anchorInput, learn): """ Compute the "sensor's location relative to a specific object" from the feature-location pair. @param anchorInput (numpy array) Active cells in the feature-location pair layer @param learn (bool) If true, maintain current cell activity and learn this input on the currently active cells """ if learn: self._anchorComputeLearningMode(anchorInput) else: overlaps = self.anchorConnections.computeActivity( anchorInput, self.connectedPermanence) self.activeSegments = np.where(overlaps >= self.activationThreshold)[0] self.activeCells = np.unique( self.anchorConnections.mapSegmentsToCells(self.activeSegments))
[ "def", "anchorCompute", "(", "self", ",", "anchorInput", ",", "learn", ")", ":", "if", "learn", ":", "self", ".", "_anchorComputeLearningMode", "(", "anchorInput", ")", "else", ":", "overlaps", "=", "self", ".", "anchorConnections", ".", "computeActivity", "("...
Compute the "sensor's location relative to a specific object" from the feature-location pair. @param anchorInput (numpy array) Active cells in the feature-location pair layer @param learn (bool) If true, maintain current cell activity and learn this input on the currently active cells
[ "Compute", "the", "sensor", "s", "location", "relative", "to", "a", "specific", "object", "from", "the", "feature", "-", "location", "pair", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/location_modules.py#L1166-L1187
train
198,833
numenta/htmresearch
htmresearch/algorithms/location_modules.py
SensorToBodyModule2D.compute
def compute(self, egocentricLocation): """ Compute the new active cells from the given "sensor location relative to body" vector. @param egocentricLocation (pair of floats) [di, dj] offset of the sensor from the body. """ offsetInCellFields = (np.matmul(self.rotationMatrix, egocentricLocation) * self.cellFieldsPerUnitDistance) np.mod(offsetInCellFields, self.cellDimensions, out=offsetInCellFields) self.activeCells = np.unique( np.ravel_multi_index(np.floor(offsetInCellFields).T.astype('int'), self.cellDimensions))
python
def compute(self, egocentricLocation): """ Compute the new active cells from the given "sensor location relative to body" vector. @param egocentricLocation (pair of floats) [di, dj] offset of the sensor from the body. """ offsetInCellFields = (np.matmul(self.rotationMatrix, egocentricLocation) * self.cellFieldsPerUnitDistance) np.mod(offsetInCellFields, self.cellDimensions, out=offsetInCellFields) self.activeCells = np.unique( np.ravel_multi_index(np.floor(offsetInCellFields).T.astype('int'), self.cellDimensions))
[ "def", "compute", "(", "self", ",", "egocentricLocation", ")", ":", "offsetInCellFields", "=", "(", "np", ".", "matmul", "(", "self", ".", "rotationMatrix", ",", "egocentricLocation", ")", "*", "self", ".", "cellFieldsPerUnitDistance", ")", "np", ".", "mod", ...
Compute the new active cells from the given "sensor location relative to body" vector. @param egocentricLocation (pair of floats) [di, dj] offset of the sensor from the body.
[ "Compute", "the", "new", "active", "cells", "from", "the", "given", "sensor", "location", "relative", "to", "body", "vector", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/location_modules.py#L1331-L1345
train
198,834
numenta/htmresearch
setup.py
htmresearchCorePrereleaseInstalled
def htmresearchCorePrereleaseInstalled(): """ Make an attempt to determine if a pre-release version of htmresearch-core is installed already. @return: boolean """ try: coreDistribution = pkg_resources.get_distribution("htmresearch-core") if pkg_resources.parse_version(coreDistribution.version).is_prerelease: # A pre-release dev version of htmresearch-core is installed. return True except pkg_resources.DistributionNotFound: pass # Silently ignore. The absence of htmresearch-core will be handled by # setuptools by default return False
python
def htmresearchCorePrereleaseInstalled(): """ Make an attempt to determine if a pre-release version of htmresearch-core is installed already. @return: boolean """ try: coreDistribution = pkg_resources.get_distribution("htmresearch-core") if pkg_resources.parse_version(coreDistribution.version).is_prerelease: # A pre-release dev version of htmresearch-core is installed. return True except pkg_resources.DistributionNotFound: pass # Silently ignore. The absence of htmresearch-core will be handled by # setuptools by default return False
[ "def", "htmresearchCorePrereleaseInstalled", "(", ")", ":", "try", ":", "coreDistribution", "=", "pkg_resources", ".", "get_distribution", "(", "\"htmresearch-core\"", ")", "if", "pkg_resources", ".", "parse_version", "(", "coreDistribution", ".", "version", ")", ".",...
Make an attempt to determine if a pre-release version of htmresearch-core is installed already. @return: boolean
[ "Make", "an", "attempt", "to", "determine", "if", "a", "pre", "-", "release", "version", "of", "htmresearch", "-", "core", "is", "installed", "already", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/setup.py#L56-L72
train
198,835
numenta/htmresearch
htmresearch/frameworks/layers/l2456_model.py
L2456Model.infer
def infer(self, sensationList, reset=True, objectName=None): """ Infer on a given set of sensations for a single object. The provided sensationList is a list of sensations, and each sensation is a mapping from cortical column to a tuple of three SDR's respectively corresponding to the locationInput, the coarseSensorInput, and the sensorInput. For example, the input can look as follows, if we are inferring a simple object with two sensations (with very few active bits for simplicity): sensationList = [ { # location, coarse feature, fine feature for CC0, sensation 1 0: ( [1, 5, 10], [9, 32, 75], [6, 12, 52] ), # location, coarse feature, fine feature for CC1, sensation 1 1: ( [6, 2, 15], [11, 42, 92], [7, 11, 50] ), }, { # location, coarse feature, fine feature for CC0, sensation 2 0: ( [2, 9, 10], [10, 35, 78], [6, 12, 52] ), # location, coarse feature, fine feature for CC1, sensation 2 1: ( [1, 4, 12], [10, 32, 52], [6, 10, 52] ), }, ] If the object is known by the caller, an object name can be specified as an optional argument, and must match the objects given while learning. This is used later when evaluating inference statistics. Parameters: ---------------------------- @param objects (dict) Objects to learn, in the canonical format specified above @param reset (bool) If set to True (which is the default value), the network will be reset after learning. @param objectName (str) Name of the objects (must match the names given during learning). """ self._unsetLearningMode() statistics = collections.defaultdict(list) if objectName is not None: if objectName not in self.objectRepresentationsL2: raise ValueError("The provided objectName was not given during" " learning") for sensations in sensationList: # feed all columns with sensations for col in xrange(self.numColumns): location, coarseFeature, fineFeature = sensations[col] self.locationInputs[col].addDataToQueue(list(location), 0, 0) self.coarseSensors[col].addDataToQueue(list(coarseFeature), 0, 0) self.sensors[col].addDataToQueue(list(fineFeature), 0, 0) self.network.run(1) self._updateInferenceStats(statistics, objectName) if reset: # send reset signal self._sendReset() # save statistics statistics["numSteps"] = len(sensationList) statistics["object"] = objectName if objectName is not None else "Unknown" self.statistics.append(statistics)
python
def infer(self, sensationList, reset=True, objectName=None): """ Infer on a given set of sensations for a single object. The provided sensationList is a list of sensations, and each sensation is a mapping from cortical column to a tuple of three SDR's respectively corresponding to the locationInput, the coarseSensorInput, and the sensorInput. For example, the input can look as follows, if we are inferring a simple object with two sensations (with very few active bits for simplicity): sensationList = [ { # location, coarse feature, fine feature for CC0, sensation 1 0: ( [1, 5, 10], [9, 32, 75], [6, 12, 52] ), # location, coarse feature, fine feature for CC1, sensation 1 1: ( [6, 2, 15], [11, 42, 92], [7, 11, 50] ), }, { # location, coarse feature, fine feature for CC0, sensation 2 0: ( [2, 9, 10], [10, 35, 78], [6, 12, 52] ), # location, coarse feature, fine feature for CC1, sensation 2 1: ( [1, 4, 12], [10, 32, 52], [6, 10, 52] ), }, ] If the object is known by the caller, an object name can be specified as an optional argument, and must match the objects given while learning. This is used later when evaluating inference statistics. Parameters: ---------------------------- @param objects (dict) Objects to learn, in the canonical format specified above @param reset (bool) If set to True (which is the default value), the network will be reset after learning. @param objectName (str) Name of the objects (must match the names given during learning). """ self._unsetLearningMode() statistics = collections.defaultdict(list) if objectName is not None: if objectName not in self.objectRepresentationsL2: raise ValueError("The provided objectName was not given during" " learning") for sensations in sensationList: # feed all columns with sensations for col in xrange(self.numColumns): location, coarseFeature, fineFeature = sensations[col] self.locationInputs[col].addDataToQueue(list(location), 0, 0) self.coarseSensors[col].addDataToQueue(list(coarseFeature), 0, 0) self.sensors[col].addDataToQueue(list(fineFeature), 0, 0) self.network.run(1) self._updateInferenceStats(statistics, objectName) if reset: # send reset signal self._sendReset() # save statistics statistics["numSteps"] = len(sensationList) statistics["object"] = objectName if objectName is not None else "Unknown" self.statistics.append(statistics)
[ "def", "infer", "(", "self", ",", "sensationList", ",", "reset", "=", "True", ",", "objectName", "=", "None", ")", ":", "self", ".", "_unsetLearningMode", "(", ")", "statistics", "=", "collections", ".", "defaultdict", "(", "list", ")", "if", "objectName",...
Infer on a given set of sensations for a single object. The provided sensationList is a list of sensations, and each sensation is a mapping from cortical column to a tuple of three SDR's respectively corresponding to the locationInput, the coarseSensorInput, and the sensorInput. For example, the input can look as follows, if we are inferring a simple object with two sensations (with very few active bits for simplicity): sensationList = [ { # location, coarse feature, fine feature for CC0, sensation 1 0: ( [1, 5, 10], [9, 32, 75], [6, 12, 52] ), # location, coarse feature, fine feature for CC1, sensation 1 1: ( [6, 2, 15], [11, 42, 92], [7, 11, 50] ), }, { # location, coarse feature, fine feature for CC0, sensation 2 0: ( [2, 9, 10], [10, 35, 78], [6, 12, 52] ), # location, coarse feature, fine feature for CC1, sensation 2 1: ( [1, 4, 12], [10, 32, 52], [6, 10, 52] ), }, ] If the object is known by the caller, an object name can be specified as an optional argument, and must match the objects given while learning. This is used later when evaluating inference statistics. Parameters: ---------------------------- @param objects (dict) Objects to learn, in the canonical format specified above @param reset (bool) If set to True (which is the default value), the network will be reset after learning. @param objectName (str) Name of the objects (must match the names given during learning).
[ "Infer", "on", "a", "given", "set", "of", "sensations", "for", "a", "single", "object", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/l2456_model.py#L269-L339
train
198,836
numenta/htmresearch
htmresearch/frameworks/layers/l2456_model.py
L2456Model.getDefaultParams
def getDefaultParams(self): """ Returns a good default set of parameters to use in L2456 regions """ return { "sensorParams": { "outputWidth": self.sensorInputSize, }, "coarseSensorParams": { "outputWidth": self.sensorInputSize, }, "locationParams": { "activeBits": 41, "outputWidth": self.sensorInputSize, "radius": 2, "verbosity": 0, }, "L4Params": { "columnCount": self.sensorInputSize, "cellsPerColumn": 8, "learn": True, "learnOnOneCell": False, "initialPermanence": 0.51, "connectedPermanence": 0.6, "permanenceIncrement": 0.1, "permanenceDecrement": 0.02, "minThreshold": 10, "basalPredictedSegmentDecrement": 0.002, "activationThreshold": 13, "sampleSize": 20, "implementation": "ApicalTiebreakCPP", }, "L2Params": { "inputWidth": self.sensorInputSize * 8, "cellCount": 4096, "sdrSize": 40, "synPermProximalInc": 0.1, "synPermProximalDec": 0.001, "initialProximalPermanence": 0.6, "minThresholdProximal": 10, "sampleSizeProximal": 20, "connectedPermanenceProximal": 0.5, "synPermDistalInc": 0.1, "synPermDistalDec": 0.001, "initialDistalPermanence": 0.41, "activationThresholdDistal": 13, "sampleSizeDistal": 20, "connectedPermanenceDistal": 0.5, "learningMode": True, }, "L6Params": { "columnCount": self.sensorInputSize, "cellsPerColumn": 8, "learn": True, "learnOnOneCell": False, "initialPermanence": 0.51, "connectedPermanence": 0.6, "permanenceIncrement": 0.1, "permanenceDecrement": 0.02, "minThreshold": 10, "basalPredictedSegmentDecrement": 0.004, "activationThreshold": 13, "sampleSize": 20, }, "L5Params": { "inputWidth": self.sensorInputSize * 8, "cellCount": 4096, "sdrSize": 40, "synPermProximalInc": 0.1, "synPermProximalDec": 0.001, "initialProximalPermanence": 0.6, "minThresholdProximal": 10, "sampleSizeProximal": 20, "connectedPermanenceProximal": 0.5, "synPermDistalInc": 0.1, "synPermDistalDec": 0.001, "initialDistalPermanence": 0.41, "activationThresholdDistal": 13, "sampleSizeDistal": 20, "connectedPermanenceDistal": 0.5, "learningMode": True, }, }
python
def getDefaultParams(self): """ Returns a good default set of parameters to use in L2456 regions """ return { "sensorParams": { "outputWidth": self.sensorInputSize, }, "coarseSensorParams": { "outputWidth": self.sensorInputSize, }, "locationParams": { "activeBits": 41, "outputWidth": self.sensorInputSize, "radius": 2, "verbosity": 0, }, "L4Params": { "columnCount": self.sensorInputSize, "cellsPerColumn": 8, "learn": True, "learnOnOneCell": False, "initialPermanence": 0.51, "connectedPermanence": 0.6, "permanenceIncrement": 0.1, "permanenceDecrement": 0.02, "minThreshold": 10, "basalPredictedSegmentDecrement": 0.002, "activationThreshold": 13, "sampleSize": 20, "implementation": "ApicalTiebreakCPP", }, "L2Params": { "inputWidth": self.sensorInputSize * 8, "cellCount": 4096, "sdrSize": 40, "synPermProximalInc": 0.1, "synPermProximalDec": 0.001, "initialProximalPermanence": 0.6, "minThresholdProximal": 10, "sampleSizeProximal": 20, "connectedPermanenceProximal": 0.5, "synPermDistalInc": 0.1, "synPermDistalDec": 0.001, "initialDistalPermanence": 0.41, "activationThresholdDistal": 13, "sampleSizeDistal": 20, "connectedPermanenceDistal": 0.5, "learningMode": True, }, "L6Params": { "columnCount": self.sensorInputSize, "cellsPerColumn": 8, "learn": True, "learnOnOneCell": False, "initialPermanence": 0.51, "connectedPermanence": 0.6, "permanenceIncrement": 0.1, "permanenceDecrement": 0.02, "minThreshold": 10, "basalPredictedSegmentDecrement": 0.004, "activationThreshold": 13, "sampleSize": 20, }, "L5Params": { "inputWidth": self.sensorInputSize * 8, "cellCount": 4096, "sdrSize": 40, "synPermProximalInc": 0.1, "synPermProximalDec": 0.001, "initialProximalPermanence": 0.6, "minThresholdProximal": 10, "sampleSizeProximal": 20, "connectedPermanenceProximal": 0.5, "synPermDistalInc": 0.1, "synPermDistalDec": 0.001, "initialDistalPermanence": 0.41, "activationThresholdDistal": 13, "sampleSizeDistal": 20, "connectedPermanenceDistal": 0.5, "learningMode": True, }, }
[ "def", "getDefaultParams", "(", "self", ")", ":", "return", "{", "\"sensorParams\"", ":", "{", "\"outputWidth\"", ":", "self", ".", "sensorInputSize", ",", "}", ",", "\"coarseSensorParams\"", ":", "{", "\"outputWidth\"", ":", "self", ".", "sensorInputSize", ",",...
Returns a good default set of parameters to use in L2456 regions
[ "Returns", "a", "good", "default", "set", "of", "parameters", "to", "use", "in", "L2456", "regions" ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/l2456_model.py#L518-L607
train
198,837
numenta/htmresearch
htmresearch/frameworks/layers/l2456_model.py
L2456Model._retrieveRegions
def _retrieveRegions(self): """ Retrieve and store Python region instances for each column """ self.sensors = [] self.coarseSensors = [] self.locationInputs = [] self.L4Columns = [] self.L2Columns = [] self.L5Columns = [] self.L6Columns = [] for i in xrange(self.numColumns): self.sensors.append( self.network.regions["sensorInput_" + str(i)].getSelf() ) self.coarseSensors.append( self.network.regions["coarseSensorInput_" + str(i)].getSelf() ) self.locationInputs.append( self.network.regions["locationInput_" + str(i)].getSelf() ) self.L4Columns.append( self.network.regions["L4Column_" + str(i)].getSelf() ) self.L2Columns.append( self.network.regions["L2Column_" + str(i)].getSelf() ) self.L5Columns.append( self.network.regions["L5Column_" + str(i)].getSelf() ) self.L6Columns.append( self.network.regions["L6Column_" + str(i)].getSelf() )
python
def _retrieveRegions(self): """ Retrieve and store Python region instances for each column """ self.sensors = [] self.coarseSensors = [] self.locationInputs = [] self.L4Columns = [] self.L2Columns = [] self.L5Columns = [] self.L6Columns = [] for i in xrange(self.numColumns): self.sensors.append( self.network.regions["sensorInput_" + str(i)].getSelf() ) self.coarseSensors.append( self.network.regions["coarseSensorInput_" + str(i)].getSelf() ) self.locationInputs.append( self.network.regions["locationInput_" + str(i)].getSelf() ) self.L4Columns.append( self.network.regions["L4Column_" + str(i)].getSelf() ) self.L2Columns.append( self.network.regions["L2Column_" + str(i)].getSelf() ) self.L5Columns.append( self.network.regions["L5Column_" + str(i)].getSelf() ) self.L6Columns.append( self.network.regions["L6Column_" + str(i)].getSelf() )
[ "def", "_retrieveRegions", "(", "self", ")", ":", "self", ".", "sensors", "=", "[", "]", "self", ".", "coarseSensors", "=", "[", "]", "self", ".", "locationInputs", "=", "[", "]", "self", ".", "L4Columns", "=", "[", "]", "self", ".", "L2Columns", "="...
Retrieve and store Python region instances for each column
[ "Retrieve", "and", "store", "Python", "region", "instances", "for", "each", "column" ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/l2456_model.py#L610-L643
train
198,838
numenta/htmresearch
projects/l2_pooling/noise_tolerance_l2.py
plotSuccessRate_varyNumColumns
def plotSuccessRate_varyNumColumns(noiseSigma, noiseEverywhere): """ Run and plot the experiment, varying the number of cortical columns. """ # # Run the experiment # noiseLevels = [x * 0.01 for x in xrange(0, 101, 5)] l2Overrides = {"sampleSizeDistal": 20} columnCounts = [1, 2, 3, 4] results = defaultdict(list) for trial in xrange(1): print "trial", trial objectDescriptions = createRandomObjectDescriptions(10, 10) for numColumns in columnCounts: print "numColumns", numColumns for noiseLevel in noiseLevels: r = doExperiment(numColumns, l2Overrides, objectDescriptions, noiseLevel, noiseSigma, numInitialTraversals=6, noiseEverywhere=noiseEverywhere) results[(numColumns, noiseLevel)].extend(r) # # Plot it # numCorrectActiveThreshold = 30 numIncorrectActiveThreshold = 10 plt.figure() colors = dict(zip(columnCounts, ('r', 'k', 'g', 'b'))) markers = dict(zip(columnCounts, ('o', '*', 'D', 'x'))) for numColumns in columnCounts: y = [] for noiseLevel in noiseLevels: trials = results[(numColumns, noiseLevel)] numPassed = len([True for numCorrect, numIncorrect in trials if numCorrect >= numCorrectActiveThreshold and numIncorrect <= numIncorrectActiveThreshold]) y.append(numPassed / float(len(trials))) plt.plot(noiseLevels, y, color=colors[numColumns], marker=markers[numColumns]) lgnd = plt.legend(["%d columns" % numColumns for numColumns in columnCounts], bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.0) plt.xlabel("Mean feedforward noise level") plt.xticks([0.01 * n for n in xrange(0, 101, 10)]) plt.ylabel("Success rate") plt.yticks([0.0, 0.2, 0.4, 0.6, 0.8, 1.0]) plt.title("Inference with normally distributed noise (stdev=%.2f)" % noiseSigma) plotPath = os.path.join("plots", "successRate_varyColumnCount_sigma%.2f_%s.pdf" % (noiseSigma, time.strftime("%Y%m%d-%H%M%S"))) plt.savefig(plotPath, bbox_extra_artists=(lgnd,), bbox_inches="tight") print "Saved file %s" % plotPath
python
def plotSuccessRate_varyNumColumns(noiseSigma, noiseEverywhere): """ Run and plot the experiment, varying the number of cortical columns. """ # # Run the experiment # noiseLevels = [x * 0.01 for x in xrange(0, 101, 5)] l2Overrides = {"sampleSizeDistal": 20} columnCounts = [1, 2, 3, 4] results = defaultdict(list) for trial in xrange(1): print "trial", trial objectDescriptions = createRandomObjectDescriptions(10, 10) for numColumns in columnCounts: print "numColumns", numColumns for noiseLevel in noiseLevels: r = doExperiment(numColumns, l2Overrides, objectDescriptions, noiseLevel, noiseSigma, numInitialTraversals=6, noiseEverywhere=noiseEverywhere) results[(numColumns, noiseLevel)].extend(r) # # Plot it # numCorrectActiveThreshold = 30 numIncorrectActiveThreshold = 10 plt.figure() colors = dict(zip(columnCounts, ('r', 'k', 'g', 'b'))) markers = dict(zip(columnCounts, ('o', '*', 'D', 'x'))) for numColumns in columnCounts: y = [] for noiseLevel in noiseLevels: trials = results[(numColumns, noiseLevel)] numPassed = len([True for numCorrect, numIncorrect in trials if numCorrect >= numCorrectActiveThreshold and numIncorrect <= numIncorrectActiveThreshold]) y.append(numPassed / float(len(trials))) plt.plot(noiseLevels, y, color=colors[numColumns], marker=markers[numColumns]) lgnd = plt.legend(["%d columns" % numColumns for numColumns in columnCounts], bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.0) plt.xlabel("Mean feedforward noise level") plt.xticks([0.01 * n for n in xrange(0, 101, 10)]) plt.ylabel("Success rate") plt.yticks([0.0, 0.2, 0.4, 0.6, 0.8, 1.0]) plt.title("Inference with normally distributed noise (stdev=%.2f)" % noiseSigma) plotPath = os.path.join("plots", "successRate_varyColumnCount_sigma%.2f_%s.pdf" % (noiseSigma, time.strftime("%Y%m%d-%H%M%S"))) plt.savefig(plotPath, bbox_extra_artists=(lgnd,), bbox_inches="tight") print "Saved file %s" % plotPath
[ "def", "plotSuccessRate_varyNumColumns", "(", "noiseSigma", ",", "noiseEverywhere", ")", ":", "#", "# Run the experiment", "#", "noiseLevels", "=", "[", "x", "*", "0.01", "for", "x", "in", "xrange", "(", "0", ",", "101", ",", "5", ")", "]", "l2Overrides", ...
Run and plot the experiment, varying the number of cortical columns.
[ "Run", "and", "plot", "the", "experiment", "varying", "the", "number", "of", "cortical", "columns", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/l2_pooling/noise_tolerance_l2.py#L222-L286
train
198,839
numenta/htmresearch
htmresearch/frameworks/layers/object_machine_base.py
ObjectMachineBase.randomTraversal
def randomTraversal(sensations, numTraversals): """ Given a list of sensations, return the SDRs that would be obtained by numTraversals random traversals of that set of sensations. Each sensation is a dict mapping cortical column index to a pair of SDR's (one location and one feature). """ newSensations = [] for _ in range(numTraversals): s = copy.deepcopy(sensations) random.shuffle(s) newSensations += s return newSensations
python
def randomTraversal(sensations, numTraversals): """ Given a list of sensations, return the SDRs that would be obtained by numTraversals random traversals of that set of sensations. Each sensation is a dict mapping cortical column index to a pair of SDR's (one location and one feature). """ newSensations = [] for _ in range(numTraversals): s = copy.deepcopy(sensations) random.shuffle(s) newSensations += s return newSensations
[ "def", "randomTraversal", "(", "sensations", ",", "numTraversals", ")", ":", "newSensations", "=", "[", "]", "for", "_", "in", "range", "(", "numTraversals", ")", ":", "s", "=", "copy", ".", "deepcopy", "(", "sensations", ")", "random", ".", "shuffle", "...
Given a list of sensations, return the SDRs that would be obtained by numTraversals random traversals of that set of sensations. Each sensation is a dict mapping cortical column index to a pair of SDR's (one location and one feature).
[ "Given", "a", "list", "of", "sensations", "return", "the", "SDRs", "that", "would", "be", "obtained", "by", "numTraversals", "random", "traversals", "of", "that", "set", "of", "sensations", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/object_machine_base.py#L132-L145
train
198,840
numenta/htmresearch
projects/nik/nik_analysis.py
NIKAnalysis.compute
def compute(self, xt1, yt1, xt, yt, theta1t1, theta2t1, theta1, theta2): """ Accumulate the various inputs. """ dx = xt - xt1 dy = yt - yt1 if self.numPoints < self.maxPoints: self.dxValues[self.numPoints,0] = dx self.dxValues[self.numPoints,1] = dy self.thetaValues[self.numPoints,0] = theta1 self.thetaValues[self.numPoints,1] = theta2 self.numPoints += 1 # print >>sys.stderr, "Xt's: ", xt1, yt1, xt, yt, "Delta's: ", dx, dy # print >>sys.stderr, "Theta t-1: ", theta1t1, theta2t1, "t:",theta1, theta2 elif self.numPoints == self.maxPoints: print >> sys.stderr,"Max points exceeded, analyzing ",self.maxPoints,"points only" self.numPoints += 1
python
def compute(self, xt1, yt1, xt, yt, theta1t1, theta2t1, theta1, theta2): """ Accumulate the various inputs. """ dx = xt - xt1 dy = yt - yt1 if self.numPoints < self.maxPoints: self.dxValues[self.numPoints,0] = dx self.dxValues[self.numPoints,1] = dy self.thetaValues[self.numPoints,0] = theta1 self.thetaValues[self.numPoints,1] = theta2 self.numPoints += 1 # print >>sys.stderr, "Xt's: ", xt1, yt1, xt, yt, "Delta's: ", dx, dy # print >>sys.stderr, "Theta t-1: ", theta1t1, theta2t1, "t:",theta1, theta2 elif self.numPoints == self.maxPoints: print >> sys.stderr,"Max points exceeded, analyzing ",self.maxPoints,"points only" self.numPoints += 1
[ "def", "compute", "(", "self", ",", "xt1", ",", "yt1", ",", "xt", ",", "yt", ",", "theta1t1", ",", "theta2t1", ",", "theta1", ",", "theta2", ")", ":", "dx", "=", "xt", "-", "xt1", "dy", "=", "yt", "-", "yt1", "if", "self", ".", "numPoints", "<"...
Accumulate the various inputs.
[ "Accumulate", "the", "various", "inputs", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/nik/nik_analysis.py#L41-L62
train
198,841
numenta/htmresearch
projects/relational_memory/relational_memory_experiment.py
bind
def bind(cell1, cell2, moduleDimensions): """Return transform index for given cells. Convert to coordinate space, calculate transform, and convert back to an index. In coordinate space, the transform represents `C2 - C1`. """ cell1Coords = np.unravel_index(cell1, moduleDimensions) cell2Coords = np.unravel_index(cell2, moduleDimensions) transformCoords = [(c2 - c1) % m for c1, c2, m in itertools.izip(cell1Coords, cell2Coords, moduleDimensions)] return np.ravel_multi_index(transformCoords, moduleDimensions)
python
def bind(cell1, cell2, moduleDimensions): """Return transform index for given cells. Convert to coordinate space, calculate transform, and convert back to an index. In coordinate space, the transform represents `C2 - C1`. """ cell1Coords = np.unravel_index(cell1, moduleDimensions) cell2Coords = np.unravel_index(cell2, moduleDimensions) transformCoords = [(c2 - c1) % m for c1, c2, m in itertools.izip(cell1Coords, cell2Coords, moduleDimensions)] return np.ravel_multi_index(transformCoords, moduleDimensions)
[ "def", "bind", "(", "cell1", ",", "cell2", ",", "moduleDimensions", ")", ":", "cell1Coords", "=", "np", ".", "unravel_index", "(", "cell1", ",", "moduleDimensions", ")", "cell2Coords", "=", "np", ".", "unravel_index", "(", "cell2", ",", "moduleDimensions", "...
Return transform index for given cells. Convert to coordinate space, calculate transform, and convert back to an index. In coordinate space, the transform represents `C2 - C1`.
[ "Return", "transform", "index", "for", "given", "cells", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/relational_memory/relational_memory_experiment.py#L48-L59
train
198,842
numenta/htmresearch
projects/relational_memory/relational_memory_experiment.py
unbind
def unbind(cell1, transform, moduleDimensions): """Return the cell index corresponding to the other half of the transform. Assumes that `transform = bind(cell1, cell2)` and, given `cell1` and `transform`, returns `cell2`. """ cell1Coords = np.unravel_index(cell1, moduleDimensions) transformCoords = np.unravel_index(transform, moduleDimensions) cell2Coords = [(t + c1) % m for c1, t, m in itertools.izip(cell1Coords, transformCoords, moduleDimensions)] return np.ravel_multi_index(cell2Coords, moduleDimensions)
python
def unbind(cell1, transform, moduleDimensions): """Return the cell index corresponding to the other half of the transform. Assumes that `transform = bind(cell1, cell2)` and, given `cell1` and `transform`, returns `cell2`. """ cell1Coords = np.unravel_index(cell1, moduleDimensions) transformCoords = np.unravel_index(transform, moduleDimensions) cell2Coords = [(t + c1) % m for c1, t, m in itertools.izip(cell1Coords, transformCoords, moduleDimensions)] return np.ravel_multi_index(cell2Coords, moduleDimensions)
[ "def", "unbind", "(", "cell1", ",", "transform", ",", "moduleDimensions", ")", ":", "cell1Coords", "=", "np", ".", "unravel_index", "(", "cell1", ",", "moduleDimensions", ")", "transformCoords", "=", "np", ".", "unravel_index", "(", "transform", ",", "moduleDi...
Return the cell index corresponding to the other half of the transform. Assumes that `transform = bind(cell1, cell2)` and, given `cell1` and `transform`, returns `cell2`.
[ "Return", "the", "cell", "index", "corresponding", "to", "the", "other", "half", "of", "the", "transform", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/relational_memory/relational_memory_experiment.py#L62-L73
train
198,843
numenta/htmresearch
htmresearch/frameworks/grid_cell_learning/DynamicCAN.py
Dynamic1DCAN.updatePlaceWeights
def updatePlaceWeights(self): """ We use a simplified version of Hebbian learning to learn place weights. Cells above the boost target are wired to the currently-active places, cells below it have their connection strength to them reduced. """ self.weightsPI += np.outer(self.activationsI - self.boostTarget, self.activationsP)*self.dt*\ self.learnFactorP*self.learningRate self.weightsPEL += np.outer(self.activationsEL - self.boostTarget, self.activationsP)*self.dt*\ self.learnFactorP*self.learningRate self.weightsPER += np.outer(self.activationsER - self.boostTarget, self.activationsP)*self.dt*\ self.learnFactorP*self.learningRate np.minimum(self.weightsPI, 1, self.weightsPI) np.minimum(self.weightsPEL, 1, self.weightsPEL) np.minimum(self.weightsPER, 1, self.weightsPER)
python
def updatePlaceWeights(self): """ We use a simplified version of Hebbian learning to learn place weights. Cells above the boost target are wired to the currently-active places, cells below it have their connection strength to them reduced. """ self.weightsPI += np.outer(self.activationsI - self.boostTarget, self.activationsP)*self.dt*\ self.learnFactorP*self.learningRate self.weightsPEL += np.outer(self.activationsEL - self.boostTarget, self.activationsP)*self.dt*\ self.learnFactorP*self.learningRate self.weightsPER += np.outer(self.activationsER - self.boostTarget, self.activationsP)*self.dt*\ self.learnFactorP*self.learningRate np.minimum(self.weightsPI, 1, self.weightsPI) np.minimum(self.weightsPEL, 1, self.weightsPEL) np.minimum(self.weightsPER, 1, self.weightsPER)
[ "def", "updatePlaceWeights", "(", "self", ")", ":", "self", ".", "weightsPI", "+=", "np", ".", "outer", "(", "self", ".", "activationsI", "-", "self", ".", "boostTarget", ",", "self", ".", "activationsP", ")", "*", "self", ".", "dt", "*", "self", ".", ...
We use a simplified version of Hebbian learning to learn place weights. Cells above the boost target are wired to the currently-active places, cells below it have their connection strength to them reduced.
[ "We", "use", "a", "simplified", "version", "of", "Hebbian", "learning", "to", "learn", "place", "weights", ".", "Cells", "above", "the", "boost", "target", "are", "wired", "to", "the", "currently", "-", "active", "places", "cells", "below", "it", "have", "...
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/grid_cell_learning/DynamicCAN.py#L459-L477
train
198,844
numenta/htmresearch
projects/sdr_paper/pytorch_experiments/union_experiment.py
create_union_mnist_dataset
def create_union_mnist_dataset(): """ Create a UnionDataset composed of two versions of the MNIST datasets where each item in the dataset contains 2 distinct images superimposed """ transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) mnist1 = datasets.MNIST('data', train=False, download=True, transform=transform) data1 = zip(mnist1.test_data, mnist1.test_labels) # Randomize second dataset mnist2 = datasets.MNIST('data', train=False, download=True, transform=transform) data2 = zip(mnist2.test_data, mnist2.test_labels) random.shuffle(data2) # Reorder images of second dataset with same label as first dataset for i in range(len(data2)): if data1[i][1] == data2[i][1]: # Swap indices with same label to a location with diffent label for j in range(len(data1)): if data1[i][1] != data2[j][1] and data2[i][1] != data1[j][1]: swap = data2[j] data2[j] = data2[i] data2[i] = swap break # Update second dataset with new item order mnist2.test_data, mnist2.test_labels = zip(*data2) # Combine the images of both datasets using the maximum value for each pixel return UnionDataset(datasets=[mnist1, mnist2], transform=lambda x, y: torch.max(x, y))
python
def create_union_mnist_dataset(): """ Create a UnionDataset composed of two versions of the MNIST datasets where each item in the dataset contains 2 distinct images superimposed """ transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) mnist1 = datasets.MNIST('data', train=False, download=True, transform=transform) data1 = zip(mnist1.test_data, mnist1.test_labels) # Randomize second dataset mnist2 = datasets.MNIST('data', train=False, download=True, transform=transform) data2 = zip(mnist2.test_data, mnist2.test_labels) random.shuffle(data2) # Reorder images of second dataset with same label as first dataset for i in range(len(data2)): if data1[i][1] == data2[i][1]: # Swap indices with same label to a location with diffent label for j in range(len(data1)): if data1[i][1] != data2[j][1] and data2[i][1] != data1[j][1]: swap = data2[j] data2[j] = data2[i] data2[i] = swap break # Update second dataset with new item order mnist2.test_data, mnist2.test_labels = zip(*data2) # Combine the images of both datasets using the maximum value for each pixel return UnionDataset(datasets=[mnist1, mnist2], transform=lambda x, y: torch.max(x, y))
[ "def", "create_union_mnist_dataset", "(", ")", ":", "transform", "=", "transforms", ".", "Compose", "(", "[", "transforms", ".", "ToTensor", "(", ")", ",", "transforms", ".", "Normalize", "(", "(", "0.1307", ",", ")", ",", "(", "0.3081", ",", ")", ")", ...
Create a UnionDataset composed of two versions of the MNIST datasets where each item in the dataset contains 2 distinct images superimposed
[ "Create", "a", "UnionDataset", "composed", "of", "two", "versions", "of", "the", "MNIST", "datasets", "where", "each", "item", "in", "the", "dataset", "contains", "2", "distinct", "images", "superimposed" ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sdr_paper/pytorch_experiments/union_experiment.py#L44-L76
train
198,845
numenta/htmresearch
projects/l2_pooling/noise_tolerance_l2_l4.py
noisy
def noisy(pattern, noiseLevel, totalNumCells): """ Generate a noisy copy of a pattern. Given number of active bits w = len(pattern), deactivate noiseLevel*w cells, and activate noiseLevel*w other cells. @param pattern (set) A set of active indices @param noiseLevel (float) The percentage of the bits to shuffle @param totalNumCells (int) The number of cells in the SDR, active and inactive @return (set) A noisy set of active indices """ n = int(noiseLevel * len(pattern)) noised = set(pattern) noised.difference_update(random.sample(noised, n)) for _ in xrange(n): while True: v = random.randint(0, totalNumCells - 1) if v not in pattern and v not in noised: noised.add(v) break return noised
python
def noisy(pattern, noiseLevel, totalNumCells): """ Generate a noisy copy of a pattern. Given number of active bits w = len(pattern), deactivate noiseLevel*w cells, and activate noiseLevel*w other cells. @param pattern (set) A set of active indices @param noiseLevel (float) The percentage of the bits to shuffle @param totalNumCells (int) The number of cells in the SDR, active and inactive @return (set) A noisy set of active indices """ n = int(noiseLevel * len(pattern)) noised = set(pattern) noised.difference_update(random.sample(noised, n)) for _ in xrange(n): while True: v = random.randint(0, totalNumCells - 1) if v not in pattern and v not in noised: noised.add(v) break return noised
[ "def", "noisy", "(", "pattern", ",", "noiseLevel", ",", "totalNumCells", ")", ":", "n", "=", "int", "(", "noiseLevel", "*", "len", "(", "pattern", ")", ")", "noised", "=", "set", "(", "pattern", ")", "noised", ".", "difference_update", "(", "random", "...
Generate a noisy copy of a pattern. Given number of active bits w = len(pattern), deactivate noiseLevel*w cells, and activate noiseLevel*w other cells. @param pattern (set) A set of active indices @param noiseLevel (float) The percentage of the bits to shuffle @param totalNumCells (int) The number of cells in the SDR, active and inactive @return (set) A noisy set of active indices
[ "Generate", "a", "noisy", "copy", "of", "a", "pattern", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/l2_pooling/noise_tolerance_l2_l4.py#L45-L77
train
198,846
numenta/htmresearch
projects/l2_pooling/noise_tolerance_l2_l4.py
createRandomObjects
def createRandomObjects(numObjects, locationsPerObject, featurePoolSize): """ Generate random objects. @param numObjects (int) The number of objects to generate @param locationsPerObject (int) The number of points on each object @param featurePoolSize (int) The number of possible features @return For example, { 0: [0, 1, 2], 1: [0, 2, 1], 2: [2, 0, 1], } is 3 objects. The first object has Feature 0 and Location 0, Feature 1 at Location 1, Feature 2 at location 2, etc. """ allFeatures = range(featurePoolSize) allLocations = range(locationsPerObject) objects = dict((name, [random.choice(allFeatures) for _ in xrange(locationsPerObject)]) for name in xrange(numObjects)) return objects
python
def createRandomObjects(numObjects, locationsPerObject, featurePoolSize): """ Generate random objects. @param numObjects (int) The number of objects to generate @param locationsPerObject (int) The number of points on each object @param featurePoolSize (int) The number of possible features @return For example, { 0: [0, 1, 2], 1: [0, 2, 1], 2: [2, 0, 1], } is 3 objects. The first object has Feature 0 and Location 0, Feature 1 at Location 1, Feature 2 at location 2, etc. """ allFeatures = range(featurePoolSize) allLocations = range(locationsPerObject) objects = dict((name, [random.choice(allFeatures) for _ in xrange(locationsPerObject)]) for name in xrange(numObjects)) return objects
[ "def", "createRandomObjects", "(", "numObjects", ",", "locationsPerObject", ",", "featurePoolSize", ")", ":", "allFeatures", "=", "range", "(", "featurePoolSize", ")", "allLocations", "=", "range", "(", "locationsPerObject", ")", "objects", "=", "dict", "(", "(", ...
Generate random objects. @param numObjects (int) The number of objects to generate @param locationsPerObject (int) The number of points on each object @param featurePoolSize (int) The number of possible features @return For example, { 0: [0, 1, 2], 1: [0, 2, 1], 2: [2, 0, 1], } is 3 objects. The first object has Feature 0 and Location 0, Feature 1 at Location 1, Feature 2 at location 2, etc.
[ "Generate", "random", "objects", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/l2_pooling/noise_tolerance_l2_l4.py#L80-L107
train
198,847
numenta/htmresearch
htmresearch/frameworks/layers/l2_l4_network_creation.py
createL4L2Column
def createL4L2Column(network, networkConfig, suffix=""): """ Create a a single column containing one L4 and one L2. networkConfig is a dict that must contain the following keys (additional keys ok): { "enableFeedback": True, "externalInputSize": 1024, "sensorInputSize": 1024, "L4RegionType": "py.ApicalTMPairRegion", "L4Params": { <constructor parameters for the L4 region> }, "L2Params": { <constructor parameters for ColumnPoolerRegion> }, "lateralSPParams": { <constructor parameters for optional SPRegion> }, "feedForwardSPParams": { <constructor parameters for optional SPRegion> } } Region names are externalInput, sensorInput, L4Column, and ColumnPoolerRegion. Each name has an optional string suffix appended to it. Configuration options: "lateralSPParams" and "feedForwardSPParams" are optional. If included appropriate spatial pooler regions will be added to the network. If externalInputSize is 0, the externalInput sensor (and SP if appropriate) will NOT be created. In this case it is expected that L4 is a sequence memory region (e.g. ApicalTMSequenceRegion) """ externalInputName = "externalInput" + suffix sensorInputName = "sensorInput" + suffix L4ColumnName = "L4Column" + suffix L2ColumnName = "L2Column" + suffix L4Params = copy.deepcopy(networkConfig["L4Params"]) L4Params["basalInputWidth"] = networkConfig["externalInputSize"] L4Params["apicalInputWidth"] = networkConfig["L2Params"]["cellCount"] if networkConfig["externalInputSize"] > 0: network.addRegion( externalInputName, "py.RawSensor", json.dumps({"outputWidth": networkConfig["externalInputSize"]})) network.addRegion( sensorInputName, "py.RawSensor", json.dumps({"outputWidth": networkConfig["sensorInputSize"]})) # Fixup network to include SP, if defined in networkConfig if networkConfig["externalInputSize"] > 0: _addLateralSPRegion(network, networkConfig, suffix) _addFeedForwardSPRegion(network, networkConfig, suffix) network.addRegion( L4ColumnName, networkConfig["L4RegionType"], json.dumps(L4Params)) network.addRegion( L2ColumnName, "py.ColumnPoolerRegion", json.dumps(networkConfig["L2Params"])) # Set phases appropriately so regions are executed in the proper sequence # This is required when we create multiple columns - the order of execution # is not the same as the order of region creation. if networkConfig["externalInputSize"] > 0: network.setPhases(externalInputName,[0]) network.setPhases(sensorInputName,[0]) _setLateralSPPhases(network, networkConfig) _setFeedForwardSPPhases(network, networkConfig) # L4 and L2 regions always have phases 2 and 3, respectively network.setPhases(L4ColumnName,[2]) network.setPhases(L2ColumnName,[3]) # Link SP region(s), if applicable if networkConfig["externalInputSize"] > 0: _linkLateralSPRegion(network, networkConfig, externalInputName, L4ColumnName) _linkFeedForwardSPRegion(network, networkConfig, sensorInputName, L4ColumnName) # Link L4 to L2 network.link(L4ColumnName, L2ColumnName, "UniformLink", "", srcOutput="activeCells", destInput="feedforwardInput") network.link(L4ColumnName, L2ColumnName, "UniformLink", "", srcOutput="predictedActiveCells", destInput="feedforwardGrowthCandidates") # Link L2 feedback to L4 if networkConfig.get("enableFeedback", True): network.link(L2ColumnName, L4ColumnName, "UniformLink", "", srcOutput="feedForwardOutput", destInput="apicalInput", propagationDelay=1) # Link reset output to L2 and L4 network.link(sensorInputName, L2ColumnName, "UniformLink", "", srcOutput="resetOut", destInput="resetIn") network.link(sensorInputName, L4ColumnName, "UniformLink", "", srcOutput="resetOut", destInput="resetIn") enableProfiling(network) return network
python
def createL4L2Column(network, networkConfig, suffix=""): """ Create a a single column containing one L4 and one L2. networkConfig is a dict that must contain the following keys (additional keys ok): { "enableFeedback": True, "externalInputSize": 1024, "sensorInputSize": 1024, "L4RegionType": "py.ApicalTMPairRegion", "L4Params": { <constructor parameters for the L4 region> }, "L2Params": { <constructor parameters for ColumnPoolerRegion> }, "lateralSPParams": { <constructor parameters for optional SPRegion> }, "feedForwardSPParams": { <constructor parameters for optional SPRegion> } } Region names are externalInput, sensorInput, L4Column, and ColumnPoolerRegion. Each name has an optional string suffix appended to it. Configuration options: "lateralSPParams" and "feedForwardSPParams" are optional. If included appropriate spatial pooler regions will be added to the network. If externalInputSize is 0, the externalInput sensor (and SP if appropriate) will NOT be created. In this case it is expected that L4 is a sequence memory region (e.g. ApicalTMSequenceRegion) """ externalInputName = "externalInput" + suffix sensorInputName = "sensorInput" + suffix L4ColumnName = "L4Column" + suffix L2ColumnName = "L2Column" + suffix L4Params = copy.deepcopy(networkConfig["L4Params"]) L4Params["basalInputWidth"] = networkConfig["externalInputSize"] L4Params["apicalInputWidth"] = networkConfig["L2Params"]["cellCount"] if networkConfig["externalInputSize"] > 0: network.addRegion( externalInputName, "py.RawSensor", json.dumps({"outputWidth": networkConfig["externalInputSize"]})) network.addRegion( sensorInputName, "py.RawSensor", json.dumps({"outputWidth": networkConfig["sensorInputSize"]})) # Fixup network to include SP, if defined in networkConfig if networkConfig["externalInputSize"] > 0: _addLateralSPRegion(network, networkConfig, suffix) _addFeedForwardSPRegion(network, networkConfig, suffix) network.addRegion( L4ColumnName, networkConfig["L4RegionType"], json.dumps(L4Params)) network.addRegion( L2ColumnName, "py.ColumnPoolerRegion", json.dumps(networkConfig["L2Params"])) # Set phases appropriately so regions are executed in the proper sequence # This is required when we create multiple columns - the order of execution # is not the same as the order of region creation. if networkConfig["externalInputSize"] > 0: network.setPhases(externalInputName,[0]) network.setPhases(sensorInputName,[0]) _setLateralSPPhases(network, networkConfig) _setFeedForwardSPPhases(network, networkConfig) # L4 and L2 regions always have phases 2 and 3, respectively network.setPhases(L4ColumnName,[2]) network.setPhases(L2ColumnName,[3]) # Link SP region(s), if applicable if networkConfig["externalInputSize"] > 0: _linkLateralSPRegion(network, networkConfig, externalInputName, L4ColumnName) _linkFeedForwardSPRegion(network, networkConfig, sensorInputName, L4ColumnName) # Link L4 to L2 network.link(L4ColumnName, L2ColumnName, "UniformLink", "", srcOutput="activeCells", destInput="feedforwardInput") network.link(L4ColumnName, L2ColumnName, "UniformLink", "", srcOutput="predictedActiveCells", destInput="feedforwardGrowthCandidates") # Link L2 feedback to L4 if networkConfig.get("enableFeedback", True): network.link(L2ColumnName, L4ColumnName, "UniformLink", "", srcOutput="feedForwardOutput", destInput="apicalInput", propagationDelay=1) # Link reset output to L2 and L4 network.link(sensorInputName, L2ColumnName, "UniformLink", "", srcOutput="resetOut", destInput="resetIn") network.link(sensorInputName, L4ColumnName, "UniformLink", "", srcOutput="resetOut", destInput="resetIn") enableProfiling(network) return network
[ "def", "createL4L2Column", "(", "network", ",", "networkConfig", ",", "suffix", "=", "\"\"", ")", ":", "externalInputName", "=", "\"externalInput\"", "+", "suffix", "sensorInputName", "=", "\"sensorInput\"", "+", "suffix", "L4ColumnName", "=", "\"L4Column\"", "+", ...
Create a a single column containing one L4 and one L2. networkConfig is a dict that must contain the following keys (additional keys ok): { "enableFeedback": True, "externalInputSize": 1024, "sensorInputSize": 1024, "L4RegionType": "py.ApicalTMPairRegion", "L4Params": { <constructor parameters for the L4 region> }, "L2Params": { <constructor parameters for ColumnPoolerRegion> }, "lateralSPParams": { <constructor parameters for optional SPRegion> }, "feedForwardSPParams": { <constructor parameters for optional SPRegion> } } Region names are externalInput, sensorInput, L4Column, and ColumnPoolerRegion. Each name has an optional string suffix appended to it. Configuration options: "lateralSPParams" and "feedForwardSPParams" are optional. If included appropriate spatial pooler regions will be added to the network. If externalInputSize is 0, the externalInput sensor (and SP if appropriate) will NOT be created. In this case it is expected that L4 is a sequence memory region (e.g. ApicalTMSequenceRegion)
[ "Create", "a", "a", "single", "column", "containing", "one", "L4", "and", "one", "L2", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/l2_l4_network_creation.py#L185-L293
train
198,848
numenta/htmresearch
htmresearch/frameworks/layers/l2_l4_network_creation.py
createMultipleL4L2Columns
def createMultipleL4L2Columns(network, networkConfig): """ Create a network consisting of multiple columns. Each column contains one L4 and one L2, is identical in structure to the network created by createL4L2Column. In addition all the L2 columns are fully connected to each other through their lateral inputs. Region names have a column number appended as in externalInput_0, externalInput_1, etc. networkConfig must be of the following format (see createL4L2Column for further documentation): { "networkType": "MultipleL4L2Columns", "numCorticalColumns": 3, "externalInputSize": 1024, "sensorInputSize": 1024, "L4Params": { <constructor parameters for ApicalTMPairRegion }, "L2Params": { <constructor parameters for ColumnPoolerRegion> }, "lateralSPParams": { <constructor parameters for optional SPRegion> }, "feedForwardSPParams": { <constructor parameters for optional SPRegion> } } """ # Create each column numCorticalColumns = networkConfig["numCorticalColumns"] for i in xrange(numCorticalColumns): networkConfigCopy = copy.deepcopy(networkConfig) layerConfig = networkConfigCopy["L2Params"] layerConfig["seed"] = layerConfig.get("seed", 42) + i layerConfig["numOtherCorticalColumns"] = numCorticalColumns - 1 suffix = "_" + str(i) network = createL4L2Column(network, networkConfigCopy, suffix) # Now connect the L2 columns laterally for i in range(networkConfig["numCorticalColumns"]): suffixSrc = "_" + str(i) for j in range(networkConfig["numCorticalColumns"]): if i != j: suffixDest = "_" + str(j) network.link( "L2Column" + suffixSrc, "L2Column" + suffixDest, "UniformLink", "", srcOutput="feedForwardOutput", destInput="lateralInput", propagationDelay=1) enableProfiling(network) return network
python
def createMultipleL4L2Columns(network, networkConfig): """ Create a network consisting of multiple columns. Each column contains one L4 and one L2, is identical in structure to the network created by createL4L2Column. In addition all the L2 columns are fully connected to each other through their lateral inputs. Region names have a column number appended as in externalInput_0, externalInput_1, etc. networkConfig must be of the following format (see createL4L2Column for further documentation): { "networkType": "MultipleL4L2Columns", "numCorticalColumns": 3, "externalInputSize": 1024, "sensorInputSize": 1024, "L4Params": { <constructor parameters for ApicalTMPairRegion }, "L2Params": { <constructor parameters for ColumnPoolerRegion> }, "lateralSPParams": { <constructor parameters for optional SPRegion> }, "feedForwardSPParams": { <constructor parameters for optional SPRegion> } } """ # Create each column numCorticalColumns = networkConfig["numCorticalColumns"] for i in xrange(numCorticalColumns): networkConfigCopy = copy.deepcopy(networkConfig) layerConfig = networkConfigCopy["L2Params"] layerConfig["seed"] = layerConfig.get("seed", 42) + i layerConfig["numOtherCorticalColumns"] = numCorticalColumns - 1 suffix = "_" + str(i) network = createL4L2Column(network, networkConfigCopy, suffix) # Now connect the L2 columns laterally for i in range(networkConfig["numCorticalColumns"]): suffixSrc = "_" + str(i) for j in range(networkConfig["numCorticalColumns"]): if i != j: suffixDest = "_" + str(j) network.link( "L2Column" + suffixSrc, "L2Column" + suffixDest, "UniformLink", "", srcOutput="feedForwardOutput", destInput="lateralInput", propagationDelay=1) enableProfiling(network) return network
[ "def", "createMultipleL4L2Columns", "(", "network", ",", "networkConfig", ")", ":", "# Create each column", "numCorticalColumns", "=", "networkConfig", "[", "\"numCorticalColumns\"", "]", "for", "i", "in", "xrange", "(", "numCorticalColumns", ")", ":", "networkConfigCop...
Create a network consisting of multiple columns. Each column contains one L4 and one L2, is identical in structure to the network created by createL4L2Column. In addition all the L2 columns are fully connected to each other through their lateral inputs. Region names have a column number appended as in externalInput_0, externalInput_1, etc. networkConfig must be of the following format (see createL4L2Column for further documentation): { "networkType": "MultipleL4L2Columns", "numCorticalColumns": 3, "externalInputSize": 1024, "sensorInputSize": 1024, "L4Params": { <constructor parameters for ApicalTMPairRegion }, "L2Params": { <constructor parameters for ColumnPoolerRegion> }, "lateralSPParams": { <constructor parameters for optional SPRegion> }, "feedForwardSPParams": { <constructor parameters for optional SPRegion> } }
[ "Create", "a", "network", "consisting", "of", "multiple", "columns", ".", "Each", "column", "contains", "one", "L4", "and", "one", "L2", "is", "identical", "in", "structure", "to", "the", "network", "created", "by", "createL4L2Column", ".", "In", "addition", ...
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/l2_l4_network_creation.py#L296-L355
train
198,849
numenta/htmresearch
htmresearch/frameworks/layers/l2_l4_network_creation.py
createMultipleL4L2ColumnsWithTopology
def createMultipleL4L2ColumnsWithTopology(network, networkConfig): """ Create a network consisting of multiple columns. Each column contains one L4 and one L2, is identical in structure to the network created by createL4L2Column. In addition the L2 columns are connected to each other through their lateral inputs, based on the topological information provided. Region names have a column number appended as in externalInput_0, externalInput_1, etc. networkConfig must be of the following format (see createL4L2Column for further documentation): { "networkType": "MultipleL4L2Columns", "numCorticalColumns": 3, "externalInputSize": 1024, "sensorInputSize": 1024, "columnPositions": a list of 2D coordinates, one for each column. Used to calculate the connections between columns. By convention, coordinates are integers. "maxConnectionDistance": should be a value >= 1. Determines how distant of columns will be connected to each other. Useful specific values are 1 and 1.5, which typically create grids without and with diagonal connections, respectively. "longDistanceConnections": Should be a value in [0,1). This is the probability that a column forms a connection with a distant column (i.e. beyond its normal connection distance). If this value is not provided, it defaults to 0, and all connections will be in the local vicinity. "L4Params": { <constructor parameters for ApicalTMPairRegion> }, "L2Params": { <constructor parameters for ColumnPoolerRegion> }, "lateralSPParams": { <constructor parameters for optional SPRegion> }, "feedForwardSPParams": { <constructor parameters for optional SPRegion> } } """ numCorticalColumns = networkConfig["numCorticalColumns"] output_lateral_connections = [[] for i in xrange(numCorticalColumns)] input_lateral_connections = [[] for i in xrange(numCorticalColumns)] # If no column positions are provided, create a grid by default. # This is typically what the user wants, so it makes sense to have it as # a default. columnPositions = networkConfig.get("columnPositions", None) if columnPositions is None: columnPositions = [] side_length = int(numpy.ceil(numpy.sqrt(numCorticalColumns))) for i in range(side_length): for j in range(side_length): columnPositions.append((i, j)) columnPositions = columnPositions[:numCorticalColumns] # Determine which columns will be mutually connected. # This has to be done before the actual creation of the network, as each # individual column need to know how many columns it is laterally connected # to. These results are then used to actually connect the columns, once # the network is created. It's awkward, but unavoidable. longDistanceConnections = networkConfig.get("longDistanceConnections", 0.) for i, src_pos in enumerate(columnPositions): for j, dest_pos in enumerate(columnPositions): if i != j: if (numpy.linalg.norm(numpy.asarray(src_pos) - numpy.asarray(dest_pos)) <= networkConfig["maxConnectionDistance"] or numpy.random.rand() < longDistanceConnections): output_lateral_connections[i].append(j) input_lateral_connections[j].append(i) # Create each column for i in xrange(numCorticalColumns): networkConfigCopy = copy.deepcopy(networkConfig) layerConfig = networkConfigCopy["L2Params"] layerConfig["seed"] = layerConfig.get("seed", 42) + i layerConfig["numOtherCorticalColumns"] = len(input_lateral_connections[i]) suffix = "_" + str(i) network = createL4L2Column(network, networkConfigCopy, suffix) # Now connect the L2 columns laterally for i, connections in enumerate(output_lateral_connections): suffixSrc = "_" + str(i) for j in connections: suffixDest = "_" + str(j) network.link("L2Column" + suffixSrc, "L2Column" + suffixDest, "UniformLink", "", srcOutput="feedForwardOutput", destInput="lateralInput", propagationDelay=1) enableProfiling(network) return network
python
def createMultipleL4L2ColumnsWithTopology(network, networkConfig): """ Create a network consisting of multiple columns. Each column contains one L4 and one L2, is identical in structure to the network created by createL4L2Column. In addition the L2 columns are connected to each other through their lateral inputs, based on the topological information provided. Region names have a column number appended as in externalInput_0, externalInput_1, etc. networkConfig must be of the following format (see createL4L2Column for further documentation): { "networkType": "MultipleL4L2Columns", "numCorticalColumns": 3, "externalInputSize": 1024, "sensorInputSize": 1024, "columnPositions": a list of 2D coordinates, one for each column. Used to calculate the connections between columns. By convention, coordinates are integers. "maxConnectionDistance": should be a value >= 1. Determines how distant of columns will be connected to each other. Useful specific values are 1 and 1.5, which typically create grids without and with diagonal connections, respectively. "longDistanceConnections": Should be a value in [0,1). This is the probability that a column forms a connection with a distant column (i.e. beyond its normal connection distance). If this value is not provided, it defaults to 0, and all connections will be in the local vicinity. "L4Params": { <constructor parameters for ApicalTMPairRegion> }, "L2Params": { <constructor parameters for ColumnPoolerRegion> }, "lateralSPParams": { <constructor parameters for optional SPRegion> }, "feedForwardSPParams": { <constructor parameters for optional SPRegion> } } """ numCorticalColumns = networkConfig["numCorticalColumns"] output_lateral_connections = [[] for i in xrange(numCorticalColumns)] input_lateral_connections = [[] for i in xrange(numCorticalColumns)] # If no column positions are provided, create a grid by default. # This is typically what the user wants, so it makes sense to have it as # a default. columnPositions = networkConfig.get("columnPositions", None) if columnPositions is None: columnPositions = [] side_length = int(numpy.ceil(numpy.sqrt(numCorticalColumns))) for i in range(side_length): for j in range(side_length): columnPositions.append((i, j)) columnPositions = columnPositions[:numCorticalColumns] # Determine which columns will be mutually connected. # This has to be done before the actual creation of the network, as each # individual column need to know how many columns it is laterally connected # to. These results are then used to actually connect the columns, once # the network is created. It's awkward, but unavoidable. longDistanceConnections = networkConfig.get("longDistanceConnections", 0.) for i, src_pos in enumerate(columnPositions): for j, dest_pos in enumerate(columnPositions): if i != j: if (numpy.linalg.norm(numpy.asarray(src_pos) - numpy.asarray(dest_pos)) <= networkConfig["maxConnectionDistance"] or numpy.random.rand() < longDistanceConnections): output_lateral_connections[i].append(j) input_lateral_connections[j].append(i) # Create each column for i in xrange(numCorticalColumns): networkConfigCopy = copy.deepcopy(networkConfig) layerConfig = networkConfigCopy["L2Params"] layerConfig["seed"] = layerConfig.get("seed", 42) + i layerConfig["numOtherCorticalColumns"] = len(input_lateral_connections[i]) suffix = "_" + str(i) network = createL4L2Column(network, networkConfigCopy, suffix) # Now connect the L2 columns laterally for i, connections in enumerate(output_lateral_connections): suffixSrc = "_" + str(i) for j in connections: suffixDest = "_" + str(j) network.link("L2Column" + suffixSrc, "L2Column" + suffixDest, "UniformLink", "", srcOutput="feedForwardOutput", destInput="lateralInput", propagationDelay=1) enableProfiling(network) return network
[ "def", "createMultipleL4L2ColumnsWithTopology", "(", "network", ",", "networkConfig", ")", ":", "numCorticalColumns", "=", "networkConfig", "[", "\"numCorticalColumns\"", "]", "output_lateral_connections", "=", "[", "[", "]", "for", "i", "in", "xrange", "(", "numCorti...
Create a network consisting of multiple columns. Each column contains one L4 and one L2, is identical in structure to the network created by createL4L2Column. In addition the L2 columns are connected to each other through their lateral inputs, based on the topological information provided. Region names have a column number appended as in externalInput_0, externalInput_1, etc. networkConfig must be of the following format (see createL4L2Column for further documentation): { "networkType": "MultipleL4L2Columns", "numCorticalColumns": 3, "externalInputSize": 1024, "sensorInputSize": 1024, "columnPositions": a list of 2D coordinates, one for each column. Used to calculate the connections between columns. By convention, coordinates are integers. "maxConnectionDistance": should be a value >= 1. Determines how distant of columns will be connected to each other. Useful specific values are 1 and 1.5, which typically create grids without and with diagonal connections, respectively. "longDistanceConnections": Should be a value in [0,1). This is the probability that a column forms a connection with a distant column (i.e. beyond its normal connection distance). If this value is not provided, it defaults to 0, and all connections will be in the local vicinity. "L4Params": { <constructor parameters for ApicalTMPairRegion> }, "L2Params": { <constructor parameters for ColumnPoolerRegion> }, "lateralSPParams": { <constructor parameters for optional SPRegion> }, "feedForwardSPParams": { <constructor parameters for optional SPRegion> } }
[ "Create", "a", "network", "consisting", "of", "multiple", "columns", ".", "Each", "column", "contains", "one", "L4", "and", "one", "L2", "is", "identical", "in", "structure", "to", "the", "network", "created", "by", "createL4L2Column", ".", "In", "addition", ...
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/l2_l4_network_creation.py#L358-L459
train
198,850
numenta/htmresearch
projects/high_order_cell_assembly/sparsity_over_trial.py
loadExperimentData
def loadExperimentData(folder, area): """ Loads the experiment's data from a MATLAB file into a python friendly structure. :param folder: Experiment data folder :param area: Experiament area to load. It should be 'V1' or 'AL' :return: The data as scipy matlab structure with the following fields: :Spiketrain.st: spike timing during stimulus (grating or naturalistic movie). :Spiketrain.st_gray: the spike timing during gray screen. The unit for spike timing is sampling frame. And spike timing is a 20X3 cell (corresponding to 20 repeats, and 3 stimulus (grating, and two naturalistic stimuli)). The same for the spike timing of gray screen. :imgPara.stim_type: 3 type of stimulus, grating and two naturalistic stimuli. :imgPara.stim_time: the length of each stimulus is 32 sec. :imgPara.updatefr: the frame rate of stimulus on screen is 60 Hz. :imgPara.intertime: the time between two stimulus, or gray screen is 8 sec. :imgPara.dt: the sample rate, ~0.075 :imgPara.F: number of sampling frames during stimulus is 32/0.075~=426 :imgPara.F_gray: number of sampling frames during gray screen is 8/0.075~=106 :ROI: the location of each neuron in the field. """ filename = os.path.join(folder, "Combo3_{}.mat".format(area)) contents = sio.loadmat(filename, variable_names=['data'], struct_as_record=False, squeeze_me=True) return contents['data']
python
def loadExperimentData(folder, area): """ Loads the experiment's data from a MATLAB file into a python friendly structure. :param folder: Experiment data folder :param area: Experiament area to load. It should be 'V1' or 'AL' :return: The data as scipy matlab structure with the following fields: :Spiketrain.st: spike timing during stimulus (grating or naturalistic movie). :Spiketrain.st_gray: the spike timing during gray screen. The unit for spike timing is sampling frame. And spike timing is a 20X3 cell (corresponding to 20 repeats, and 3 stimulus (grating, and two naturalistic stimuli)). The same for the spike timing of gray screen. :imgPara.stim_type: 3 type of stimulus, grating and two naturalistic stimuli. :imgPara.stim_time: the length of each stimulus is 32 sec. :imgPara.updatefr: the frame rate of stimulus on screen is 60 Hz. :imgPara.intertime: the time between two stimulus, or gray screen is 8 sec. :imgPara.dt: the sample rate, ~0.075 :imgPara.F: number of sampling frames during stimulus is 32/0.075~=426 :imgPara.F_gray: number of sampling frames during gray screen is 8/0.075~=106 :ROI: the location of each neuron in the field. """ filename = os.path.join(folder, "Combo3_{}.mat".format(area)) contents = sio.loadmat(filename, variable_names=['data'], struct_as_record=False, squeeze_me=True) return contents['data']
[ "def", "loadExperimentData", "(", "folder", ",", "area", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "folder", ",", "\"Combo3_{}.mat\"", ".", "format", "(", "area", ")", ")", "contents", "=", "sio", ".", "loadmat", "(", "filename", ...
Loads the experiment's data from a MATLAB file into a python friendly structure. :param folder: Experiment data folder :param area: Experiament area to load. It should be 'V1' or 'AL' :return: The data as scipy matlab structure with the following fields: :Spiketrain.st: spike timing during stimulus (grating or naturalistic movie). :Spiketrain.st_gray: the spike timing during gray screen. The unit for spike timing is sampling frame. And spike timing is a 20X3 cell (corresponding to 20 repeats, and 3 stimulus (grating, and two naturalistic stimuli)). The same for the spike timing of gray screen. :imgPara.stim_type: 3 type of stimulus, grating and two naturalistic stimuli. :imgPara.stim_time: the length of each stimulus is 32 sec. :imgPara.updatefr: the frame rate of stimulus on screen is 60 Hz. :imgPara.intertime: the time between two stimulus, or gray screen is 8 sec. :imgPara.dt: the sample rate, ~0.075 :imgPara.F: number of sampling frames during stimulus is 32/0.075~=426 :imgPara.F_gray: number of sampling frames during gray screen is 8/0.075~=106 :ROI: the location of each neuron in the field.
[ "Loads", "the", "experiment", "s", "data", "from", "a", "MATLAB", "file", "into", "a", "python", "friendly", "structure", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/high_order_cell_assembly/sparsity_over_trial.py#L35-L61
train
198,851
numenta/htmresearch
projects/l2_pooling/ideal_classifier_experiment.py
classifierPredict
def classifierPredict(testVector, storedVectors): """ Return overlap of the testVector with stored representations for each object. """ numClasses = storedVectors.shape[0] output = np.zeros((numClasses,)) for i in range(numClasses): output[i] = np.sum(np.minimum(testVector, storedVectors[i, :])) return output
python
def classifierPredict(testVector, storedVectors): """ Return overlap of the testVector with stored representations for each object. """ numClasses = storedVectors.shape[0] output = np.zeros((numClasses,)) for i in range(numClasses): output[i] = np.sum(np.minimum(testVector, storedVectors[i, :])) return output
[ "def", "classifierPredict", "(", "testVector", ",", "storedVectors", ")", ":", "numClasses", "=", "storedVectors", ".", "shape", "[", "0", "]", "output", "=", "np", ".", "zeros", "(", "(", "numClasses", ",", ")", ")", "for", "i", "in", "range", "(", "n...
Return overlap of the testVector with stored representations for each object.
[ "Return", "overlap", "of", "the", "testVector", "with", "stored", "representations", "for", "each", "object", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/l2_pooling/ideal_classifier_experiment.py#L85-L94
train
198,852
numenta/htmresearch
projects/l2_pooling/ideal_classifier_experiment.py
run_multiple_column_experiment
def run_multiple_column_experiment(): """ Compare the ideal observer against a multi-column sensorimotor network. """ # Create the objects featureRange = [5, 10, 20, 30] pointRange = 1 objectRange = [100] numLocations = [10] numPoints = 10 numTrials = 10 columnRange = [1, 2, 3, 4, 5, 6, 7, 8] useLocation = 1 resultsDir = os.path.dirname(os.path.realpath(__file__)) args = [] for c in reversed(columnRange): for o in reversed(objectRange): for l in numLocations: for f in featureRange: for t in range(numTrials): args.append( {"numObjects": o, "numLocations": l, "numFeatures": f, "numColumns": c, "trialNum": t, "pointRange": pointRange, "numPoints": numPoints, "useLocation": useLocation } ) print "Number of experiments:",len(args) idealResultsFile = os.path.join(resultsDir, "ideal_multi_column_useLocation_{}.pkl".format(useLocation)) pool = Pool(processes=cpu_count()) result = pool.map(run_ideal_classifier, args) # Pickle results for later use with open(idealResultsFile, "wb") as f: cPickle.dump(result, f) htmResultsFile = os.path.join(resultsDir, "column_convergence_results.pkl") runExperimentPool( numObjects=objectRange, numLocations=[10], numFeatures=featureRange, numColumns=columnRange, numPoints=10, nTrials=numTrials, numWorkers=cpu_count(), resultsName=htmResultsFile) with open(htmResultsFile, "rb") as f: results = cPickle.load(f) with open(idealResultsFile, "rb") as f: resultsIdeal = cPickle.load(f) plt.figure() plotConvergenceByColumn(results, columnRange, featureRange, numTrials) plotConvergenceByColumn(resultsIdeal, columnRange, featureRange, numTrials, "--") plt.savefig('plots/ideal_observer_multiple_column.pdf')
python
def run_multiple_column_experiment(): """ Compare the ideal observer against a multi-column sensorimotor network. """ # Create the objects featureRange = [5, 10, 20, 30] pointRange = 1 objectRange = [100] numLocations = [10] numPoints = 10 numTrials = 10 columnRange = [1, 2, 3, 4, 5, 6, 7, 8] useLocation = 1 resultsDir = os.path.dirname(os.path.realpath(__file__)) args = [] for c in reversed(columnRange): for o in reversed(objectRange): for l in numLocations: for f in featureRange: for t in range(numTrials): args.append( {"numObjects": o, "numLocations": l, "numFeatures": f, "numColumns": c, "trialNum": t, "pointRange": pointRange, "numPoints": numPoints, "useLocation": useLocation } ) print "Number of experiments:",len(args) idealResultsFile = os.path.join(resultsDir, "ideal_multi_column_useLocation_{}.pkl".format(useLocation)) pool = Pool(processes=cpu_count()) result = pool.map(run_ideal_classifier, args) # Pickle results for later use with open(idealResultsFile, "wb") as f: cPickle.dump(result, f) htmResultsFile = os.path.join(resultsDir, "column_convergence_results.pkl") runExperimentPool( numObjects=objectRange, numLocations=[10], numFeatures=featureRange, numColumns=columnRange, numPoints=10, nTrials=numTrials, numWorkers=cpu_count(), resultsName=htmResultsFile) with open(htmResultsFile, "rb") as f: results = cPickle.load(f) with open(idealResultsFile, "rb") as f: resultsIdeal = cPickle.load(f) plt.figure() plotConvergenceByColumn(results, columnRange, featureRange, numTrials) plotConvergenceByColumn(resultsIdeal, columnRange, featureRange, numTrials, "--") plt.savefig('plots/ideal_observer_multiple_column.pdf')
[ "def", "run_multiple_column_experiment", "(", ")", ":", "# Create the objects", "featureRange", "=", "[", "5", ",", "10", ",", "20", ",", "30", "]", "pointRange", "=", "1", "objectRange", "=", "[", "100", "]", "numLocations", "=", "[", "10", "]", "numPoint...
Compare the ideal observer against a multi-column sensorimotor network.
[ "Compare", "the", "ideal", "observer", "against", "a", "multi", "-", "column", "sensorimotor", "network", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/l2_pooling/ideal_classifier_experiment.py#L432-L497
train
198,853
numenta/htmresearch
htmresearch/support/logging_decorator.py
LoggingDecorator.save
def save(callLog, logFilename): """ Save the call log history into this file. @param logFilename (path) Filename in which to save a pickled version of the call logs. """ with open(logFilename, "wb") as outp: cPickle.dump(callLog, outp)
python
def save(callLog, logFilename): """ Save the call log history into this file. @param logFilename (path) Filename in which to save a pickled version of the call logs. """ with open(logFilename, "wb") as outp: cPickle.dump(callLog, outp)
[ "def", "save", "(", "callLog", ",", "logFilename", ")", ":", "with", "open", "(", "logFilename", ",", "\"wb\"", ")", "as", "outp", ":", "cPickle", ".", "dump", "(", "callLog", ",", "outp", ")" ]
Save the call log history into this file. @param logFilename (path) Filename in which to save a pickled version of the call logs.
[ "Save", "the", "call", "log", "history", "into", "this", "file", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/logging_decorator.py#L92-L101
train
198,854
numenta/htmresearch
htmresearch/frameworks/layers/combined_sequence_experiment2.py
CombinedSequenceExperiment._getDefaultCombinedL4Params
def _getDefaultCombinedL4Params(self, numInputBits, inputSize, numExternalInputBits, externalInputSize, L2CellCount): """ Returns a good default set of parameters to use in a combined L4 region. """ sampleSize = numExternalInputBits + numInputBits activationThreshold = int(max(numExternalInputBits, numInputBits) * .6) minThreshold = activationThreshold return { "columnCount": inputSize, "cellsPerColumn": 16, "learn": True, "learnOnOneCell": False, "initialPermanence": 0.41, "connectedPermanence": 0.6, "permanenceIncrement": 0.1, "permanenceDecrement": 0.02, "minThreshold": minThreshold, "basalPredictedSegmentDecrement": 0.001, "apicalPredictedSegmentDecrement": 0.0, "reducedBasalThreshold": int(activationThreshold*0.6), "activationThreshold": activationThreshold, "sampleSize": sampleSize, "implementation": "ApicalTiebreak", "seed": self.seed, "basalInputWidth": inputSize*16 + externalInputSize, "apicalInputWidth": L2CellCount, }
python
def _getDefaultCombinedL4Params(self, numInputBits, inputSize, numExternalInputBits, externalInputSize, L2CellCount): """ Returns a good default set of parameters to use in a combined L4 region. """ sampleSize = numExternalInputBits + numInputBits activationThreshold = int(max(numExternalInputBits, numInputBits) * .6) minThreshold = activationThreshold return { "columnCount": inputSize, "cellsPerColumn": 16, "learn": True, "learnOnOneCell": False, "initialPermanence": 0.41, "connectedPermanence": 0.6, "permanenceIncrement": 0.1, "permanenceDecrement": 0.02, "minThreshold": minThreshold, "basalPredictedSegmentDecrement": 0.001, "apicalPredictedSegmentDecrement": 0.0, "reducedBasalThreshold": int(activationThreshold*0.6), "activationThreshold": activationThreshold, "sampleSize": sampleSize, "implementation": "ApicalTiebreak", "seed": self.seed, "basalInputWidth": inputSize*16 + externalInputSize, "apicalInputWidth": L2CellCount, }
[ "def", "_getDefaultCombinedL4Params", "(", "self", ",", "numInputBits", ",", "inputSize", ",", "numExternalInputBits", ",", "externalInputSize", ",", "L2CellCount", ")", ":", "sampleSize", "=", "numExternalInputBits", "+", "numInputBits", "activationThreshold", "=", "in...
Returns a good default set of parameters to use in a combined L4 region.
[ "Returns", "a", "good", "default", "set", "of", "parameters", "to", "use", "in", "a", "combined", "L4", "region", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/combined_sequence_experiment2.py#L138-L167
train
198,855
numenta/htmresearch
htmresearch/frameworks/location/ambiguity_index.py
findBinomialNsWithExpectedSampleMinimum
def findBinomialNsWithExpectedSampleMinimum(desiredValuesSorted, p, numSamples, nMax): """ For each desired value, find an approximate n for which the sample minimum has a expected value equal to this value. For each value, find an adjacent pair of n values whose expected sample minima are below and above the desired value, respectively, and return a linearly-interpolated n between these two values. @param p (float) The p if the binomial distribution. @param numSamples (int) The number of samples in the sample minimum distribution. @return A list of results. Each result contains (interpolated_n, lower_value, upper_value). where each lower_value and upper_value are the expected sample minimum for floor(interpolated_n) and ceil(interpolated_n) """ # mapping from n -> expected value actualValues = [ getExpectedValue( SampleMinimumDistribution(numSamples, BinomialDistribution(n, p, cache=True))) for n in xrange(nMax + 1)] results = [] n = 0 for desiredValue in desiredValuesSorted: while n + 1 <= nMax and actualValues[n + 1] < desiredValue: n += 1 if n + 1 > nMax: break interpolated = n + ((desiredValue - actualValues[n]) / (actualValues[n+1] - actualValues[n])) result = (interpolated, actualValues[n], actualValues[n + 1]) results.append(result) return results
python
def findBinomialNsWithExpectedSampleMinimum(desiredValuesSorted, p, numSamples, nMax): """ For each desired value, find an approximate n for which the sample minimum has a expected value equal to this value. For each value, find an adjacent pair of n values whose expected sample minima are below and above the desired value, respectively, and return a linearly-interpolated n between these two values. @param p (float) The p if the binomial distribution. @param numSamples (int) The number of samples in the sample minimum distribution. @return A list of results. Each result contains (interpolated_n, lower_value, upper_value). where each lower_value and upper_value are the expected sample minimum for floor(interpolated_n) and ceil(interpolated_n) """ # mapping from n -> expected value actualValues = [ getExpectedValue( SampleMinimumDistribution(numSamples, BinomialDistribution(n, p, cache=True))) for n in xrange(nMax + 1)] results = [] n = 0 for desiredValue in desiredValuesSorted: while n + 1 <= nMax and actualValues[n + 1] < desiredValue: n += 1 if n + 1 > nMax: break interpolated = n + ((desiredValue - actualValues[n]) / (actualValues[n+1] - actualValues[n])) result = (interpolated, actualValues[n], actualValues[n + 1]) results.append(result) return results
[ "def", "findBinomialNsWithExpectedSampleMinimum", "(", "desiredValuesSorted", ",", "p", ",", "numSamples", ",", "nMax", ")", ":", "# mapping from n -> expected value", "actualValues", "=", "[", "getExpectedValue", "(", "SampleMinimumDistribution", "(", "numSamples", ",", ...
For each desired value, find an approximate n for which the sample minimum has a expected value equal to this value. For each value, find an adjacent pair of n values whose expected sample minima are below and above the desired value, respectively, and return a linearly-interpolated n between these two values. @param p (float) The p if the binomial distribution. @param numSamples (int) The number of samples in the sample minimum distribution. @return A list of results. Each result contains (interpolated_n, lower_value, upper_value). where each lower_value and upper_value are the expected sample minimum for floor(interpolated_n) and ceil(interpolated_n)
[ "For", "each", "desired", "value", "find", "an", "approximate", "n", "for", "which", "the", "sample", "minimum", "has", "a", "expected", "value", "equal", "to", "this", "value", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/location/ambiguity_index.py#L127-L172
train
198,856
numenta/htmresearch
htmresearch/frameworks/location/ambiguity_index.py
findBinomialNsWithLowerBoundSampleMinimum
def findBinomialNsWithLowerBoundSampleMinimum(confidence, desiredValuesSorted, p, numSamples, nMax): """ For each desired value, find an approximate n for which the sample minimum has a probabilistic lower bound equal to this value. For each value, find an adjacent pair of n values whose lower bound sample minima are below and above the desired value, respectively, and return a linearly-interpolated n between these two values. @param confidence (float) For the probabilistic lower bound, this specifies the probability. If this is 0.8, that means that there's an 80% chance that the sample minimum is >= the desired value, and 20% chance that it's < the desired value. @param p (float) The p if the binomial distribution. @param numSamples (int) The number of samples in the sample minimum distribution. @return A list of results. Each result contains (interpolated_n, lower_value, upper_value). where each lower_value and upper_value are the probabilistic lower bound sample minimum for floor(interpolated_n) and ceil(interpolated_n) respectively. ...] """ def P(n, numOccurrences): """ Given n, return probability than the sample minimum is >= numOccurrences """ return 1 - SampleMinimumDistribution(numSamples, BinomialDistribution(n, p)).cdf( numOccurrences - 1) results = [] n = 0 for desiredValue in desiredValuesSorted: while n + 1 <= nMax and P(n + 1, desiredValue) < confidence: n += 1 if n + 1 > nMax: break left = P(n, desiredValue) right = P(n + 1, desiredValue) interpolated = n + ((confidence - left) / (right - left)) result = (interpolated, left, right) results.append(result) return results
python
def findBinomialNsWithLowerBoundSampleMinimum(confidence, desiredValuesSorted, p, numSamples, nMax): """ For each desired value, find an approximate n for which the sample minimum has a probabilistic lower bound equal to this value. For each value, find an adjacent pair of n values whose lower bound sample minima are below and above the desired value, respectively, and return a linearly-interpolated n between these two values. @param confidence (float) For the probabilistic lower bound, this specifies the probability. If this is 0.8, that means that there's an 80% chance that the sample minimum is >= the desired value, and 20% chance that it's < the desired value. @param p (float) The p if the binomial distribution. @param numSamples (int) The number of samples in the sample minimum distribution. @return A list of results. Each result contains (interpolated_n, lower_value, upper_value). where each lower_value and upper_value are the probabilistic lower bound sample minimum for floor(interpolated_n) and ceil(interpolated_n) respectively. ...] """ def P(n, numOccurrences): """ Given n, return probability than the sample minimum is >= numOccurrences """ return 1 - SampleMinimumDistribution(numSamples, BinomialDistribution(n, p)).cdf( numOccurrences - 1) results = [] n = 0 for desiredValue in desiredValuesSorted: while n + 1 <= nMax and P(n + 1, desiredValue) < confidence: n += 1 if n + 1 > nMax: break left = P(n, desiredValue) right = P(n + 1, desiredValue) interpolated = n + ((confidence - left) / (right - left)) result = (interpolated, left, right) results.append(result) return results
[ "def", "findBinomialNsWithLowerBoundSampleMinimum", "(", "confidence", ",", "desiredValuesSorted", ",", "p", ",", "numSamples", ",", "nMax", ")", ":", "def", "P", "(", "n", ",", "numOccurrences", ")", ":", "\"\"\"\n Given n, return probability than the sample minimum i...
For each desired value, find an approximate n for which the sample minimum has a probabilistic lower bound equal to this value. For each value, find an adjacent pair of n values whose lower bound sample minima are below and above the desired value, respectively, and return a linearly-interpolated n between these two values. @param confidence (float) For the probabilistic lower bound, this specifies the probability. If this is 0.8, that means that there's an 80% chance that the sample minimum is >= the desired value, and 20% chance that it's < the desired value. @param p (float) The p if the binomial distribution. @param numSamples (int) The number of samples in the sample minimum distribution. @return A list of results. Each result contains (interpolated_n, lower_value, upper_value). where each lower_value and upper_value are the probabilistic lower bound sample minimum for floor(interpolated_n) and ceil(interpolated_n) respectively. ...]
[ "For", "each", "desired", "value", "find", "an", "approximate", "n", "for", "which", "the", "sample", "minimum", "has", "a", "probabilistic", "lower", "bound", "equal", "to", "this", "value", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/location/ambiguity_index.py#L175-L231
train
198,857
numenta/htmresearch
htmresearch/frameworks/specific_timing/timing_adtm.py
TimingADTM.tempoAdjust1
def tempoAdjust1(self, tempoFactor): """ Adjust tempo based on recent active apical input only :param tempoFactor: scaling signal to MC clock from last sequence item :return: adjusted scaling signal """ if self.apicalIntersect.any(): tempoFactor = tempoFactor * 0.5 else: tempoFactor = tempoFactor * 2 return tempoFactor
python
def tempoAdjust1(self, tempoFactor): """ Adjust tempo based on recent active apical input only :param tempoFactor: scaling signal to MC clock from last sequence item :return: adjusted scaling signal """ if self.apicalIntersect.any(): tempoFactor = tempoFactor * 0.5 else: tempoFactor = tempoFactor * 2 return tempoFactor
[ "def", "tempoAdjust1", "(", "self", ",", "tempoFactor", ")", ":", "if", "self", ".", "apicalIntersect", ".", "any", "(", ")", ":", "tempoFactor", "=", "tempoFactor", "*", "0.5", "else", ":", "tempoFactor", "=", "tempoFactor", "*", "2", "return", "tempoFact...
Adjust tempo based on recent active apical input only :param tempoFactor: scaling signal to MC clock from last sequence item :return: adjusted scaling signal
[ "Adjust", "tempo", "based", "on", "recent", "active", "apical", "input", "only" ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/specific_timing/timing_adtm.py#L259-L273
train
198,858
numenta/htmresearch
htmresearch/frameworks/specific_timing/timing_adtm.py
TimingADTM.tempoAdjust2
def tempoAdjust2(self, tempoFactor): """ Adjust tempo by aggregating active basal cell votes for pre vs. post :param tempoFactor: scaling signal to MC clock from last sequence item :return: adjusted scaling signal """ late_votes = (len(self.adtm.getNextBasalPredictedCells()) - len(self.apicalIntersect)) * -1 early_votes = len(self.apicalIntersect) votes = late_votes + early_votes print('vote tally', votes) if votes > 0: tempoFactor = tempoFactor * 0.5 print 'speed up' elif votes < 0: tempoFactor = tempoFactor * 2 print 'slow down' elif votes == 0: print 'pick randomly' if random.random() > 0.5: tempoFactor = tempoFactor * 0.5 print 'random pick: speed up' else: tempoFactor = tempoFactor * 2 print 'random pick: slow down' return tempoFactor
python
def tempoAdjust2(self, tempoFactor): """ Adjust tempo by aggregating active basal cell votes for pre vs. post :param tempoFactor: scaling signal to MC clock from last sequence item :return: adjusted scaling signal """ late_votes = (len(self.adtm.getNextBasalPredictedCells()) - len(self.apicalIntersect)) * -1 early_votes = len(self.apicalIntersect) votes = late_votes + early_votes print('vote tally', votes) if votes > 0: tempoFactor = tempoFactor * 0.5 print 'speed up' elif votes < 0: tempoFactor = tempoFactor * 2 print 'slow down' elif votes == 0: print 'pick randomly' if random.random() > 0.5: tempoFactor = tempoFactor * 0.5 print 'random pick: speed up' else: tempoFactor = tempoFactor * 2 print 'random pick: slow down' return tempoFactor
[ "def", "tempoAdjust2", "(", "self", ",", "tempoFactor", ")", ":", "late_votes", "=", "(", "len", "(", "self", ".", "adtm", ".", "getNextBasalPredictedCells", "(", ")", ")", "-", "len", "(", "self", ".", "apicalIntersect", ")", ")", "*", "-", "1", "earl...
Adjust tempo by aggregating active basal cell votes for pre vs. post :param tempoFactor: scaling signal to MC clock from last sequence item :return: adjusted scaling signal
[ "Adjust", "tempo", "by", "aggregating", "active", "basal", "cell", "votes", "for", "pre", "vs", ".", "post" ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/specific_timing/timing_adtm.py#L276-L306
train
198,859
numenta/htmresearch
htmresearch/algorithms/column_pooler.py
_countWhereGreaterEqualInRows
def _countWhereGreaterEqualInRows(sparseMatrix, rows, threshold): """ Like countWhereGreaterOrEqual, but for an arbitrary selection of rows, and without any column filtering. """ return sum(sparseMatrix.countWhereGreaterOrEqual(row, row+1, 0, sparseMatrix.nCols(), threshold) for row in rows)
python
def _countWhereGreaterEqualInRows(sparseMatrix, rows, threshold): """ Like countWhereGreaterOrEqual, but for an arbitrary selection of rows, and without any column filtering. """ return sum(sparseMatrix.countWhereGreaterOrEqual(row, row+1, 0, sparseMatrix.nCols(), threshold) for row in rows)
[ "def", "_countWhereGreaterEqualInRows", "(", "sparseMatrix", ",", "rows", ",", "threshold", ")", ":", "return", "sum", "(", "sparseMatrix", ".", "countWhereGreaterOrEqual", "(", "row", ",", "row", "+", "1", ",", "0", ",", "sparseMatrix", ".", "nCols", "(", "...
Like countWhereGreaterOrEqual, but for an arbitrary selection of rows, and without any column filtering.
[ "Like", "countWhereGreaterOrEqual", "but", "for", "an", "arbitrary", "selection", "of", "rows", "and", "without", "any", "column", "filtering", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/column_pooler.py#L672-L680
train
198,860
numenta/htmresearch
htmresearch/algorithms/column_pooler.py
ColumnPooler.compute
def compute(self, feedforwardInput=(), lateralInputs=(), feedforwardGrowthCandidates=None, learn=True, predictedInput = None,): """ Runs one time step of the column pooler algorithm. @param feedforwardInput (sequence) Sorted indices of active feedforward input bits @param lateralInputs (list of sequences) For each lateral layer, a list of sorted indices of active lateral input bits @param feedforwardGrowthCandidates (sequence or None) Sorted indices of feedforward input bits that active cells may grow new synapses to. If None, the entire feedforwardInput is used. @param learn (bool) If True, we are learning a new object @param predictedInput (sequence) Sorted indices of predicted cells in the TM layer. """ if feedforwardGrowthCandidates is None: feedforwardGrowthCandidates = feedforwardInput # inference step if not learn: self._computeInferenceMode(feedforwardInput, lateralInputs) # learning step elif not self.onlineLearning: self._computeLearningMode(feedforwardInput, lateralInputs, feedforwardGrowthCandidates) # online learning step else: if (predictedInput is not None and len(predictedInput) > self.predictedInhibitionThreshold): predictedActiveInput = numpy.intersect1d(feedforwardInput, predictedInput) predictedGrowthCandidates = numpy.intersect1d( feedforwardGrowthCandidates, predictedInput) self._computeInferenceMode(predictedActiveInput, lateralInputs) self._computeLearningMode(predictedActiveInput, lateralInputs, feedforwardGrowthCandidates) elif not self.minSdrSize <= len(self.activeCells) <= self.maxSdrSize: # If the pooler doesn't have a single representation, try to infer one, # before actually attempting to learn. self._computeInferenceMode(feedforwardInput, lateralInputs) self._computeLearningMode(feedforwardInput, lateralInputs, feedforwardGrowthCandidates) else: # If there isn't predicted input and we have a single SDR, # we are extending that representation and should just learn. self._computeLearningMode(feedforwardInput, lateralInputs, feedforwardGrowthCandidates)
python
def compute(self, feedforwardInput=(), lateralInputs=(), feedforwardGrowthCandidates=None, learn=True, predictedInput = None,): """ Runs one time step of the column pooler algorithm. @param feedforwardInput (sequence) Sorted indices of active feedforward input bits @param lateralInputs (list of sequences) For each lateral layer, a list of sorted indices of active lateral input bits @param feedforwardGrowthCandidates (sequence or None) Sorted indices of feedforward input bits that active cells may grow new synapses to. If None, the entire feedforwardInput is used. @param learn (bool) If True, we are learning a new object @param predictedInput (sequence) Sorted indices of predicted cells in the TM layer. """ if feedforwardGrowthCandidates is None: feedforwardGrowthCandidates = feedforwardInput # inference step if not learn: self._computeInferenceMode(feedforwardInput, lateralInputs) # learning step elif not self.onlineLearning: self._computeLearningMode(feedforwardInput, lateralInputs, feedforwardGrowthCandidates) # online learning step else: if (predictedInput is not None and len(predictedInput) > self.predictedInhibitionThreshold): predictedActiveInput = numpy.intersect1d(feedforwardInput, predictedInput) predictedGrowthCandidates = numpy.intersect1d( feedforwardGrowthCandidates, predictedInput) self._computeInferenceMode(predictedActiveInput, lateralInputs) self._computeLearningMode(predictedActiveInput, lateralInputs, feedforwardGrowthCandidates) elif not self.minSdrSize <= len(self.activeCells) <= self.maxSdrSize: # If the pooler doesn't have a single representation, try to infer one, # before actually attempting to learn. self._computeInferenceMode(feedforwardInput, lateralInputs) self._computeLearningMode(feedforwardInput, lateralInputs, feedforwardGrowthCandidates) else: # If there isn't predicted input and we have a single SDR, # we are extending that representation and should just learn. self._computeLearningMode(feedforwardInput, lateralInputs, feedforwardGrowthCandidates)
[ "def", "compute", "(", "self", ",", "feedforwardInput", "=", "(", ")", ",", "lateralInputs", "=", "(", ")", ",", "feedforwardGrowthCandidates", "=", "None", ",", "learn", "=", "True", ",", "predictedInput", "=", "None", ",", ")", ":", "if", "feedforwardGro...
Runs one time step of the column pooler algorithm. @param feedforwardInput (sequence) Sorted indices of active feedforward input bits @param lateralInputs (list of sequences) For each lateral layer, a list of sorted indices of active lateral input bits @param feedforwardGrowthCandidates (sequence or None) Sorted indices of feedforward input bits that active cells may grow new synapses to. If None, the entire feedforwardInput is used. @param learn (bool) If True, we are learning a new object @param predictedInput (sequence) Sorted indices of predicted cells in the TM layer.
[ "Runs", "one", "time", "step", "of", "the", "column", "pooler", "algorithm", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/column_pooler.py#L193-L249
train
198,861
numenta/htmresearch
htmresearch/algorithms/column_pooler.py
ColumnPooler.numberOfConnectedProximalSynapses
def numberOfConnectedProximalSynapses(self, cells=None): """ Returns the number of proximal connected synapses on these cells. Parameters: ---------------------------- @param cells (iterable) Indices of the cells. If None return count for all cells. """ if cells is None: cells = xrange(self.numberOfCells()) return _countWhereGreaterEqualInRows(self.proximalPermanences, cells, self.connectedPermanenceProximal)
python
def numberOfConnectedProximalSynapses(self, cells=None): """ Returns the number of proximal connected synapses on these cells. Parameters: ---------------------------- @param cells (iterable) Indices of the cells. If None return count for all cells. """ if cells is None: cells = xrange(self.numberOfCells()) return _countWhereGreaterEqualInRows(self.proximalPermanences, cells, self.connectedPermanenceProximal)
[ "def", "numberOfConnectedProximalSynapses", "(", "self", ",", "cells", "=", "None", ")", ":", "if", "cells", "is", "None", ":", "cells", "=", "xrange", "(", "self", ".", "numberOfCells", "(", ")", ")", "return", "_countWhereGreaterEqualInRows", "(", "self", ...
Returns the number of proximal connected synapses on these cells. Parameters: ---------------------------- @param cells (iterable) Indices of the cells. If None return count for all cells.
[ "Returns", "the", "number", "of", "proximal", "connected", "synapses", "on", "these", "cells", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/column_pooler.py#L455-L468
train
198,862
numenta/htmresearch
htmresearch/algorithms/column_pooler.py
ColumnPooler.numberOfProximalSynapses
def numberOfProximalSynapses(self, cells=None): """ Returns the number of proximal synapses with permanence>0 on these cells. Parameters: ---------------------------- @param cells (iterable) Indices of the cells. If None return count for all cells. """ if cells is None: cells = xrange(self.numberOfCells()) n = 0 for cell in cells: n += self.proximalPermanences.nNonZerosOnRow(cell) return n
python
def numberOfProximalSynapses(self, cells=None): """ Returns the number of proximal synapses with permanence>0 on these cells. Parameters: ---------------------------- @param cells (iterable) Indices of the cells. If None return count for all cells. """ if cells is None: cells = xrange(self.numberOfCells()) n = 0 for cell in cells: n += self.proximalPermanences.nNonZerosOnRow(cell) return n
[ "def", "numberOfProximalSynapses", "(", "self", ",", "cells", "=", "None", ")", ":", "if", "cells", "is", "None", ":", "cells", "=", "xrange", "(", "self", ".", "numberOfCells", "(", ")", ")", "n", "=", "0", "for", "cell", "in", "cells", ":", "n", ...
Returns the number of proximal synapses with permanence>0 on these cells. Parameters: ---------------------------- @param cells (iterable) Indices of the cells. If None return count for all cells.
[ "Returns", "the", "number", "of", "proximal", "synapses", "with", "permanence", ">", "0", "on", "these", "cells", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/column_pooler.py#L471-L486
train
198,863
numenta/htmresearch
htmresearch/algorithms/column_pooler.py
ColumnPooler.numberOfDistalSegments
def numberOfDistalSegments(self, cells=None): """ Returns the total number of distal segments for these cells. A segment "exists" if its row in the matrix has any permanence values > 0. Parameters: ---------------------------- @param cells (iterable) Indices of the cells """ if cells is None: cells = xrange(self.numberOfCells()) n = 0 for cell in cells: if self.internalDistalPermanences.nNonZerosOnRow(cell) > 0: n += 1 for permanences in self.distalPermanences: if permanences.nNonZerosOnRow(cell) > 0: n += 1 return n
python
def numberOfDistalSegments(self, cells=None): """ Returns the total number of distal segments for these cells. A segment "exists" if its row in the matrix has any permanence values > 0. Parameters: ---------------------------- @param cells (iterable) Indices of the cells """ if cells is None: cells = xrange(self.numberOfCells()) n = 0 for cell in cells: if self.internalDistalPermanences.nNonZerosOnRow(cell) > 0: n += 1 for permanences in self.distalPermanences: if permanences.nNonZerosOnRow(cell) > 0: n += 1 return n
[ "def", "numberOfDistalSegments", "(", "self", ",", "cells", "=", "None", ")", ":", "if", "cells", "is", "None", ":", "cells", "=", "xrange", "(", "self", ".", "numberOfCells", "(", ")", ")", "n", "=", "0", "for", "cell", "in", "cells", ":", "if", "...
Returns the total number of distal segments for these cells. A segment "exists" if its row in the matrix has any permanence values > 0. Parameters: ---------------------------- @param cells (iterable) Indices of the cells
[ "Returns", "the", "total", "number", "of", "distal", "segments", "for", "these", "cells", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/column_pooler.py#L489-L513
train
198,864
numenta/htmresearch
htmresearch/algorithms/column_pooler.py
ColumnPooler.numberOfConnectedDistalSynapses
def numberOfConnectedDistalSynapses(self, cells=None): """ Returns the number of connected distal synapses on these cells. Parameters: ---------------------------- @param cells (iterable) Indices of the cells. If None return count for all cells. """ if cells is None: cells = xrange(self.numberOfCells()) n = _countWhereGreaterEqualInRows(self.internalDistalPermanences, cells, self.connectedPermanenceDistal) for permanences in self.distalPermanences: n += _countWhereGreaterEqualInRows(permanences, cells, self.connectedPermanenceDistal) return n
python
def numberOfConnectedDistalSynapses(self, cells=None): """ Returns the number of connected distal synapses on these cells. Parameters: ---------------------------- @param cells (iterable) Indices of the cells. If None return count for all cells. """ if cells is None: cells = xrange(self.numberOfCells()) n = _countWhereGreaterEqualInRows(self.internalDistalPermanences, cells, self.connectedPermanenceDistal) for permanences in self.distalPermanences: n += _countWhereGreaterEqualInRows(permanences, cells, self.connectedPermanenceDistal) return n
[ "def", "numberOfConnectedDistalSynapses", "(", "self", ",", "cells", "=", "None", ")", ":", "if", "cells", "is", "None", ":", "cells", "=", "xrange", "(", "self", ".", "numberOfCells", "(", ")", ")", "n", "=", "_countWhereGreaterEqualInRows", "(", "self", ...
Returns the number of connected distal synapses on these cells. Parameters: ---------------------------- @param cells (iterable) Indices of the cells. If None return count for all cells.
[ "Returns", "the", "number", "of", "connected", "distal", "synapses", "on", "these", "cells", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/column_pooler.py#L516-L535
train
198,865
numenta/htmresearch
htmresearch/algorithms/column_pooler.py
ColumnPooler._learn
def _learn(# mutated args permanences, rng, # activity activeCells, activeInput, growthCandidateInput, # configuration sampleSize, initialPermanence, permanenceIncrement, permanenceDecrement, connectedPermanence): """ For each active cell, reinforce active synapses, punish inactive synapses, and grow new synapses to a subset of the active input bits that the cell isn't already connected to. Parameters: ---------------------------- @param permanences (SparseMatrix) Matrix of permanences, with cells as rows and inputs as columns @param rng (Random) Random number generator @param activeCells (sorted sequence) Sorted list of the cells that are learning @param activeInput (sorted sequence) Sorted list of active bits in the input @param growthCandidateInput (sorted sequence) Sorted list of active bits in the input that the activeCells may grow new synapses to For remaining parameters, see the __init__ docstring. """ permanences.incrementNonZerosOnOuter( activeCells, activeInput, permanenceIncrement) permanences.incrementNonZerosOnRowsExcludingCols( activeCells, activeInput, -permanenceDecrement) permanences.clipRowsBelowAndAbove( activeCells, 0.0, 1.0) if sampleSize == -1: permanences.setZerosOnOuter( activeCells, activeInput, initialPermanence) else: existingSynapseCounts = permanences.nNonZerosPerRowOnCols( activeCells, activeInput) maxNewByCell = numpy.empty(len(activeCells), dtype="int32") numpy.subtract(sampleSize, existingSynapseCounts, out=maxNewByCell) permanences.setRandomZerosOnOuter( activeCells, growthCandidateInput, maxNewByCell, initialPermanence, rng)
python
def _learn(# mutated args permanences, rng, # activity activeCells, activeInput, growthCandidateInput, # configuration sampleSize, initialPermanence, permanenceIncrement, permanenceDecrement, connectedPermanence): """ For each active cell, reinforce active synapses, punish inactive synapses, and grow new synapses to a subset of the active input bits that the cell isn't already connected to. Parameters: ---------------------------- @param permanences (SparseMatrix) Matrix of permanences, with cells as rows and inputs as columns @param rng (Random) Random number generator @param activeCells (sorted sequence) Sorted list of the cells that are learning @param activeInput (sorted sequence) Sorted list of active bits in the input @param growthCandidateInput (sorted sequence) Sorted list of active bits in the input that the activeCells may grow new synapses to For remaining parameters, see the __init__ docstring. """ permanences.incrementNonZerosOnOuter( activeCells, activeInput, permanenceIncrement) permanences.incrementNonZerosOnRowsExcludingCols( activeCells, activeInput, -permanenceDecrement) permanences.clipRowsBelowAndAbove( activeCells, 0.0, 1.0) if sampleSize == -1: permanences.setZerosOnOuter( activeCells, activeInput, initialPermanence) else: existingSynapseCounts = permanences.nNonZerosPerRowOnCols( activeCells, activeInput) maxNewByCell = numpy.empty(len(activeCells), dtype="int32") numpy.subtract(sampleSize, existingSynapseCounts, out=maxNewByCell) permanences.setRandomZerosOnOuter( activeCells, growthCandidateInput, maxNewByCell, initialPermanence, rng)
[ "def", "_learn", "(", "# mutated args", "permanences", ",", "rng", ",", "# activity", "activeCells", ",", "activeInput", ",", "growthCandidateInput", ",", "# configuration", "sampleSize", ",", "initialPermanence", ",", "permanenceIncrement", ",", "permanenceDecrement", ...
For each active cell, reinforce active synapses, punish inactive synapses, and grow new synapses to a subset of the active input bits that the cell isn't already connected to. Parameters: ---------------------------- @param permanences (SparseMatrix) Matrix of permanences, with cells as rows and inputs as columns @param rng (Random) Random number generator @param activeCells (sorted sequence) Sorted list of the cells that are learning @param activeInput (sorted sequence) Sorted list of active bits in the input @param growthCandidateInput (sorted sequence) Sorted list of active bits in the input that the activeCells may grow new synapses to For remaining parameters, see the __init__ docstring.
[ "For", "each", "active", "cell", "reinforce", "active", "synapses", "punish", "inactive", "synapses", "and", "grow", "new", "synapses", "to", "a", "subset", "of", "the", "active", "input", "bits", "that", "the", "cell", "isn", "t", "already", "connected", "t...
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/column_pooler.py#L584-L636
train
198,866
numenta/htmresearch
projects/location_layer/memorize_math_pooled_tm/run.py
runExperiment
def runExperiment(n, w, threshold, cellsPerColumn, folder, numTrials=5, cleverTMSDRs=False): """ Run a PoolOfPairsLocation1DExperiment various union sizes. """ if not os.path.exists(folder): try: os.makedirs(folder) except OSError: # Multiple parallel tasks might create the folder. That's fine. pass filename = "{}/n_{}_w_{}_threshold_{}_cellsPerColumn_{}.json".format( folder, n, w, threshold, cellsPerColumn) if len(glob.glob(filename)) == 0: print("Starting: {}/n_{}_w_{}_threshold_{}_cellsPerColumn_{}".format( folder, n, w, threshold, cellsPerColumn)) result = defaultdict(list) for _ in xrange(numTrials): exp = PoolOfPairsLocation1DExperiment(**{ "numMinicolumns": n, "numActiveMinicolumns": w, "poolingThreshold": threshold, "cellsPerColumn": cellsPerColumn, "minicolumnSDRs": generateMinicolumnSDRs(n=n, w=w, threshold=threshold), }) if cleverTMSDRs: exp.trainWithSpecificPairSDRs(carefullyCollideContexts( numContexts=25, numCells=cellsPerColumn, numMinicolumns = n)) else: exp.train() for unionSize in [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25]: additionalSDRCounts = exp.testInferenceOnUnions(unionSize) result[unionSize] += additionalSDRCounts with open(filename, "w") as fOut: json.dump(sorted(result.items(), key=lambda x: x[0]), fOut) print("Wrote:", filename)
python
def runExperiment(n, w, threshold, cellsPerColumn, folder, numTrials=5, cleverTMSDRs=False): """ Run a PoolOfPairsLocation1DExperiment various union sizes. """ if not os.path.exists(folder): try: os.makedirs(folder) except OSError: # Multiple parallel tasks might create the folder. That's fine. pass filename = "{}/n_{}_w_{}_threshold_{}_cellsPerColumn_{}.json".format( folder, n, w, threshold, cellsPerColumn) if len(glob.glob(filename)) == 0: print("Starting: {}/n_{}_w_{}_threshold_{}_cellsPerColumn_{}".format( folder, n, w, threshold, cellsPerColumn)) result = defaultdict(list) for _ in xrange(numTrials): exp = PoolOfPairsLocation1DExperiment(**{ "numMinicolumns": n, "numActiveMinicolumns": w, "poolingThreshold": threshold, "cellsPerColumn": cellsPerColumn, "minicolumnSDRs": generateMinicolumnSDRs(n=n, w=w, threshold=threshold), }) if cleverTMSDRs: exp.trainWithSpecificPairSDRs(carefullyCollideContexts( numContexts=25, numCells=cellsPerColumn, numMinicolumns = n)) else: exp.train() for unionSize in [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25]: additionalSDRCounts = exp.testInferenceOnUnions(unionSize) result[unionSize] += additionalSDRCounts with open(filename, "w") as fOut: json.dump(sorted(result.items(), key=lambda x: x[0]), fOut) print("Wrote:", filename)
[ "def", "runExperiment", "(", "n", ",", "w", ",", "threshold", ",", "cellsPerColumn", ",", "folder", ",", "numTrials", "=", "5", ",", "cleverTMSDRs", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "folder", ")", ":", "try"...
Run a PoolOfPairsLocation1DExperiment various union sizes.
[ "Run", "a", "PoolOfPairsLocation1DExperiment", "various", "union", "sizes", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/location_layer/memorize_math_pooled_tm/run.py#L291-L334
train
198,867
numenta/htmresearch
projects/location_layer/memorize_math_pooled_tm/run.py
PoolOfPairsLocation1DExperiment.train
def train(self): """ Train the pair layer and pooling layer. """ for iDriving, cDriving in enumerate(self.drivingOperandSDRs): minicolumnSDR = self.minicolumnSDRs[iDriving] self.pairLayerProximalConnections.associate(minicolumnSDR, cDriving) for iContext, cContext in enumerate(self.contextOperandSDRs): iResult = (iContext + iDriving) % self.numLocations cResult = self.resultSDRs[iResult] self.pairLayer.compute(minicolumnSDR, basalInput=cContext) cPair = self.pairLayer.getWinnerCells() self.poolingLayer.associate(cResult, cPair)
python
def train(self): """ Train the pair layer and pooling layer. """ for iDriving, cDriving in enumerate(self.drivingOperandSDRs): minicolumnSDR = self.minicolumnSDRs[iDriving] self.pairLayerProximalConnections.associate(minicolumnSDR, cDriving) for iContext, cContext in enumerate(self.contextOperandSDRs): iResult = (iContext + iDriving) % self.numLocations cResult = self.resultSDRs[iResult] self.pairLayer.compute(minicolumnSDR, basalInput=cContext) cPair = self.pairLayer.getWinnerCells() self.poolingLayer.associate(cResult, cPair)
[ "def", "train", "(", "self", ")", ":", "for", "iDriving", ",", "cDriving", "in", "enumerate", "(", "self", ".", "drivingOperandSDRs", ")", ":", "minicolumnSDR", "=", "self", ".", "minicolumnSDRs", "[", "iDriving", "]", "self", ".", "pairLayerProximalConnection...
Train the pair layer and pooling layer.
[ "Train", "the", "pair", "layer", "and", "pooling", "layer", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/location_layer/memorize_math_pooled_tm/run.py#L196-L208
train
198,868
numenta/htmresearch
projects/sdr_paper/poirazi_neuron_model/run_noise_experiment.py
run_noise_experiment
def run_noise_experiment(num_neurons = 1, a = 128, dim = 6000, test_noise_levels = range(15, 100, 5), num_samples = 500, num_dendrites = 500, dendrite_length = 30, theta = 8, num_trials = 100): """ Tests the impact of noise on a neuron, using an HTM approach to a P&M model of a neuron. Nonlinearity is a simple threshold at theta, as in the original version of this experiment, and each dendrite is bound by the initialization to a single pattern. Only one neuron is used, unlike in the P&M classification experiment, and a successful identification is simply defined as at least one dendrite having theta active synapses. Training is done via HTM-style initialization. In the event that the init fails to produce an error rate of 0 without noise (which anecdotally never occurs), we simple reinitialize. Results are saved to the file noise_FN_{theta}.txt. This corresponds to the false negative vs. noise level figure in the paper. To generate the results shown, we used theta = 8, theta = 12 and theta = 16, with noise levels in range(15, 85, 5), 500 dendrites and 30 synapses per dendrite. We generated 500 sample SDRs, one per dendrite, and ran 100 trials at each noise level. Each SDR had a = 128, dim = 6000. """ nonlinearity = threshold_nonlinearity(theta) for noise in test_noise_levels: fps = [] fns = [] for trial in range(num_trials): successful_initialization = False while not successful_initialization: neuron = Neuron(size = dendrite_length*num_dendrites, num_dendrites = num_dendrites, dendrite_length = dendrite_length, dim = dim, nonlinearity = nonlinearity) data = generate_evenly_distributed_data_sparse(dim = dim, num_active = a, num_samples = num_samples) labels = [1 for i in range(num_samples)] neuron.HTM_style_initialize_on_data(data, labels) error, fp, fn = get_error(data, labels, [neuron]) print "Initialization error is {}, with {} false positives and {} false negatives".format(error, fp, fn) if error == 0: successful_initialization = True else: print "Repeating to get a successful initialization" apply_noise(data, noise) error, fp, fn = get_error(data, labels, [neuron]) fps.append(fp) fns.append(fn) print "Error at noise {} is {}, with {} false positives and {} false negatives".format(noise, error, fp, fn) with open("noise_FN_{}.txt".format(theta), "a") as f: f.write(str(noise) + ", " + str(numpy.sum(fns)) + ", " + str(num_trials*num_samples) + "\n")
python
def run_noise_experiment(num_neurons = 1, a = 128, dim = 6000, test_noise_levels = range(15, 100, 5), num_samples = 500, num_dendrites = 500, dendrite_length = 30, theta = 8, num_trials = 100): """ Tests the impact of noise on a neuron, using an HTM approach to a P&M model of a neuron. Nonlinearity is a simple threshold at theta, as in the original version of this experiment, and each dendrite is bound by the initialization to a single pattern. Only one neuron is used, unlike in the P&M classification experiment, and a successful identification is simply defined as at least one dendrite having theta active synapses. Training is done via HTM-style initialization. In the event that the init fails to produce an error rate of 0 without noise (which anecdotally never occurs), we simple reinitialize. Results are saved to the file noise_FN_{theta}.txt. This corresponds to the false negative vs. noise level figure in the paper. To generate the results shown, we used theta = 8, theta = 12 and theta = 16, with noise levels in range(15, 85, 5), 500 dendrites and 30 synapses per dendrite. We generated 500 sample SDRs, one per dendrite, and ran 100 trials at each noise level. Each SDR had a = 128, dim = 6000. """ nonlinearity = threshold_nonlinearity(theta) for noise in test_noise_levels: fps = [] fns = [] for trial in range(num_trials): successful_initialization = False while not successful_initialization: neuron = Neuron(size = dendrite_length*num_dendrites, num_dendrites = num_dendrites, dendrite_length = dendrite_length, dim = dim, nonlinearity = nonlinearity) data = generate_evenly_distributed_data_sparse(dim = dim, num_active = a, num_samples = num_samples) labels = [1 for i in range(num_samples)] neuron.HTM_style_initialize_on_data(data, labels) error, fp, fn = get_error(data, labels, [neuron]) print "Initialization error is {}, with {} false positives and {} false negatives".format(error, fp, fn) if error == 0: successful_initialization = True else: print "Repeating to get a successful initialization" apply_noise(data, noise) error, fp, fn = get_error(data, labels, [neuron]) fps.append(fp) fns.append(fn) print "Error at noise {} is {}, with {} false positives and {} false negatives".format(noise, error, fp, fn) with open("noise_FN_{}.txt".format(theta), "a") as f: f.write(str(noise) + ", " + str(numpy.sum(fns)) + ", " + str(num_trials*num_samples) + "\n")
[ "def", "run_noise_experiment", "(", "num_neurons", "=", "1", ",", "a", "=", "128", ",", "dim", "=", "6000", ",", "test_noise_levels", "=", "range", "(", "15", ",", "100", ",", "5", ")", ",", "num_samples", "=", "500", ",", "num_dendrites", "=", "500", ...
Tests the impact of noise on a neuron, using an HTM approach to a P&M model of a neuron. Nonlinearity is a simple threshold at theta, as in the original version of this experiment, and each dendrite is bound by the initialization to a single pattern. Only one neuron is used, unlike in the P&M classification experiment, and a successful identification is simply defined as at least one dendrite having theta active synapses. Training is done via HTM-style initialization. In the event that the init fails to produce an error rate of 0 without noise (which anecdotally never occurs), we simple reinitialize. Results are saved to the file noise_FN_{theta}.txt. This corresponds to the false negative vs. noise level figure in the paper. To generate the results shown, we used theta = 8, theta = 12 and theta = 16, with noise levels in range(15, 85, 5), 500 dendrites and 30 synapses per dendrite. We generated 500 sample SDRs, one per dendrite, and ran 100 trials at each noise level. Each SDR had a = 128, dim = 6000.
[ "Tests", "the", "impact", "of", "noise", "on", "a", "neuron", "using", "an", "HTM", "approach", "to", "a", "P&M", "model", "of", "a", "neuron", ".", "Nonlinearity", "is", "a", "simple", "threshold", "at", "theta", "as", "in", "the", "original", "version"...
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sdr_paper/poirazi_neuron_model/run_noise_experiment.py#L31-L91
train
198,869
numenta/htmresearch
htmresearch/frameworks/pytorch/cifar_experiment.py
CIFARExperiment.reset
def reset(self, params, repetition): """Called at the beginning of each experiment and each repetition""" pprint.pprint(params) self.initialize(params, repetition) # Load CIFAR dataset dataDir = params.get('dataDir', 'data') self.transform_train = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), ]) self.trainset = datasets.CIFAR10(root=dataDir, train=True, download=True, transform=self.transform_train) self.createModel(params, repetition) print("Torch reports", torch.cuda.device_count(), "GPUs available") if torch.cuda.device_count() > 1: self.model = torch.nn.DataParallel(self.model) self.model.to(self.device) self.optimizer = self.createOptimizer(self.model) self.lr_scheduler = self.createLearningRateScheduler(self.optimizer) self.test_loaders = self.createTestLoaders(self.noise_values)
python
def reset(self, params, repetition): """Called at the beginning of each experiment and each repetition""" pprint.pprint(params) self.initialize(params, repetition) # Load CIFAR dataset dataDir = params.get('dataDir', 'data') self.transform_train = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), ]) self.trainset = datasets.CIFAR10(root=dataDir, train=True, download=True, transform=self.transform_train) self.createModel(params, repetition) print("Torch reports", torch.cuda.device_count(), "GPUs available") if torch.cuda.device_count() > 1: self.model = torch.nn.DataParallel(self.model) self.model.to(self.device) self.optimizer = self.createOptimizer(self.model) self.lr_scheduler = self.createLearningRateScheduler(self.optimizer) self.test_loaders = self.createTestLoaders(self.noise_values)
[ "def", "reset", "(", "self", ",", "params", ",", "repetition", ")", ":", "pprint", ".", "pprint", "(", "params", ")", "self", ".", "initialize", "(", "params", ",", "repetition", ")", "# Load CIFAR dataset", "dataDir", "=", "params", ".", "get", "(", "'d...
Called at the beginning of each experiment and each repetition
[ "Called", "at", "the", "beginning", "of", "each", "experiment", "and", "each", "repetition" ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/pytorch/cifar_experiment.py#L66-L94
train
198,870
numenta/htmresearch
htmresearch/algorithms/faulty_spatial_pooler.py
FaultySpatialPooler.killCellRegion
def killCellRegion(self, centerColumn, radius): """ Kill cells around a centerColumn, within radius """ self.deadCols = topology.wrappingNeighborhood(centerColumn, radius, self._columnDimensions) self.deadColumnInputSpan = self.getConnectedSpan(self.deadCols) self.removeDeadColumns()
python
def killCellRegion(self, centerColumn, radius): """ Kill cells around a centerColumn, within radius """ self.deadCols = topology.wrappingNeighborhood(centerColumn, radius, self._columnDimensions) self.deadColumnInputSpan = self.getConnectedSpan(self.deadCols) self.removeDeadColumns()
[ "def", "killCellRegion", "(", "self", ",", "centerColumn", ",", "radius", ")", ":", "self", ".", "deadCols", "=", "topology", ".", "wrappingNeighborhood", "(", "centerColumn", ",", "radius", ",", "self", ".", "_columnDimensions", ")", "self", ".", "deadColumnI...
Kill cells around a centerColumn, within radius
[ "Kill", "cells", "around", "a", "centerColumn", "within", "radius" ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/faulty_spatial_pooler.py#L78-L86
train
198,871
numenta/htmresearch
htmresearch/algorithms/faulty_spatial_pooler.py
FaultySpatialPooler.compute
def compute(self, inputVector, learn, activeArray): """ This is the primary public method of the SpatialPooler class. This function takes a input vector and outputs the indices of the active columns. If 'learn' is set to True, this method also updates the permanences of the columns. @param inputVector: A numpy array of 0's and 1's that comprises the input to the spatial pooler. The array will be treated as a one dimensional array, therefore the dimensions of the array do not have to match the exact dimensions specified in the class constructor. In fact, even a list would suffice. The number of input bits in the vector must, however, match the number of bits specified by the call to the constructor. Therefore there must be a '0' or '1' in the array for every input bit. @param learn: A boolean value indicating whether learning should be performed. Learning entails updating the permanence values of the synapses, and hence modifying the 'state' of the model. Setting learning to 'off' freezes the SP and has many uses. For example, you might want to feed in various inputs and examine the resulting SDR's. @param activeArray: An array whose size is equal to the number of columns. Before the function returns this array will be populated with 1's at the indices of the active columns, and 0's everywhere else. """ if not isinstance(inputVector, numpy.ndarray): raise TypeError("Input vector must be a numpy array, not %s" % str(type(inputVector))) if inputVector.size != self._numInputs: raise ValueError( "Input vector dimensions don't match. Expecting %s but got %s" % ( inputVector.size, self._numInputs)) self._updateBookeepingVars(learn) inputVector = numpy.array(inputVector, dtype=realDType) inputVector.reshape(-1) self._overlaps = self._calculateOverlap(inputVector) # self._overlaps[self.deadCols] = 0 # Apply boosting when learning is on if learn: self._boostedOverlaps = self._boostFactors * self._overlaps else: self._boostedOverlaps = self._overlaps # Apply inhibition to determine the winning columns activeColumns = self._inhibitColumns(self._boostedOverlaps) if learn: self._adaptSynapses(inputVector, activeColumns) self._updateDutyCycles(self._overlaps, activeColumns) self._bumpUpWeakColumns() self._updateTargetActivityDensity() self._updateBoostFactors() if self._isUpdateRound(): self._updateInhibitionRadius() self._updateMinDutyCycles() # self.growRandomSynapses() activeArray.fill(0) activeArray[activeColumns] = 1
python
def compute(self, inputVector, learn, activeArray): """ This is the primary public method of the SpatialPooler class. This function takes a input vector and outputs the indices of the active columns. If 'learn' is set to True, this method also updates the permanences of the columns. @param inputVector: A numpy array of 0's and 1's that comprises the input to the spatial pooler. The array will be treated as a one dimensional array, therefore the dimensions of the array do not have to match the exact dimensions specified in the class constructor. In fact, even a list would suffice. The number of input bits in the vector must, however, match the number of bits specified by the call to the constructor. Therefore there must be a '0' or '1' in the array for every input bit. @param learn: A boolean value indicating whether learning should be performed. Learning entails updating the permanence values of the synapses, and hence modifying the 'state' of the model. Setting learning to 'off' freezes the SP and has many uses. For example, you might want to feed in various inputs and examine the resulting SDR's. @param activeArray: An array whose size is equal to the number of columns. Before the function returns this array will be populated with 1's at the indices of the active columns, and 0's everywhere else. """ if not isinstance(inputVector, numpy.ndarray): raise TypeError("Input vector must be a numpy array, not %s" % str(type(inputVector))) if inputVector.size != self._numInputs: raise ValueError( "Input vector dimensions don't match. Expecting %s but got %s" % ( inputVector.size, self._numInputs)) self._updateBookeepingVars(learn) inputVector = numpy.array(inputVector, dtype=realDType) inputVector.reshape(-1) self._overlaps = self._calculateOverlap(inputVector) # self._overlaps[self.deadCols] = 0 # Apply boosting when learning is on if learn: self._boostedOverlaps = self._boostFactors * self._overlaps else: self._boostedOverlaps = self._overlaps # Apply inhibition to determine the winning columns activeColumns = self._inhibitColumns(self._boostedOverlaps) if learn: self._adaptSynapses(inputVector, activeColumns) self._updateDutyCycles(self._overlaps, activeColumns) self._bumpUpWeakColumns() self._updateTargetActivityDensity() self._updateBoostFactors() if self._isUpdateRound(): self._updateInhibitionRadius() self._updateMinDutyCycles() # self.growRandomSynapses() activeArray.fill(0) activeArray[activeColumns] = 1
[ "def", "compute", "(", "self", ",", "inputVector", ",", "learn", ",", "activeArray", ")", ":", "if", "not", "isinstance", "(", "inputVector", ",", "numpy", ".", "ndarray", ")", ":", "raise", "TypeError", "(", "\"Input vector must be a numpy array, not %s\"", "%"...
This is the primary public method of the SpatialPooler class. This function takes a input vector and outputs the indices of the active columns. If 'learn' is set to True, this method also updates the permanences of the columns. @param inputVector: A numpy array of 0's and 1's that comprises the input to the spatial pooler. The array will be treated as a one dimensional array, therefore the dimensions of the array do not have to match the exact dimensions specified in the class constructor. In fact, even a list would suffice. The number of input bits in the vector must, however, match the number of bits specified by the call to the constructor. Therefore there must be a '0' or '1' in the array for every input bit. @param learn: A boolean value indicating whether learning should be performed. Learning entails updating the permanence values of the synapses, and hence modifying the 'state' of the model. Setting learning to 'off' freezes the SP and has many uses. For example, you might want to feed in various inputs and examine the resulting SDR's. @param activeArray: An array whose size is equal to the number of columns. Before the function returns this array will be populated with 1's at the indices of the active columns, and 0's everywhere else.
[ "This", "is", "the", "primary", "public", "method", "of", "the", "SpatialPooler", "class", ".", "This", "function", "takes", "a", "input", "vector", "and", "outputs", "the", "indices", "of", "the", "active", "columns", ".", "If", "learn", "is", "set", "to"...
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/faulty_spatial_pooler.py#L117-L178
train
198,872
numenta/htmresearch
htmresearch/regions/ColumnPoolerRegion.py
getConstructorArguments
def getConstructorArguments(): """ Return constructor argument associated with ColumnPooler. @return defaults (list) a list of args and default values for each argument """ argspec = inspect.getargspec(ColumnPooler.__init__) return argspec.args[1:], argspec.defaults
python
def getConstructorArguments(): """ Return constructor argument associated with ColumnPooler. @return defaults (list) a list of args and default values for each argument """ argspec = inspect.getargspec(ColumnPooler.__init__) return argspec.args[1:], argspec.defaults
[ "def", "getConstructorArguments", "(", ")", ":", "argspec", "=", "inspect", ".", "getargspec", "(", "ColumnPooler", ".", "__init__", ")", "return", "argspec", ".", "args", "[", "1", ":", "]", ",", "argspec", ".", "defaults" ]
Return constructor argument associated with ColumnPooler. @return defaults (list) a list of args and default values for each argument
[ "Return", "constructor", "argument", "associated", "with", "ColumnPooler", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/regions/ColumnPoolerRegion.py#L30-L36
train
198,873
numenta/htmresearch
htmresearch/regions/ColumnPoolerRegion.py
ColumnPoolerRegion.initialize
def initialize(self): """ Initialize the internal objects. """ if self._pooler is None: params = { "inputWidth": self.inputWidth, "lateralInputWidths": [self.cellCount] * self.numOtherCorticalColumns, "cellCount": self.cellCount, "sdrSize": self.sdrSize, "onlineLearning": self.onlineLearning, "maxSdrSize": self.maxSdrSize, "minSdrSize": self.minSdrSize, "synPermProximalInc": self.synPermProximalInc, "synPermProximalDec": self.synPermProximalDec, "initialProximalPermanence": self.initialProximalPermanence, "minThresholdProximal": self.minThresholdProximal, "sampleSizeProximal": self.sampleSizeProximal, "connectedPermanenceProximal": self.connectedPermanenceProximal, "predictedInhibitionThreshold": self.predictedInhibitionThreshold, "synPermDistalInc": self.synPermDistalInc, "synPermDistalDec": self.synPermDistalDec, "initialDistalPermanence": self.initialDistalPermanence, "activationThresholdDistal": self.activationThresholdDistal, "sampleSizeDistal": self.sampleSizeDistal, "connectedPermanenceDistal": self.connectedPermanenceDistal, "inertiaFactor": self.inertiaFactor, "seed": self.seed, } self._pooler = ColumnPooler(**params)
python
def initialize(self): """ Initialize the internal objects. """ if self._pooler is None: params = { "inputWidth": self.inputWidth, "lateralInputWidths": [self.cellCount] * self.numOtherCorticalColumns, "cellCount": self.cellCount, "sdrSize": self.sdrSize, "onlineLearning": self.onlineLearning, "maxSdrSize": self.maxSdrSize, "minSdrSize": self.minSdrSize, "synPermProximalInc": self.synPermProximalInc, "synPermProximalDec": self.synPermProximalDec, "initialProximalPermanence": self.initialProximalPermanence, "minThresholdProximal": self.minThresholdProximal, "sampleSizeProximal": self.sampleSizeProximal, "connectedPermanenceProximal": self.connectedPermanenceProximal, "predictedInhibitionThreshold": self.predictedInhibitionThreshold, "synPermDistalInc": self.synPermDistalInc, "synPermDistalDec": self.synPermDistalDec, "initialDistalPermanence": self.initialDistalPermanence, "activationThresholdDistal": self.activationThresholdDistal, "sampleSizeDistal": self.sampleSizeDistal, "connectedPermanenceDistal": self.connectedPermanenceDistal, "inertiaFactor": self.inertiaFactor, "seed": self.seed, } self._pooler = ColumnPooler(**params)
[ "def", "initialize", "(", "self", ")", ":", "if", "self", ".", "_pooler", "is", "None", ":", "params", "=", "{", "\"inputWidth\"", ":", "self", ".", "inputWidth", ",", "\"lateralInputWidths\"", ":", "[", "self", ".", "cellCount", "]", "*", "self", ".", ...
Initialize the internal objects.
[ "Initialize", "the", "internal", "objects", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/regions/ColumnPoolerRegion.py#L389-L418
train
198,874
numenta/htmresearch
htmresearch/regions/ColumnPoolerRegion.py
ColumnPoolerRegion.compute
def compute(self, inputs, outputs): """ Run one iteration of compute. Note that if the reset signal is True (1) we assume this iteration represents the *end* of a sequence. The output will contain the representation to this point and any history will then be reset. The output at the next compute will start fresh, presumably with bursting columns. """ # Handle reset first (should be sent with an empty signal) if "resetIn" in inputs: assert len(inputs["resetIn"]) == 1 if inputs["resetIn"][0] != 0: # send empty output self.reset() outputs["feedForwardOutput"][:] = 0 outputs["activeCells"][:] = 0 return feedforwardInput = numpy.asarray(inputs["feedforwardInput"].nonzero()[0], dtype="uint32") if "feedforwardGrowthCandidates" in inputs: feedforwardGrowthCandidates = numpy.asarray( inputs["feedforwardGrowthCandidates"].nonzero()[0], dtype="uint32") else: feedforwardGrowthCandidates = feedforwardInput if "lateralInput" in inputs: lateralInputs = tuple(numpy.asarray(singleInput.nonzero()[0], dtype="uint32") for singleInput in numpy.split(inputs["lateralInput"], self.numOtherCorticalColumns)) else: lateralInputs = () if "predictedInput" in inputs: predictedInput = numpy.asarray( inputs["predictedInput"].nonzero()[0], dtype="uint32") else: predictedInput = None # Send the inputs into the Column Pooler. self._pooler.compute(feedforwardInput, lateralInputs, feedforwardGrowthCandidates, learn=self.learningMode, predictedInput = predictedInput) # Extract the active / predicted cells and put them into binary arrays. outputs["activeCells"][:] = 0 outputs["activeCells"][self._pooler.getActiveCells()] = 1 # Send appropriate output to feedForwardOutput. if self.defaultOutputType == "active": outputs["feedForwardOutput"][:] = outputs["activeCells"] else: raise Exception("Unknown outputType: " + self.defaultOutputType)
python
def compute(self, inputs, outputs): """ Run one iteration of compute. Note that if the reset signal is True (1) we assume this iteration represents the *end* of a sequence. The output will contain the representation to this point and any history will then be reset. The output at the next compute will start fresh, presumably with bursting columns. """ # Handle reset first (should be sent with an empty signal) if "resetIn" in inputs: assert len(inputs["resetIn"]) == 1 if inputs["resetIn"][0] != 0: # send empty output self.reset() outputs["feedForwardOutput"][:] = 0 outputs["activeCells"][:] = 0 return feedforwardInput = numpy.asarray(inputs["feedforwardInput"].nonzero()[0], dtype="uint32") if "feedforwardGrowthCandidates" in inputs: feedforwardGrowthCandidates = numpy.asarray( inputs["feedforwardGrowthCandidates"].nonzero()[0], dtype="uint32") else: feedforwardGrowthCandidates = feedforwardInput if "lateralInput" in inputs: lateralInputs = tuple(numpy.asarray(singleInput.nonzero()[0], dtype="uint32") for singleInput in numpy.split(inputs["lateralInput"], self.numOtherCorticalColumns)) else: lateralInputs = () if "predictedInput" in inputs: predictedInput = numpy.asarray( inputs["predictedInput"].nonzero()[0], dtype="uint32") else: predictedInput = None # Send the inputs into the Column Pooler. self._pooler.compute(feedforwardInput, lateralInputs, feedforwardGrowthCandidates, learn=self.learningMode, predictedInput = predictedInput) # Extract the active / predicted cells and put them into binary arrays. outputs["activeCells"][:] = 0 outputs["activeCells"][self._pooler.getActiveCells()] = 1 # Send appropriate output to feedForwardOutput. if self.defaultOutputType == "active": outputs["feedForwardOutput"][:] = outputs["activeCells"] else: raise Exception("Unknown outputType: " + self.defaultOutputType)
[ "def", "compute", "(", "self", ",", "inputs", ",", "outputs", ")", ":", "# Handle reset first (should be sent with an empty signal)", "if", "\"resetIn\"", "in", "inputs", ":", "assert", "len", "(", "inputs", "[", "\"resetIn\"", "]", ")", "==", "1", "if", "inputs...
Run one iteration of compute. Note that if the reset signal is True (1) we assume this iteration represents the *end* of a sequence. The output will contain the representation to this point and any history will then be reset. The output at the next compute will start fresh, presumably with bursting columns.
[ "Run", "one", "iteration", "of", "compute", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/regions/ColumnPoolerRegion.py#L421-L477
train
198,875
numenta/htmresearch
htmresearch/support/expsuite.py
progress
def progress(params, rep): """ Helper function to calculate the progress made on one experiment. """ name = params['name'] fullpath = os.path.join(params['path'], params['name']) logname = os.path.join(fullpath, '%i.log'%rep) if os.path.exists(logname): logfile = open(logname, 'r') lines = logfile.readlines() logfile.close() return int(100 * len(lines) / params['iterations']) else: return 0
python
def progress(params, rep): """ Helper function to calculate the progress made on one experiment. """ name = params['name'] fullpath = os.path.join(params['path'], params['name']) logname = os.path.join(fullpath, '%i.log'%rep) if os.path.exists(logname): logfile = open(logname, 'r') lines = logfile.readlines() logfile.close() return int(100 * len(lines) / params['iterations']) else: return 0
[ "def", "progress", "(", "params", ",", "rep", ")", ":", "name", "=", "params", "[", "'name'", "]", "fullpath", "=", "os", ".", "path", ".", "join", "(", "params", "[", "'path'", "]", ",", "params", "[", "'name'", "]", ")", "logname", "=", "os", "...
Helper function to calculate the progress made on one experiment.
[ "Helper", "function", "to", "calculate", "the", "progress", "made", "on", "one", "experiment", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/expsuite.py#L31-L42
train
198,876
numenta/htmresearch
htmresearch/support/expsuite.py
convert_param_to_dirname
def convert_param_to_dirname(param): """ Helper function to convert a parameter value to a valid directory name. """ if type(param) == types.StringType: return param else: return re.sub("0+$", '0', '%f'%param)
python
def convert_param_to_dirname(param): """ Helper function to convert a parameter value to a valid directory name. """ if type(param) == types.StringType: return param else: return re.sub("0+$", '0', '%f'%param)
[ "def", "convert_param_to_dirname", "(", "param", ")", ":", "if", "type", "(", "param", ")", "==", "types", ".", "StringType", ":", "return", "param", "else", ":", "return", "re", ".", "sub", "(", "\"0+$\"", ",", "'0'", ",", "'%f'", "%", "param", ")" ]
Helper function to convert a parameter value to a valid directory name.
[ "Helper", "function", "to", "convert", "a", "parameter", "value", "to", "a", "valid", "directory", "name", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/expsuite.py#L44-L49
train
198,877
numenta/htmresearch
htmresearch/support/expsuite.py
PyExperimentSuite.parse_opt
def parse_opt(self): """ parses the command line options for different settings. """ optparser = optparse.OptionParser() optparser.add_option('-c', '--config', action='store', dest='config', type='string', default='experiments.cfg', help="your experiments config file") optparser.add_option('-n', '--numcores', action='store', dest='ncores', type='int', default=cpu_count(), help="number of processes you want to use, default is %i"%cpu_count()) optparser.add_option('-d', '--del', action='store_true', dest='delete', default=False, help="delete experiment folder if it exists") optparser.add_option('-e', '--experiment', action='append', dest='experiments', type='string', help="run only selected experiments, by default run all experiments in config file.") optparser.add_option('-b', '--browse', action='store_true', dest='browse', default=False, help="browse existing experiments.") optparser.add_option('-B', '--Browse', action='store_true', dest='browse_big', default=False, help="browse existing experiments, more verbose than -b") optparser.add_option('-p', '--progress', action='store_true', dest='progress', default=False, help="like browse, but only shows name and progress bar") options, args = optparser.parse_args() self.options = options return options, args
python
def parse_opt(self): """ parses the command line options for different settings. """ optparser = optparse.OptionParser() optparser.add_option('-c', '--config', action='store', dest='config', type='string', default='experiments.cfg', help="your experiments config file") optparser.add_option('-n', '--numcores', action='store', dest='ncores', type='int', default=cpu_count(), help="number of processes you want to use, default is %i"%cpu_count()) optparser.add_option('-d', '--del', action='store_true', dest='delete', default=False, help="delete experiment folder if it exists") optparser.add_option('-e', '--experiment', action='append', dest='experiments', type='string', help="run only selected experiments, by default run all experiments in config file.") optparser.add_option('-b', '--browse', action='store_true', dest='browse', default=False, help="browse existing experiments.") optparser.add_option('-B', '--Browse', action='store_true', dest='browse_big', default=False, help="browse existing experiments, more verbose than -b") optparser.add_option('-p', '--progress', action='store_true', dest='progress', default=False, help="like browse, but only shows name and progress bar") options, args = optparser.parse_args() self.options = options return options, args
[ "def", "parse_opt", "(", "self", ")", ":", "optparser", "=", "optparse", ".", "OptionParser", "(", ")", "optparser", ".", "add_option", "(", "'-c'", ",", "'--config'", ",", "action", "=", "'store'", ",", "dest", "=", "'config'", ",", "type", "=", "'strin...
parses the command line options for different settings.
[ "parses", "the", "command", "line", "options", "for", "different", "settings", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/expsuite.py#L61-L88
train
198,878
numenta/htmresearch
htmresearch/support/expsuite.py
PyExperimentSuite.parse_cfg
def parse_cfg(self): """ parses the given config file for experiments. """ self.cfgparser = ConfigParser() if not self.cfgparser.read(self.options.config): raise SystemExit('config file %s not found.'%self.options.config) # Change the current working directory to be relative to 'experiments.cfg' projectDir = os.path.dirname(self.options.config) projectDir = os.path.abspath(projectDir) os.chdir(projectDir)
python
def parse_cfg(self): """ parses the given config file for experiments. """ self.cfgparser = ConfigParser() if not self.cfgparser.read(self.options.config): raise SystemExit('config file %s not found.'%self.options.config) # Change the current working directory to be relative to 'experiments.cfg' projectDir = os.path.dirname(self.options.config) projectDir = os.path.abspath(projectDir) os.chdir(projectDir)
[ "def", "parse_cfg", "(", "self", ")", ":", "self", ".", "cfgparser", "=", "ConfigParser", "(", ")", "if", "not", "self", ".", "cfgparser", ".", "read", "(", "self", ".", "options", ".", "config", ")", ":", "raise", "SystemExit", "(", "'config file %s not...
parses the given config file for experiments.
[ "parses", "the", "given", "config", "file", "for", "experiments", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/expsuite.py#L90-L99
train
198,879
numenta/htmresearch
htmresearch/support/expsuite.py
PyExperimentSuite.mkdir
def mkdir(self, path): """ create a directory if it does not exist. """ if not os.path.exists(path): os.makedirs(path)
python
def mkdir(self, path): """ create a directory if it does not exist. """ if not os.path.exists(path): os.makedirs(path)
[ "def", "mkdir", "(", "self", ",", "path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "makedirs", "(", "path", ")" ]
create a directory if it does not exist.
[ "create", "a", "directory", "if", "it", "does", "not", "exist", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/expsuite.py#L102-L105
train
198,880
numenta/htmresearch
htmresearch/support/expsuite.py
PyExperimentSuite.write_config_file
def write_config_file(self, params, path): """ write a config file for this single exp in the folder path. """ cfgp = ConfigParser() cfgp.add_section(params['name']) for p in params: if p == 'name': continue cfgp.set(params['name'], p, params[p]) f = open(os.path.join(path, 'experiment.cfg'), 'w') cfgp.write(f) f.close()
python
def write_config_file(self, params, path): """ write a config file for this single exp in the folder path. """ cfgp = ConfigParser() cfgp.add_section(params['name']) for p in params: if p == 'name': continue cfgp.set(params['name'], p, params[p]) f = open(os.path.join(path, 'experiment.cfg'), 'w') cfgp.write(f) f.close()
[ "def", "write_config_file", "(", "self", ",", "params", ",", "path", ")", ":", "cfgp", "=", "ConfigParser", "(", ")", "cfgp", ".", "add_section", "(", "params", "[", "'name'", "]", ")", "for", "p", "in", "params", ":", "if", "p", "==", "'name'", ":",...
write a config file for this single exp in the folder path.
[ "write", "a", "config", "file", "for", "this", "single", "exp", "in", "the", "folder", "path", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/expsuite.py#L162-L173
train
198,881
numenta/htmresearch
htmresearch/support/expsuite.py
PyExperimentSuite.get_history
def get_history(self, exp, rep, tags): """ returns the whole history for one experiment and one repetition. tags can be a string or a list of strings. if tags is a string, the history is returned as list of values, if tags is a list of strings or 'all', history is returned as a dictionary of lists of values. """ params = self.get_params(exp) if params == None: raise SystemExit('experiment %s not found.'%exp) # make list of tags, even if it is only one if tags != 'all' and not hasattr(tags, '__iter__'): tags = [tags] results = {} logfile = os.path.join(exp, '%i.log'%rep) try: f = open(logfile) except IOError: if len(tags) == 1: return [] else: return {} for line in f: dic = json.loads(line) for tag in tags: if not tag in results: results[tag] = [] if tag in dic: results[tag].append(dic[tag]) else: results[tag].append(None) f.close() if len(results) == 0: if len(tags) == 1: return [] else: return {} # raise ValueError('tag(s) not found: %s'%str(tags)) if len(tags) == 1: return results[results.keys()[0]] else: return results
python
def get_history(self, exp, rep, tags): """ returns the whole history for one experiment and one repetition. tags can be a string or a list of strings. if tags is a string, the history is returned as list of values, if tags is a list of strings or 'all', history is returned as a dictionary of lists of values. """ params = self.get_params(exp) if params == None: raise SystemExit('experiment %s not found.'%exp) # make list of tags, even if it is only one if tags != 'all' and not hasattr(tags, '__iter__'): tags = [tags] results = {} logfile = os.path.join(exp, '%i.log'%rep) try: f = open(logfile) except IOError: if len(tags) == 1: return [] else: return {} for line in f: dic = json.loads(line) for tag in tags: if not tag in results: results[tag] = [] if tag in dic: results[tag].append(dic[tag]) else: results[tag].append(None) f.close() if len(results) == 0: if len(tags) == 1: return [] else: return {} # raise ValueError('tag(s) not found: %s'%str(tags)) if len(tags) == 1: return results[results.keys()[0]] else: return results
[ "def", "get_history", "(", "self", ",", "exp", ",", "rep", ",", "tags", ")", ":", "params", "=", "self", ".", "get_params", "(", "exp", ")", "if", "params", "==", "None", ":", "raise", "SystemExit", "(", "'experiment %s not found.'", "%", "exp", ")", "...
returns the whole history for one experiment and one repetition. tags can be a string or a list of strings. if tags is a string, the history is returned as list of values, if tags is a list of strings or 'all', history is returned as a dictionary of lists of values.
[ "returns", "the", "whole", "history", "for", "one", "experiment", "and", "one", "repetition", ".", "tags", "can", "be", "a", "string", "or", "a", "list", "of", "strings", ".", "if", "tags", "is", "a", "string", "the", "history", "is", "returned", "as", ...
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/expsuite.py#L175-L222
train
198,882
numenta/htmresearch
htmresearch/support/expsuite.py
PyExperimentSuite.create_dir
def create_dir(self, params, delete=False): """ creates a subdirectory for the experiment, and deletes existing files, if the delete flag is true. then writes the current experiment.cfg file in the folder. """ # create experiment path and subdir fullpath = os.path.join(params['path'], params['name']) self.mkdir(fullpath) # delete old histories if --del flag is active if delete and os.path.exists(fullpath): os.system('rm %s/*' % fullpath) # write a config file for this single exp. in the folder self.write_config_file(params, fullpath)
python
def create_dir(self, params, delete=False): """ creates a subdirectory for the experiment, and deletes existing files, if the delete flag is true. then writes the current experiment.cfg file in the folder. """ # create experiment path and subdir fullpath = os.path.join(params['path'], params['name']) self.mkdir(fullpath) # delete old histories if --del flag is active if delete and os.path.exists(fullpath): os.system('rm %s/*' % fullpath) # write a config file for this single exp. in the folder self.write_config_file(params, fullpath)
[ "def", "create_dir", "(", "self", ",", "params", ",", "delete", "=", "False", ")", ":", "# create experiment path and subdir", "fullpath", "=", "os", ".", "path", ".", "join", "(", "params", "[", "'path'", "]", ",", "params", "[", "'name'", "]", ")", "se...
creates a subdirectory for the experiment, and deletes existing files, if the delete flag is true. then writes the current experiment.cfg file in the folder.
[ "creates", "a", "subdirectory", "for", "the", "experiment", "and", "deletes", "existing", "files", "if", "the", "delete", "flag", "is", "true", ".", "then", "writes", "the", "current", "experiment", ".", "cfg", "file", "in", "the", "folder", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/expsuite.py#L534-L548
train
198,883
numenta/htmresearch
htmresearch/support/expsuite.py
PyExperimentSuite.start
def start(self): """ starts the experiments as given in the config file. """ self.parse_opt() self.parse_cfg() # if -b, -B or -p option is set, only show information, don't # start the experiments if self.options.browse or self.options.browse_big or self.options.progress: self.browse() raise SystemExit # read main configuration file paramlist = [] for exp in self.cfgparser.sections(): if not self.options.experiments or exp in self.options.experiments: params = self.items_to_params(self.cfgparser.items(exp)) params['name'] = exp paramlist.append(params) self.do_experiment(paramlist)
python
def start(self): """ starts the experiments as given in the config file. """ self.parse_opt() self.parse_cfg() # if -b, -B or -p option is set, only show information, don't # start the experiments if self.options.browse or self.options.browse_big or self.options.progress: self.browse() raise SystemExit # read main configuration file paramlist = [] for exp in self.cfgparser.sections(): if not self.options.experiments or exp in self.options.experiments: params = self.items_to_params(self.cfgparser.items(exp)) params['name'] = exp paramlist.append(params) self.do_experiment(paramlist)
[ "def", "start", "(", "self", ")", ":", "self", ".", "parse_opt", "(", ")", "self", ".", "parse_cfg", "(", ")", "# if -b, -B or -p option is set, only show information, don't", "# start the experiments", "if", "self", ".", "options", ".", "browse", "or", "self", "....
starts the experiments as given in the config file.
[ "starts", "the", "experiments", "as", "given", "in", "the", "config", "file", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/expsuite.py#L551-L570
train
198,884
numenta/htmresearch
htmresearch/support/expsuite.py
PyExperimentSuite.run_rep
def run_rep(self, params, rep): """ run a single repetition including directory creation, log files, etc. """ try: name = params['name'] fullpath = os.path.join(params['path'], params['name']) logname = os.path.join(fullpath, '%i.log'%rep) # check if repetition exists and has been completed restore = 0 if os.path.exists(logname): logfile = open(logname, 'r') lines = logfile.readlines() logfile.close() # if completed, continue loop if 'iterations' in params and len(lines) == params['iterations']: return False # if not completed, check if restore_state is supported if not self.restore_supported: # not supported, delete repetition and start over # print 'restore not supported, deleting %s' % logname os.remove(logname) restore = 0 else: restore = len(lines) self.reset(params, rep) if restore: logfile = open(logname, 'a') self.restore_state(params, rep, restore) else: logfile = open(logname, 'w') # loop through iterations and call iterate for it in xrange(restore, params['iterations']): dic = self.iterate(params, rep, it) or {} dic['iteration'] = it if self.restore_supported: self.save_state(params, rep, it) if dic is not None: json.dump(dic, logfile) logfile.write('\n') logfile.flush() logfile.close() self.finalize(params, rep) except: import traceback traceback.print_exc() raise
python
def run_rep(self, params, rep): """ run a single repetition including directory creation, log files, etc. """ try: name = params['name'] fullpath = os.path.join(params['path'], params['name']) logname = os.path.join(fullpath, '%i.log'%rep) # check if repetition exists and has been completed restore = 0 if os.path.exists(logname): logfile = open(logname, 'r') lines = logfile.readlines() logfile.close() # if completed, continue loop if 'iterations' in params and len(lines) == params['iterations']: return False # if not completed, check if restore_state is supported if not self.restore_supported: # not supported, delete repetition and start over # print 'restore not supported, deleting %s' % logname os.remove(logname) restore = 0 else: restore = len(lines) self.reset(params, rep) if restore: logfile = open(logname, 'a') self.restore_state(params, rep, restore) else: logfile = open(logname, 'w') # loop through iterations and call iterate for it in xrange(restore, params['iterations']): dic = self.iterate(params, rep, it) or {} dic['iteration'] = it if self.restore_supported: self.save_state(params, rep, it) if dic is not None: json.dump(dic, logfile) logfile.write('\n') logfile.flush() logfile.close() self.finalize(params, rep) except: import traceback traceback.print_exc() raise
[ "def", "run_rep", "(", "self", ",", "params", ",", "rep", ")", ":", "try", ":", "name", "=", "params", "[", "'name'", "]", "fullpath", "=", "os", ".", "path", ".", "join", "(", "params", "[", "'path'", "]", ",", "params", "[", "'name'", "]", ")",...
run a single repetition including directory creation, log files, etc.
[ "run", "a", "single", "repetition", "including", "directory", "creation", "log", "files", "etc", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/expsuite.py#L608-L661
train
198,885
numenta/htmresearch
htmresearch/algorithms/hierarchical_clustering.py
HierarchicalClustering.getClusterPrototypes
def getClusterPrototypes(self, numClusters, numPrototypes=1): """ Create numClusters flat clusters and find approximately numPrototypes prototypes per flat cluster. Returns an array with each row containing the indices of the prototypes for a single flat cluster. @param numClusters (int) Number of flat clusters to return (approximate). @param numPrototypes (int) Number of prototypes to return per cluster. @returns (tuple of numpy.ndarray) The first element is an array with rows containing the indices of the prototypes for a single flat cluster. If a cluster has less than numPrototypes members, missing indices are filled in with -1. The second element is an array of number of elements in each cluster. """ linkage = self.getLinkageMatrix() linkage[:, 2] -= linkage[:, 2].min() clusters = scipy.cluster.hierarchy.fcluster( linkage, numClusters, criterion="maxclust") prototypes = [] clusterSizes = [] for cluster_id in numpy.unique(clusters): ids = numpy.arange(len(clusters))[clusters == cluster_id] clusterSizes.append(len(ids)) if len(ids) > numPrototypes: cluster_prototypes = HierarchicalClustering._getPrototypes( ids, self._overlaps, numPrototypes) else: cluster_prototypes = numpy.ones(numPrototypes) * -1 cluster_prototypes[:len(ids)] = ids prototypes.append(cluster_prototypes) return numpy.vstack(prototypes).astype(int), numpy.array(clusterSizes)
python
def getClusterPrototypes(self, numClusters, numPrototypes=1): """ Create numClusters flat clusters and find approximately numPrototypes prototypes per flat cluster. Returns an array with each row containing the indices of the prototypes for a single flat cluster. @param numClusters (int) Number of flat clusters to return (approximate). @param numPrototypes (int) Number of prototypes to return per cluster. @returns (tuple of numpy.ndarray) The first element is an array with rows containing the indices of the prototypes for a single flat cluster. If a cluster has less than numPrototypes members, missing indices are filled in with -1. The second element is an array of number of elements in each cluster. """ linkage = self.getLinkageMatrix() linkage[:, 2] -= linkage[:, 2].min() clusters = scipy.cluster.hierarchy.fcluster( linkage, numClusters, criterion="maxclust") prototypes = [] clusterSizes = [] for cluster_id in numpy.unique(clusters): ids = numpy.arange(len(clusters))[clusters == cluster_id] clusterSizes.append(len(ids)) if len(ids) > numPrototypes: cluster_prototypes = HierarchicalClustering._getPrototypes( ids, self._overlaps, numPrototypes) else: cluster_prototypes = numpy.ones(numPrototypes) * -1 cluster_prototypes[:len(ids)] = ids prototypes.append(cluster_prototypes) return numpy.vstack(prototypes).astype(int), numpy.array(clusterSizes)
[ "def", "getClusterPrototypes", "(", "self", ",", "numClusters", ",", "numPrototypes", "=", "1", ")", ":", "linkage", "=", "self", ".", "getLinkageMatrix", "(", ")", "linkage", "[", ":", ",", "2", "]", "-=", "linkage", "[", ":", ",", "2", "]", ".", "m...
Create numClusters flat clusters and find approximately numPrototypes prototypes per flat cluster. Returns an array with each row containing the indices of the prototypes for a single flat cluster. @param numClusters (int) Number of flat clusters to return (approximate). @param numPrototypes (int) Number of prototypes to return per cluster. @returns (tuple of numpy.ndarray) The first element is an array with rows containing the indices of the prototypes for a single flat cluster. If a cluster has less than numPrototypes members, missing indices are filled in with -1. The second element is an array of number of elements in each cluster.
[ "Create", "numClusters", "flat", "clusters", "and", "find", "approximately", "numPrototypes", "prototypes", "per", "flat", "cluster", ".", "Returns", "an", "array", "with", "each", "row", "containing", "the", "indices", "of", "the", "prototypes", "for", "a", "si...
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/hierarchical_clustering.py#L130-L165
train
198,886
numenta/htmresearch
htmresearch/algorithms/hierarchical_clustering.py
HierarchicalClustering._getPrototypes
def _getPrototypes(indices, overlaps, topNumber=1): """ Given a compressed overlap array and a set of indices specifying a subset of those in that array, return the set of topNumber indices of vectors that have maximum average overlap with other vectors in `indices`. @param indices (arraylike) Array of indices for which to get prototypes. @param overlaps (numpy.ndarray) Condensed array of overlaps of the form returned by _computeOverlaps(). @param topNumber (int) The number of prototypes to return. Optional, defaults to 1. @returns (numpy.ndarray) Array of indices of prototypes """ # find the number of data points based on the length of the overlap array # solves for n: len(overlaps) = n(n-1)/2 n = numpy.roots([1, -1, -2 * len(overlaps)]).max() k = len(indices) indices = numpy.array(indices, dtype=int) rowIdxs = numpy.ndarray((k, k-1), dtype=int) colIdxs = numpy.ndarray((k, k-1), dtype=int) for i in xrange(k): rowIdxs[i, :] = indices[i] colIdxs[i, :i] = indices[:i] colIdxs[i, i:] = indices[i+1:] idx = HierarchicalClustering._condensedIndex(rowIdxs, colIdxs, n) subsampledOverlaps = overlaps[idx] meanSubsampledOverlaps = subsampledOverlaps.mean(1) biggestOverlapSubsetIdxs = numpy.argsort( -meanSubsampledOverlaps)[:topNumber] return indices[biggestOverlapSubsetIdxs]
python
def _getPrototypes(indices, overlaps, topNumber=1): """ Given a compressed overlap array and a set of indices specifying a subset of those in that array, return the set of topNumber indices of vectors that have maximum average overlap with other vectors in `indices`. @param indices (arraylike) Array of indices for which to get prototypes. @param overlaps (numpy.ndarray) Condensed array of overlaps of the form returned by _computeOverlaps(). @param topNumber (int) The number of prototypes to return. Optional, defaults to 1. @returns (numpy.ndarray) Array of indices of prototypes """ # find the number of data points based on the length of the overlap array # solves for n: len(overlaps) = n(n-1)/2 n = numpy.roots([1, -1, -2 * len(overlaps)]).max() k = len(indices) indices = numpy.array(indices, dtype=int) rowIdxs = numpy.ndarray((k, k-1), dtype=int) colIdxs = numpy.ndarray((k, k-1), dtype=int) for i in xrange(k): rowIdxs[i, :] = indices[i] colIdxs[i, :i] = indices[:i] colIdxs[i, i:] = indices[i+1:] idx = HierarchicalClustering._condensedIndex(rowIdxs, colIdxs, n) subsampledOverlaps = overlaps[idx] meanSubsampledOverlaps = subsampledOverlaps.mean(1) biggestOverlapSubsetIdxs = numpy.argsort( -meanSubsampledOverlaps)[:topNumber] return indices[biggestOverlapSubsetIdxs]
[ "def", "_getPrototypes", "(", "indices", ",", "overlaps", ",", "topNumber", "=", "1", ")", ":", "# find the number of data points based on the length of the overlap array", "# solves for n: len(overlaps) = n(n-1)/2", "n", "=", "numpy", ".", "roots", "(", "[", "1", ",", ...
Given a compressed overlap array and a set of indices specifying a subset of those in that array, return the set of topNumber indices of vectors that have maximum average overlap with other vectors in `indices`. @param indices (arraylike) Array of indices for which to get prototypes. @param overlaps (numpy.ndarray) Condensed array of overlaps of the form returned by _computeOverlaps(). @param topNumber (int) The number of prototypes to return. Optional, defaults to 1. @returns (numpy.ndarray) Array of indices of prototypes
[ "Given", "a", "compressed", "overlap", "array", "and", "a", "set", "of", "indices", "specifying", "a", "subset", "of", "those", "in", "that", "array", "return", "the", "set", "of", "topNumber", "indices", "of", "vectors", "that", "have", "maximum", "average"...
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/hierarchical_clustering.py#L174-L211
train
198,887
numenta/htmresearch
projects/sdr_paper/pytorch_experiments/analyze_experiment.py
analyzeParameters
def analyzeParameters(expName, suite): """ Analyze the impact of each list parameter in this experiment """ print("\n================",expName,"=====================") try: expParams = suite.get_params(expName) pprint.pprint(expParams) for p in ["boost_strength", "k", "learning_rate", "weight_sparsity", "k_inference_factor", "boost_strength_factor", "c1_out_channels", "c1_k", "learning_rate_factor", "batches_in_epoch", ]: if p in expParams and type(expParams[p]) == list: print("\n",p) for v1 in expParams[p]: # Retrieve the last totalCorrect from each experiment # Print them sorted from best to worst values, params = suite.get_values_fix_params( expName, 0, "testerror", "last", **{p:v1}) v = np.array(values) try: print("Average/min/max for", p, v1, "=", v.mean(), v.min(), v.max()) # sortedIndices = v.argsort() # for i in sortedIndices[::-1]: # print(v[i],params[i]["name"]) except: print("Can't compute stats for",p) except: print("Couldn't load experiment",expName)
python
def analyzeParameters(expName, suite): """ Analyze the impact of each list parameter in this experiment """ print("\n================",expName,"=====================") try: expParams = suite.get_params(expName) pprint.pprint(expParams) for p in ["boost_strength", "k", "learning_rate", "weight_sparsity", "k_inference_factor", "boost_strength_factor", "c1_out_channels", "c1_k", "learning_rate_factor", "batches_in_epoch", ]: if p in expParams and type(expParams[p]) == list: print("\n",p) for v1 in expParams[p]: # Retrieve the last totalCorrect from each experiment # Print them sorted from best to worst values, params = suite.get_values_fix_params( expName, 0, "testerror", "last", **{p:v1}) v = np.array(values) try: print("Average/min/max for", p, v1, "=", v.mean(), v.min(), v.max()) # sortedIndices = v.argsort() # for i in sortedIndices[::-1]: # print(v[i],params[i]["name"]) except: print("Can't compute stats for",p) except: print("Couldn't load experiment",expName)
[ "def", "analyzeParameters", "(", "expName", ",", "suite", ")", ":", "print", "(", "\"\\n================\"", ",", "expName", ",", "\"=====================\"", ")", "try", ":", "expParams", "=", "suite", ".", "get_params", "(", "expName", ")", "pprint", ".", "p...
Analyze the impact of each list parameter in this experiment
[ "Analyze", "the", "impact", "of", "each", "list", "parameter", "in", "this", "experiment" ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sdr_paper/pytorch_experiments/analyze_experiment.py#L31-L62
train
198,888
numenta/htmresearch
projects/sdr_paper/pytorch_experiments/analyze_experiment.py
summarizeResults
def summarizeResults(expName, suite): """ Summarize the totalCorrect value from the last iteration for each experiment in the directory tree. """ print("\n================",expName,"=====================") try: # Retrieve the last totalCorrect from each experiment # Print them sorted from best to worst values, params = suite.get_values_fix_params( expName, 0, "totalCorrect", "last") v = np.array(values) sortedIndices = v.argsort() for i in sortedIndices[::-1]: print(v[i], params[i]["name"]) print() except: print("Couldn't analyze experiment",expName) try: # Retrieve the last totalCorrect from each experiment # Print them sorted from best to worst values, params = suite.get_values_fix_params( expName, 0, "testerror", "last") v = np.array(values) sortedIndices = v.argsort() for i in sortedIndices[::-1]: print(v[i], params[i]["name"]) print() except: print("Couldn't analyze experiment",expName)
python
def summarizeResults(expName, suite): """ Summarize the totalCorrect value from the last iteration for each experiment in the directory tree. """ print("\n================",expName,"=====================") try: # Retrieve the last totalCorrect from each experiment # Print them sorted from best to worst values, params = suite.get_values_fix_params( expName, 0, "totalCorrect", "last") v = np.array(values) sortedIndices = v.argsort() for i in sortedIndices[::-1]: print(v[i], params[i]["name"]) print() except: print("Couldn't analyze experiment",expName) try: # Retrieve the last totalCorrect from each experiment # Print them sorted from best to worst values, params = suite.get_values_fix_params( expName, 0, "testerror", "last") v = np.array(values) sortedIndices = v.argsort() for i in sortedIndices[::-1]: print(v[i], params[i]["name"]) print() except: print("Couldn't analyze experiment",expName)
[ "def", "summarizeResults", "(", "expName", ",", "suite", ")", ":", "print", "(", "\"\\n================\"", ",", "expName", ",", "\"=====================\"", ")", "try", ":", "# Retrieve the last totalCorrect from each experiment", "# Print them sorted from best to worst", "v...
Summarize the totalCorrect value from the last iteration for each experiment in the directory tree.
[ "Summarize", "the", "totalCorrect", "value", "from", "the", "last", "iteration", "for", "each", "experiment", "in", "the", "directory", "tree", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sdr_paper/pytorch_experiments/analyze_experiment.py#L65-L98
train
198,889
numenta/htmresearch
projects/sdr_paper/pytorch_experiments/analyze_experiment.py
learningCurve
def learningCurve(expPath, suite): """ Print the test and overall noise errors from each iteration of this experiment """ print("\nLEARNING CURVE ================",expPath,"=====================") try: headers=["testerror","totalCorrect","elapsedTime","entropy"] result = suite.get_value(expPath, 0, headers, "all") info = [] for i,v in enumerate(zip(result["testerror"],result["totalCorrect"], result["elapsedTime"],result["entropy"])): info.append([i, v[0], v[1], int(v[2]), v[3]]) headers.insert(0,"iteration") print(tabulate(info, headers=headers, tablefmt="grid")) except: print("Couldn't load experiment",expPath)
python
def learningCurve(expPath, suite): """ Print the test and overall noise errors from each iteration of this experiment """ print("\nLEARNING CURVE ================",expPath,"=====================") try: headers=["testerror","totalCorrect","elapsedTime","entropy"] result = suite.get_value(expPath, 0, headers, "all") info = [] for i,v in enumerate(zip(result["testerror"],result["totalCorrect"], result["elapsedTime"],result["entropy"])): info.append([i, v[0], v[1], int(v[2]), v[3]]) headers.insert(0,"iteration") print(tabulate(info, headers=headers, tablefmt="grid")) except: print("Couldn't load experiment",expPath)
[ "def", "learningCurve", "(", "expPath", ",", "suite", ")", ":", "print", "(", "\"\\nLEARNING CURVE ================\"", ",", "expPath", ",", "\"=====================\"", ")", "try", ":", "headers", "=", "[", "\"testerror\"", ",", "\"totalCorrect\"", ",", "\"elapsedT...
Print the test and overall noise errors from each iteration of this experiment
[ "Print", "the", "test", "and", "overall", "noise", "errors", "from", "each", "iteration", "of", "this", "experiment" ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sdr_paper/pytorch_experiments/analyze_experiment.py#L124-L139
train
198,890
numenta/htmresearch
htmresearch/regions/CoordinateSensorRegion.py
CoordinateSensorRegion.compute
def compute(self, inputs, outputs): """ Get the next record from the queue and encode it. @param inputs This parameter is ignored. The data comes from the queue @param outputs See definition in the spec above. """ if len(self.queue) > 0: data = self.queue.pop() else: raise Exception("CoordinateSensor: No data to encode: queue is empty") outputs["resetOut"][0] = data["reset"] outputs["sequenceIdOut"][0] = data["sequenceId"] sdr = self.encoder.encode((numpy.array(data["coordinate"]), self.radius)) outputs["dataOut"][:] = sdr if self.verbosity > 1: print "CoordinateSensor outputs:" print "Coordinate = ", data["coordinate"] print "sequenceIdOut: ", outputs["sequenceIdOut"] print "resetOut: ", outputs["resetOut"] print "dataOut: ", outputs["dataOut"].nonzero()[0]
python
def compute(self, inputs, outputs): """ Get the next record from the queue and encode it. @param inputs This parameter is ignored. The data comes from the queue @param outputs See definition in the spec above. """ if len(self.queue) > 0: data = self.queue.pop() else: raise Exception("CoordinateSensor: No data to encode: queue is empty") outputs["resetOut"][0] = data["reset"] outputs["sequenceIdOut"][0] = data["sequenceId"] sdr = self.encoder.encode((numpy.array(data["coordinate"]), self.radius)) outputs["dataOut"][:] = sdr if self.verbosity > 1: print "CoordinateSensor outputs:" print "Coordinate = ", data["coordinate"] print "sequenceIdOut: ", outputs["sequenceIdOut"] print "resetOut: ", outputs["resetOut"] print "dataOut: ", outputs["dataOut"].nonzero()[0]
[ "def", "compute", "(", "self", ",", "inputs", ",", "outputs", ")", ":", "if", "len", "(", "self", ".", "queue", ")", ">", "0", ":", "data", "=", "self", ".", "queue", ".", "pop", "(", ")", "else", ":", "raise", "Exception", "(", "\"CoordinateSensor...
Get the next record from the queue and encode it. @param inputs This parameter is ignored. The data comes from the queue @param outputs See definition in the spec above.
[ "Get", "the", "next", "record", "from", "the", "queue", "and", "encode", "it", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/regions/CoordinateSensorRegion.py#L127-L149
train
198,891
numenta/htmresearch
projects/combined_sequences/analysis_utilities.py
printDiagnostics
def printDiagnostics(exp, sequences, objects, args, verbosity=0): """Useful diagnostics for debugging.""" print "Experiment start time:", time.ctime() print "\nExperiment arguments:" pprint.pprint(args) r = sequences.objectConfusion() print "Average common pairs in sequences=", r[0], print ", features=",r[2] r = objects.objectConfusion() print "Average common pairs in objects=", r[0], print ", locations=",r[1], print ", features=",r[2] # For detailed debugging if verbosity > 0: print "\nObjects are:" for o in objects: pairs = objects[o] pairs.sort() print str(o) + ": " + str(pairs) print "\nSequences:" for i in sequences: print i,sequences[i] print "\nNetwork parameters:" pprint.pprint(exp.config)
python
def printDiagnostics(exp, sequences, objects, args, verbosity=0): """Useful diagnostics for debugging.""" print "Experiment start time:", time.ctime() print "\nExperiment arguments:" pprint.pprint(args) r = sequences.objectConfusion() print "Average common pairs in sequences=", r[0], print ", features=",r[2] r = objects.objectConfusion() print "Average common pairs in objects=", r[0], print ", locations=",r[1], print ", features=",r[2] # For detailed debugging if verbosity > 0: print "\nObjects are:" for o in objects: pairs = objects[o] pairs.sort() print str(o) + ": " + str(pairs) print "\nSequences:" for i in sequences: print i,sequences[i] print "\nNetwork parameters:" pprint.pprint(exp.config)
[ "def", "printDiagnostics", "(", "exp", ",", "sequences", ",", "objects", ",", "args", ",", "verbosity", "=", "0", ")", ":", "print", "\"Experiment start time:\"", ",", "time", ".", "ctime", "(", ")", "print", "\"\\nExperiment arguments:\"", "pprint", ".", "ppr...
Useful diagnostics for debugging.
[ "Useful", "diagnostics", "for", "debugging", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/combined_sequences/analysis_utilities.py#L37-L64
train
198,892
numenta/htmresearch
projects/combined_sequences/analysis_utilities.py
createArgs
def createArgs(**kwargs): """ Each kwarg is a list. Return a list of dicts representing all possible combinations of the kwargs. """ if len(kwargs) == 0: return [{}] kargs = deepcopy(kwargs) k1 = kargs.keys()[0] values = kargs.pop(k1) args = [] # Get all other combinations otherArgs = createArgs(**kargs) # Create combinations for values associated with k1 for v in values: newArgs = deepcopy(otherArgs) arg = {k1: v} for newArg in newArgs: newArg.update(arg) args.append(newArg) return args
python
def createArgs(**kwargs): """ Each kwarg is a list. Return a list of dicts representing all possible combinations of the kwargs. """ if len(kwargs) == 0: return [{}] kargs = deepcopy(kwargs) k1 = kargs.keys()[0] values = kargs.pop(k1) args = [] # Get all other combinations otherArgs = createArgs(**kargs) # Create combinations for values associated with k1 for v in values: newArgs = deepcopy(otherArgs) arg = {k1: v} for newArg in newArgs: newArg.update(arg) args.append(newArg) return args
[ "def", "createArgs", "(", "*", "*", "kwargs", ")", ":", "if", "len", "(", "kwargs", ")", "==", "0", ":", "return", "[", "{", "}", "]", "kargs", "=", "deepcopy", "(", "kwargs", ")", "k1", "=", "kargs", ".", "keys", "(", ")", "[", "0", "]", "va...
Each kwarg is a list. Return a list of dicts representing all possible combinations of the kwargs.
[ "Each", "kwarg", "is", "a", "list", ".", "Return", "a", "list", "of", "dicts", "representing", "all", "possible", "combinations", "of", "the", "kwargs", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/combined_sequences/analysis_utilities.py#L156-L178
train
198,893
numenta/htmresearch
htmresearch/support/neural_correlations_utils.py
randomizeSequence
def randomizeSequence(sequence, symbolsPerSequence, numColumns, sparsity, p = 0.25): """ Takes a sequence as input and randomizes a percentage p of it by choosing SDRs at random while preserving the remaining invariant. @param sequence (array) sequence to be randomized @param symbolsPerSequence (int) number of symbols per sequence @param numColumns (int) number of columns in the TM @param sparsity (float) percentage of sparsity @p (float) percentage of symbols to be replaced @return randomizedSequence (array) sequence that contains p percentage of new SDRs """ randomizedSequence = [] sparseCols = int(numColumns * sparsity) numSymbolsToChange = int(symbolsPerSequence * p) symIndices = np.random.permutation(np.arange(symbolsPerSequence)) for symbol in range(symbolsPerSequence): randomizedSequence.append(sequence[symbol]) i = 0 while numSymbolsToChange > 0: randomizedSequence[symIndices[i]] = generateRandomSymbol(numColumns, sparseCols) i += 1 numSymbolsToChange -= 1 return randomizedSequence
python
def randomizeSequence(sequence, symbolsPerSequence, numColumns, sparsity, p = 0.25): """ Takes a sequence as input and randomizes a percentage p of it by choosing SDRs at random while preserving the remaining invariant. @param sequence (array) sequence to be randomized @param symbolsPerSequence (int) number of symbols per sequence @param numColumns (int) number of columns in the TM @param sparsity (float) percentage of sparsity @p (float) percentage of symbols to be replaced @return randomizedSequence (array) sequence that contains p percentage of new SDRs """ randomizedSequence = [] sparseCols = int(numColumns * sparsity) numSymbolsToChange = int(symbolsPerSequence * p) symIndices = np.random.permutation(np.arange(symbolsPerSequence)) for symbol in range(symbolsPerSequence): randomizedSequence.append(sequence[symbol]) i = 0 while numSymbolsToChange > 0: randomizedSequence[symIndices[i]] = generateRandomSymbol(numColumns, sparseCols) i += 1 numSymbolsToChange -= 1 return randomizedSequence
[ "def", "randomizeSequence", "(", "sequence", ",", "symbolsPerSequence", ",", "numColumns", ",", "sparsity", ",", "p", "=", "0.25", ")", ":", "randomizedSequence", "=", "[", "]", "sparseCols", "=", "int", "(", "numColumns", "*", "sparsity", ")", "numSymbolsToCh...
Takes a sequence as input and randomizes a percentage p of it by choosing SDRs at random while preserving the remaining invariant. @param sequence (array) sequence to be randomized @param symbolsPerSequence (int) number of symbols per sequence @param numColumns (int) number of columns in the TM @param sparsity (float) percentage of sparsity @p (float) percentage of symbols to be replaced @return randomizedSequence (array) sequence that contains p percentage of new SDRs
[ "Takes", "a", "sequence", "as", "input", "and", "randomizes", "a", "percentage", "p", "of", "it", "by", "choosing", "SDRs", "at", "random", "while", "preserving", "the", "remaining", "invariant", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/neural_correlations_utils.py#L42-L65
train
198,894
numenta/htmresearch
htmresearch/support/neural_correlations_utils.py
generateHOSequence
def generateHOSequence(sequence, symbolsPerSequence, numColumns, sparsity): """ Generates a high-order sequence by taking an initial sequence and the changing its first and last SDRs by random SDRs @param sequence (array) sequence to be randomized @param symbolsPerSequence (int) number of symbols per sequence @param numColumns (int) number of columns in the TM @param sparsity (float) percentage of sparsity @return randomizedSequence (array) sequence that contains p percentage of new SDRs """ sequenceHO = [] sparseCols = int(numColumns * sparsity) for symbol in range(symbolsPerSequence): if symbol == 0 or symbol == (symbolsPerSequence - 1): sequenceHO.append(generateRandomSymbol(numColumns, sparseCols)) else: sequenceHO.append(sequence[symbol]) return sequenceHO
python
def generateHOSequence(sequence, symbolsPerSequence, numColumns, sparsity): """ Generates a high-order sequence by taking an initial sequence and the changing its first and last SDRs by random SDRs @param sequence (array) sequence to be randomized @param symbolsPerSequence (int) number of symbols per sequence @param numColumns (int) number of columns in the TM @param sparsity (float) percentage of sparsity @return randomizedSequence (array) sequence that contains p percentage of new SDRs """ sequenceHO = [] sparseCols = int(numColumns * sparsity) for symbol in range(symbolsPerSequence): if symbol == 0 or symbol == (symbolsPerSequence - 1): sequenceHO.append(generateRandomSymbol(numColumns, sparseCols)) else: sequenceHO.append(sequence[symbol]) return sequenceHO
[ "def", "generateHOSequence", "(", "sequence", ",", "symbolsPerSequence", ",", "numColumns", ",", "sparsity", ")", ":", "sequenceHO", "=", "[", "]", "sparseCols", "=", "int", "(", "numColumns", "*", "sparsity", ")", "for", "symbol", "in", "range", "(", "symbo...
Generates a high-order sequence by taking an initial sequence and the changing its first and last SDRs by random SDRs @param sequence (array) sequence to be randomized @param symbolsPerSequence (int) number of symbols per sequence @param numColumns (int) number of columns in the TM @param sparsity (float) percentage of sparsity @return randomizedSequence (array) sequence that contains p percentage of new SDRs
[ "Generates", "a", "high", "-", "order", "sequence", "by", "taking", "an", "initial", "sequence", "and", "the", "changing", "its", "first", "and", "last", "SDRs", "by", "random", "SDRs" ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/neural_correlations_utils.py#L68-L86
train
198,895
numenta/htmresearch
htmresearch/support/neural_correlations_utils.py
percentOverlap
def percentOverlap(x1, x2, numColumns): """ Calculates the percentage of overlap between two SDRs @param x1 (array) SDR @param x2 (array) SDR @return percentageOverlap (float) percentage overlap between x1 and x2 """ nonZeroX1 = np.count_nonzero(x1) nonZeroX2 = np.count_nonzero(x2) sparseCols = min(nonZeroX1, nonZeroX2) # transform input vector specifying columns into binary vector binX1 = np.zeros(numColumns, dtype="uint32") binX2 = np.zeros(numColumns, dtype="uint32") for i in range(sparseCols): binX1[x1[i]] = 1 binX2[x2[i]] = 1 return float(np.dot(binX1, binX2))/float(sparseCols)
python
def percentOverlap(x1, x2, numColumns): """ Calculates the percentage of overlap between two SDRs @param x1 (array) SDR @param x2 (array) SDR @return percentageOverlap (float) percentage overlap between x1 and x2 """ nonZeroX1 = np.count_nonzero(x1) nonZeroX2 = np.count_nonzero(x2) sparseCols = min(nonZeroX1, nonZeroX2) # transform input vector specifying columns into binary vector binX1 = np.zeros(numColumns, dtype="uint32") binX2 = np.zeros(numColumns, dtype="uint32") for i in range(sparseCols): binX1[x1[i]] = 1 binX2[x2[i]] = 1 return float(np.dot(binX1, binX2))/float(sparseCols)
[ "def", "percentOverlap", "(", "x1", ",", "x2", ",", "numColumns", ")", ":", "nonZeroX1", "=", "np", ".", "count_nonzero", "(", "x1", ")", "nonZeroX2", "=", "np", ".", "count_nonzero", "(", "x2", ")", "sparseCols", "=", "min", "(", "nonZeroX1", ",", "no...
Calculates the percentage of overlap between two SDRs @param x1 (array) SDR @param x2 (array) SDR @return percentageOverlap (float) percentage overlap between x1 and x2
[ "Calculates", "the", "percentage", "of", "overlap", "between", "two", "SDRs" ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/neural_correlations_utils.py#L89-L106
train
198,896
numenta/htmresearch
htmresearch/support/neural_correlations_utils.py
generateRandomSymbol
def generateRandomSymbol(numColumns, sparseCols): """ Generates a random SDR with sparseCols number of active columns @param numColumns (int) number of columns in the temporal memory @param sparseCols (int) number of sparse columns for desired SDR @return symbol (list) SDR """ symbol = list() remainingCols = sparseCols while remainingCols > 0: col = random.randrange(numColumns) if col not in symbol: symbol.append(col) remainingCols -= 1 return symbol
python
def generateRandomSymbol(numColumns, sparseCols): """ Generates a random SDR with sparseCols number of active columns @param numColumns (int) number of columns in the temporal memory @param sparseCols (int) number of sparse columns for desired SDR @return symbol (list) SDR """ symbol = list() remainingCols = sparseCols while remainingCols > 0: col = random.randrange(numColumns) if col not in symbol: symbol.append(col) remainingCols -= 1 return symbol
[ "def", "generateRandomSymbol", "(", "numColumns", ",", "sparseCols", ")", ":", "symbol", "=", "list", "(", ")", "remainingCols", "=", "sparseCols", "while", "remainingCols", ">", "0", ":", "col", "=", "random", ".", "randrange", "(", "numColumns", ")", "if",...
Generates a random SDR with sparseCols number of active columns @param numColumns (int) number of columns in the temporal memory @param sparseCols (int) number of sparse columns for desired SDR @return symbol (list) SDR
[ "Generates", "a", "random", "SDR", "with", "sparseCols", "number", "of", "active", "columns" ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/neural_correlations_utils.py#L109-L124
train
198,897
numenta/htmresearch
htmresearch/support/neural_correlations_utils.py
generateRandomSequence
def generateRandomSequence(numSymbols, numColumns, sparsity): """ Generate a random sequence comprising numSymbols SDRs @param numSymbols (int) number of SDRs in random sequence @param numColumns (int) number of columns in the temporal memory @param sparsity (float) percentage of sparsity (real number between 0 and 1) @return sequence (array) random sequence generated """ sequence = [] sparseCols = int(numColumns * sparsity) for _ in range(numSymbols): sequence.append(generateRandomSymbol(numColumns, sparseCols)) return sequence
python
def generateRandomSequence(numSymbols, numColumns, sparsity): """ Generate a random sequence comprising numSymbols SDRs @param numSymbols (int) number of SDRs in random sequence @param numColumns (int) number of columns in the temporal memory @param sparsity (float) percentage of sparsity (real number between 0 and 1) @return sequence (array) random sequence generated """ sequence = [] sparseCols = int(numColumns * sparsity) for _ in range(numSymbols): sequence.append(generateRandomSymbol(numColumns, sparseCols)) return sequence
[ "def", "generateRandomSequence", "(", "numSymbols", ",", "numColumns", ",", "sparsity", ")", ":", "sequence", "=", "[", "]", "sparseCols", "=", "int", "(", "numColumns", "*", "sparsity", ")", "for", "_", "in", "range", "(", "numSymbols", ")", ":", "sequenc...
Generate a random sequence comprising numSymbols SDRs @param numSymbols (int) number of SDRs in random sequence @param numColumns (int) number of columns in the temporal memory @param sparsity (float) percentage of sparsity (real number between 0 and 1) @return sequence (array) random sequence generated
[ "Generate", "a", "random", "sequence", "comprising", "numSymbols", "SDRs" ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/neural_correlations_utils.py#L127-L140
train
198,898
numenta/htmresearch
htmresearch/support/neural_correlations_utils.py
accuracy
def accuracy(current, predicted): """ Computes the accuracy of the TM at time-step t based on the prediction at time-step t-1 and the current active columns at time-step t. @param current (array) binary vector containing current active columns @param predicted (array) binary vector containing predicted active columns @return acc (float) prediction accuracy of the TM at time-step t """ acc = 0 if np.count_nonzero(predicted) > 0: acc = float(np.dot(current, predicted))/float(np.count_nonzero(predicted)) return acc
python
def accuracy(current, predicted): """ Computes the accuracy of the TM at time-step t based on the prediction at time-step t-1 and the current active columns at time-step t. @param current (array) binary vector containing current active columns @param predicted (array) binary vector containing predicted active columns @return acc (float) prediction accuracy of the TM at time-step t """ acc = 0 if np.count_nonzero(predicted) > 0: acc = float(np.dot(current, predicted))/float(np.count_nonzero(predicted)) return acc
[ "def", "accuracy", "(", "current", ",", "predicted", ")", ":", "acc", "=", "0", "if", "np", ".", "count_nonzero", "(", "predicted", ")", ">", "0", ":", "acc", "=", "float", "(", "np", ".", "dot", "(", "current", ",", "predicted", ")", ")", "/", "...
Computes the accuracy of the TM at time-step t based on the prediction at time-step t-1 and the current active columns at time-step t. @param current (array) binary vector containing current active columns @param predicted (array) binary vector containing predicted active columns @return acc (float) prediction accuracy of the TM at time-step t
[ "Computes", "the", "accuracy", "of", "the", "TM", "at", "time", "-", "step", "t", "based", "on", "the", "prediction", "at", "time", "-", "step", "t", "-", "1", "and", "the", "current", "active", "columns", "at", "time", "-", "step", "t", "." ]
70c096b09a577ea0432c3f3bfff4442d4871b7aa
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/neural_correlations_utils.py#L169-L181
train
198,899