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 | htmresearch/support/neural_correlations_utils.py | sampleCellsWithinColumns | def sampleCellsWithinColumns(numCellPairs, cellsPerColumn, numColumns, seed=42):
"""
Generate indices of cell pairs, each pair of cells are from the same column
@return cellPairs (list) list of cell pairs
"""
np.random.seed(seed)
cellPairs = []
for i in range(numCellPairs):
randCol = np.random.randint(numColumns)
randCells = np.random.choice(np.arange(cellsPerColumn), (2, ), replace=False)
cellsPair = randCol * cellsPerColumn + randCells
cellPairs.append(cellsPair)
return cellPairs | python | def sampleCellsWithinColumns(numCellPairs, cellsPerColumn, numColumns, seed=42):
"""
Generate indices of cell pairs, each pair of cells are from the same column
@return cellPairs (list) list of cell pairs
"""
np.random.seed(seed)
cellPairs = []
for i in range(numCellPairs):
randCol = np.random.randint(numColumns)
randCells = np.random.choice(np.arange(cellsPerColumn), (2, ), replace=False)
cellsPair = randCol * cellsPerColumn + randCells
cellPairs.append(cellsPair)
return cellPairs | [
"def",
"sampleCellsWithinColumns",
"(",
"numCellPairs",
",",
"cellsPerColumn",
",",
"numColumns",
",",
"seed",
"=",
"42",
")",
":",
"np",
".",
"random",
".",
"seed",
"(",
"seed",
")",
"cellPairs",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"numCellPa... | Generate indices of cell pairs, each pair of cells are from the same column
@return cellPairs (list) list of cell pairs | [
"Generate",
"indices",
"of",
"cell",
"pairs",
"each",
"pair",
"of",
"cells",
"are",
"from",
"the",
"same",
"column"
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/neural_correlations_utils.py#L202-L215 | train | 198,900 |
numenta/htmresearch | htmresearch/support/neural_correlations_utils.py | sampleCellsAcrossColumns | def sampleCellsAcrossColumns(numCellPairs, cellsPerColumn, numColumns, seed=42):
"""
Generate indices of cell pairs, each pair of cells are from different column
@return cellPairs (list) list of cell pairs
"""
np.random.seed(seed)
cellPairs = []
for i in range(numCellPairs):
randCols = np.random.choice(np.arange(numColumns), (2, ), replace=False)
randCells = np.random.choice(np.arange(cellsPerColumn), (2, ), replace=False)
cellsPair = np.zeros((2, ))
for j in range(2):
cellsPair[j] = randCols[j] * cellsPerColumn + randCells[j]
cellPairs.append(cellsPair.astype('int32'))
return cellPairs | python | def sampleCellsAcrossColumns(numCellPairs, cellsPerColumn, numColumns, seed=42):
"""
Generate indices of cell pairs, each pair of cells are from different column
@return cellPairs (list) list of cell pairs
"""
np.random.seed(seed)
cellPairs = []
for i in range(numCellPairs):
randCols = np.random.choice(np.arange(numColumns), (2, ), replace=False)
randCells = np.random.choice(np.arange(cellsPerColumn), (2, ), replace=False)
cellsPair = np.zeros((2, ))
for j in range(2):
cellsPair[j] = randCols[j] * cellsPerColumn + randCells[j]
cellPairs.append(cellsPair.astype('int32'))
return cellPairs | [
"def",
"sampleCellsAcrossColumns",
"(",
"numCellPairs",
",",
"cellsPerColumn",
",",
"numColumns",
",",
"seed",
"=",
"42",
")",
":",
"np",
".",
"random",
".",
"seed",
"(",
"seed",
")",
"cellPairs",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"numCellPa... | Generate indices of cell pairs, each pair of cells are from different column
@return cellPairs (list) list of cell pairs | [
"Generate",
"indices",
"of",
"cell",
"pairs",
"each",
"pair",
"of",
"cells",
"are",
"from",
"different",
"column"
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/neural_correlations_utils.py#L218-L233 | train | 198,901 |
numenta/htmresearch | htmresearch/support/neural_correlations_utils.py | subSample | def subSample(spikeTrains, numCells, totalCells, currentTS, timeWindow):
"""
Obtains a random sample of cells from the whole spike train matrix consisting of numCells cells
from the start of simulation time up to currentTS
@param spikeTrains (array) array containing the spike trains of cells in the TM
@param numCells (int) number of cells to be sampled from the matrix of spike trains
@param totalCells (int) total number of cells in the TM
@param currentTS (int) time-step upper bound of sample (sample will go from time-step 0 up to currentTS)
@param timeWindow (int) number of time-steps to sample from the spike trains
@return subSpikeTrains (array) spike train matrix sampled from the total spike train matrix
"""
indices = np.random.permutation(np.arange(totalCells))
if currentTS > 0 and currentTS < timeWindow:
subSpikeTrains = np.zeros((numCells, currentTS), dtype = "uint32")
for i in range(numCells):
subSpikeTrains[i,:] = spikeTrains[indices[i],:]
elif currentTS > 0 and currentTS >= timeWindow:
subSpikeTrains = np.zeros((numCells, timeWindow), dtype = "uint32")
for i in range(numCells):
subSpikeTrains[i,:] = spikeTrains[indices[i],(currentTS-timeWindow):currentTS]
elif currentTS == 0:
# This option takes the whole spike train history
totalTS = np.shape(spikeTrains)[1]
subSpikeTrains = np.zeros((numCells, totalTS), dtype = "uint32")
for i in range(numCells):
subSpikeTrains[i,:] = spikeTrains[indices[i],:]
elif currentTS < 0:
# This option takes a timestep at random and a time window
# specified by the user after the chosen time step
totalTS = np.shape(spikeTrains)[1]
subSpikeTrains = np.zeros((numCells, timeWindow), dtype = "uint32")
rnd = random.randrange(totalTS - timeWindow)
print "Starting from timestep: " + str(rnd)
for i in range(numCells):
subSpikeTrains[i,:] = spikeTrains[indices[i],rnd:(rnd+timeWindow)]
return subSpikeTrains | python | def subSample(spikeTrains, numCells, totalCells, currentTS, timeWindow):
"""
Obtains a random sample of cells from the whole spike train matrix consisting of numCells cells
from the start of simulation time up to currentTS
@param spikeTrains (array) array containing the spike trains of cells in the TM
@param numCells (int) number of cells to be sampled from the matrix of spike trains
@param totalCells (int) total number of cells in the TM
@param currentTS (int) time-step upper bound of sample (sample will go from time-step 0 up to currentTS)
@param timeWindow (int) number of time-steps to sample from the spike trains
@return subSpikeTrains (array) spike train matrix sampled from the total spike train matrix
"""
indices = np.random.permutation(np.arange(totalCells))
if currentTS > 0 and currentTS < timeWindow:
subSpikeTrains = np.zeros((numCells, currentTS), dtype = "uint32")
for i in range(numCells):
subSpikeTrains[i,:] = spikeTrains[indices[i],:]
elif currentTS > 0 and currentTS >= timeWindow:
subSpikeTrains = np.zeros((numCells, timeWindow), dtype = "uint32")
for i in range(numCells):
subSpikeTrains[i,:] = spikeTrains[indices[i],(currentTS-timeWindow):currentTS]
elif currentTS == 0:
# This option takes the whole spike train history
totalTS = np.shape(spikeTrains)[1]
subSpikeTrains = np.zeros((numCells, totalTS), dtype = "uint32")
for i in range(numCells):
subSpikeTrains[i,:] = spikeTrains[indices[i],:]
elif currentTS < 0:
# This option takes a timestep at random and a time window
# specified by the user after the chosen time step
totalTS = np.shape(spikeTrains)[1]
subSpikeTrains = np.zeros((numCells, timeWindow), dtype = "uint32")
rnd = random.randrange(totalTS - timeWindow)
print "Starting from timestep: " + str(rnd)
for i in range(numCells):
subSpikeTrains[i,:] = spikeTrains[indices[i],rnd:(rnd+timeWindow)]
return subSpikeTrains | [
"def",
"subSample",
"(",
"spikeTrains",
",",
"numCells",
",",
"totalCells",
",",
"currentTS",
",",
"timeWindow",
")",
":",
"indices",
"=",
"np",
".",
"random",
".",
"permutation",
"(",
"np",
".",
"arange",
"(",
"totalCells",
")",
")",
"if",
"currentTS",
... | Obtains a random sample of cells from the whole spike train matrix consisting of numCells cells
from the start of simulation time up to currentTS
@param spikeTrains (array) array containing the spike trains of cells in the TM
@param numCells (int) number of cells to be sampled from the matrix of spike trains
@param totalCells (int) total number of cells in the TM
@param currentTS (int) time-step upper bound of sample (sample will go from time-step 0 up to currentTS)
@param timeWindow (int) number of time-steps to sample from the spike trains
@return subSpikeTrains (array) spike train matrix sampled from the total spike train matrix | [
"Obtains",
"a",
"random",
"sample",
"of",
"cells",
"from",
"the",
"whole",
"spike",
"train",
"matrix",
"consisting",
"of",
"numCells",
"cells",
"from",
"the",
"start",
"of",
"simulation",
"time",
"up",
"to",
"currentTS"
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/neural_correlations_utils.py#L236-L273 | train | 198,902 |
numenta/htmresearch | htmresearch/support/neural_correlations_utils.py | subSampleWholeColumn | def subSampleWholeColumn(spikeTrains, colIndices, cellsPerColumn, currentTS, timeWindow):
"""
Obtains subsample from matrix of spike trains by considering the cells in columns specified
by colIndices. Thus, it returns a matrix of spike trains of cells within the same column.
@param spikeTrains (array) array containing the spike trains of cells in the TM
@param colIndices (array) array containing the indices of columns whose spike trains should be sampled
@param cellsPerColumn (int) number of cells per column in the TM
@param currentTS (int) time-step upper bound of sample (sample will go from time-step 0 up to currentTS)
@param timeWindow (int) number of time-steps to sample from the spike trains
@return subSpikeTrains (array) spike train matrix sampled from the total spike train matrix
"""
numColumns = np.shape(colIndices)[0]
numCells = numColumns * cellsPerColumn
if currentTS > 0 and currentTS < timeWindow:
subSpikeTrains = np.zeros((numCells, currentTS), dtype = "uint32")
for i in range(numColumns):
currentCol = colIndices[i]
initialCell = cellsPerColumn * currentCol
for j in range(cellsPerColumn):
subSpikeTrains[(cellsPerColumn*i) + j,:] = spikeTrains[initialCell + j,:]
elif currentTS > 0 and currentTS >= timeWindow:
subSpikeTrains = np.zeros((numCells, timeWindow), dtype = "uint32")
for i in range(numColumns):
currentCol = colIndices[i]
initialCell = cellsPerColumn * currentCol
for j in range(cellsPerColumn):
subSpikeTrains[(cellsPerColumn*i) + j,:] = spikeTrains[initialCell + j,(currentTS-timeWindow):currentTS]
elif currentTS == 0:
# This option takes the whole spike train history
totalTS = np.shape(spikeTrains)[1]
subSpikeTrains = np.zeros((numCells, totalTS), dtype = "uint32")
for i in range(numColumns):
currentCol = colIndices[i]
initialCell = cellsPerColumn * currentCol
for j in range(cellsPerColumn):
subSpikeTrains[(cellsPerColumn*i) + j,:] = spikeTrains[initialCell + j,:]
elif currentTS < 0:
totalTS = np.shape(spikeTrains)[1]
subSpikeTrains = np.zeros((numCells, timeWindow), dtype = "uint32")
rnd = random.randrange(totalTS - timeWindow)
print "Starting from timestep: " + str(rnd)
for i in range(numColumns):
currentCol = colIndices[i]
initialCell = cellsPerColumn * currentCol
for j in range(cellsPerColumn):
subSpikeTrains[(cellsPerColumn*i) + j,:] = spikeTrains[initialCell + j,rnd:(rnd+timeWindow)]
return subSpikeTrains | python | def subSampleWholeColumn(spikeTrains, colIndices, cellsPerColumn, currentTS, timeWindow):
"""
Obtains subsample from matrix of spike trains by considering the cells in columns specified
by colIndices. Thus, it returns a matrix of spike trains of cells within the same column.
@param spikeTrains (array) array containing the spike trains of cells in the TM
@param colIndices (array) array containing the indices of columns whose spike trains should be sampled
@param cellsPerColumn (int) number of cells per column in the TM
@param currentTS (int) time-step upper bound of sample (sample will go from time-step 0 up to currentTS)
@param timeWindow (int) number of time-steps to sample from the spike trains
@return subSpikeTrains (array) spike train matrix sampled from the total spike train matrix
"""
numColumns = np.shape(colIndices)[0]
numCells = numColumns * cellsPerColumn
if currentTS > 0 and currentTS < timeWindow:
subSpikeTrains = np.zeros((numCells, currentTS), dtype = "uint32")
for i in range(numColumns):
currentCol = colIndices[i]
initialCell = cellsPerColumn * currentCol
for j in range(cellsPerColumn):
subSpikeTrains[(cellsPerColumn*i) + j,:] = spikeTrains[initialCell + j,:]
elif currentTS > 0 and currentTS >= timeWindow:
subSpikeTrains = np.zeros((numCells, timeWindow), dtype = "uint32")
for i in range(numColumns):
currentCol = colIndices[i]
initialCell = cellsPerColumn * currentCol
for j in range(cellsPerColumn):
subSpikeTrains[(cellsPerColumn*i) + j,:] = spikeTrains[initialCell + j,(currentTS-timeWindow):currentTS]
elif currentTS == 0:
# This option takes the whole spike train history
totalTS = np.shape(spikeTrains)[1]
subSpikeTrains = np.zeros((numCells, totalTS), dtype = "uint32")
for i in range(numColumns):
currentCol = colIndices[i]
initialCell = cellsPerColumn * currentCol
for j in range(cellsPerColumn):
subSpikeTrains[(cellsPerColumn*i) + j,:] = spikeTrains[initialCell + j,:]
elif currentTS < 0:
totalTS = np.shape(spikeTrains)[1]
subSpikeTrains = np.zeros((numCells, timeWindow), dtype = "uint32")
rnd = random.randrange(totalTS - timeWindow)
print "Starting from timestep: " + str(rnd)
for i in range(numColumns):
currentCol = colIndices[i]
initialCell = cellsPerColumn * currentCol
for j in range(cellsPerColumn):
subSpikeTrains[(cellsPerColumn*i) + j,:] = spikeTrains[initialCell + j,rnd:(rnd+timeWindow)]
return subSpikeTrains | [
"def",
"subSampleWholeColumn",
"(",
"spikeTrains",
",",
"colIndices",
",",
"cellsPerColumn",
",",
"currentTS",
",",
"timeWindow",
")",
":",
"numColumns",
"=",
"np",
".",
"shape",
"(",
"colIndices",
")",
"[",
"0",
"]",
"numCells",
"=",
"numColumns",
"*",
"cel... | Obtains subsample from matrix of spike trains by considering the cells in columns specified
by colIndices. Thus, it returns a matrix of spike trains of cells within the same column.
@param spikeTrains (array) array containing the spike trains of cells in the TM
@param colIndices (array) array containing the indices of columns whose spike trains should be sampled
@param cellsPerColumn (int) number of cells per column in the TM
@param currentTS (int) time-step upper bound of sample (sample will go from time-step 0 up to currentTS)
@param timeWindow (int) number of time-steps to sample from the spike trains
@return subSpikeTrains (array) spike train matrix sampled from the total spike train matrix | [
"Obtains",
"subsample",
"from",
"matrix",
"of",
"spike",
"trains",
"by",
"considering",
"the",
"cells",
"in",
"columns",
"specified",
"by",
"colIndices",
".",
"Thus",
"it",
"returns",
"a",
"matrix",
"of",
"spike",
"trains",
"of",
"cells",
"within",
"the",
"s... | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/neural_correlations_utils.py#L276-L325 | train | 198,903 |
numenta/htmresearch | htmresearch/support/neural_correlations_utils.py | computeEntropy | def computeEntropy(spikeTrains):
"""
Estimates entropy in spike trains.
@param spikeTrains (array) matrix of spike trains
@return entropy (float) entropy
"""
MIN_ACTIVATION_PROB = 0.000001
activationProb = np.mean(spikeTrains, 1)
activationProb[activationProb < MIN_ACTIVATION_PROB] = MIN_ACTIVATION_PROB
activationProb = activationProb / np.sum(activationProb)
entropy = -np.dot(activationProb, np.log2(activationProb))
return entropy | python | def computeEntropy(spikeTrains):
"""
Estimates entropy in spike trains.
@param spikeTrains (array) matrix of spike trains
@return entropy (float) entropy
"""
MIN_ACTIVATION_PROB = 0.000001
activationProb = np.mean(spikeTrains, 1)
activationProb[activationProb < MIN_ACTIVATION_PROB] = MIN_ACTIVATION_PROB
activationProb = activationProb / np.sum(activationProb)
entropy = -np.dot(activationProb, np.log2(activationProb))
return entropy | [
"def",
"computeEntropy",
"(",
"spikeTrains",
")",
":",
"MIN_ACTIVATION_PROB",
"=",
"0.000001",
"activationProb",
"=",
"np",
".",
"mean",
"(",
"spikeTrains",
",",
"1",
")",
"activationProb",
"[",
"activationProb",
"<",
"MIN_ACTIVATION_PROB",
"]",
"=",
"MIN_ACTIVATI... | Estimates entropy in spike trains.
@param spikeTrains (array) matrix of spike trains
@return entropy (float) entropy | [
"Estimates",
"entropy",
"in",
"spike",
"trains",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/neural_correlations_utils.py#L328-L340 | train | 198,904 |
numenta/htmresearch | htmresearch/support/neural_correlations_utils.py | computeISI | def computeISI(spikeTrains):
"""
Estimates the inter-spike interval from a spike train matrix.
@param spikeTrains (array) matrix of spike trains
@return isi (array) matrix with the inter-spike interval obtained from the spike train.
Each entry in this matrix represents the number of time-steps in-between 2 spikes
as the algorithm scans the spike train matrix.
"""
zeroCount = 0
isi = []
cells = 0
for i in range(np.shape(spikeTrains)[0]):
if cells > 0 and cells % 250 == 0:
print str(cells) + " cells processed"
for j in range(np.shape(spikeTrains)[1]):
if spikeTrains[i][j] == 0:
zeroCount += 1
elif zeroCount > 0:
isi.append(zeroCount)
zeroCount = 0
zeroCount = 0
cells += 1
print "**All cells processed**"
return isi | python | def computeISI(spikeTrains):
"""
Estimates the inter-spike interval from a spike train matrix.
@param spikeTrains (array) matrix of spike trains
@return isi (array) matrix with the inter-spike interval obtained from the spike train.
Each entry in this matrix represents the number of time-steps in-between 2 spikes
as the algorithm scans the spike train matrix.
"""
zeroCount = 0
isi = []
cells = 0
for i in range(np.shape(spikeTrains)[0]):
if cells > 0 and cells % 250 == 0:
print str(cells) + " cells processed"
for j in range(np.shape(spikeTrains)[1]):
if spikeTrains[i][j] == 0:
zeroCount += 1
elif zeroCount > 0:
isi.append(zeroCount)
zeroCount = 0
zeroCount = 0
cells += 1
print "**All cells processed**"
return isi | [
"def",
"computeISI",
"(",
"spikeTrains",
")",
":",
"zeroCount",
"=",
"0",
"isi",
"=",
"[",
"]",
"cells",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"np",
".",
"shape",
"(",
"spikeTrains",
")",
"[",
"0",
"]",
")",
":",
"if",
"cells",
">",
"0",
"a... | Estimates the inter-spike interval from a spike train matrix.
@param spikeTrains (array) matrix of spike trains
@return isi (array) matrix with the inter-spike interval obtained from the spike train.
Each entry in this matrix represents the number of time-steps in-between 2 spikes
as the algorithm scans the spike train matrix. | [
"Estimates",
"the",
"inter",
"-",
"spike",
"interval",
"from",
"a",
"spike",
"train",
"matrix",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/neural_correlations_utils.py#L343-L367 | train | 198,905 |
numenta/htmresearch | htmresearch/support/neural_correlations_utils.py | poissonSpikeGenerator | def poissonSpikeGenerator(firingRate, nBins, nTrials):
"""
Generates a Poisson spike train.
@param firingRate (int) firing rate of sample of Poisson spike trains to be generated
@param nBins (int) number of bins or timesteps for the Poisson spike train
@param nTrials (int) number of trials (or cells) in the spike train
@return poissonSpikeTrain (array)
"""
dt = 0.001 # we are simulating a ms as a single bin in a vector, ie 1sec = 1000bins
poissonSpikeTrain = np.zeros((nTrials, nBins), dtype = "uint32")
for i in range(nTrials):
for j in range(int(nBins)):
if random.random() < firingRate*dt:
poissonSpikeTrain[i,j] = 1
return poissonSpikeTrain | python | def poissonSpikeGenerator(firingRate, nBins, nTrials):
"""
Generates a Poisson spike train.
@param firingRate (int) firing rate of sample of Poisson spike trains to be generated
@param nBins (int) number of bins or timesteps for the Poisson spike train
@param nTrials (int) number of trials (or cells) in the spike train
@return poissonSpikeTrain (array)
"""
dt = 0.001 # we are simulating a ms as a single bin in a vector, ie 1sec = 1000bins
poissonSpikeTrain = np.zeros((nTrials, nBins), dtype = "uint32")
for i in range(nTrials):
for j in range(int(nBins)):
if random.random() < firingRate*dt:
poissonSpikeTrain[i,j] = 1
return poissonSpikeTrain | [
"def",
"poissonSpikeGenerator",
"(",
"firingRate",
",",
"nBins",
",",
"nTrials",
")",
":",
"dt",
"=",
"0.001",
"# we are simulating a ms as a single bin in a vector, ie 1sec = 1000bins",
"poissonSpikeTrain",
"=",
"np",
".",
"zeros",
"(",
"(",
"nTrials",
",",
"nBins",
... | Generates a Poisson spike train.
@param firingRate (int) firing rate of sample of Poisson spike trains to be generated
@param nBins (int) number of bins or timesteps for the Poisson spike train
@param nTrials (int) number of trials (or cells) in the spike train
@return poissonSpikeTrain (array) | [
"Generates",
"a",
"Poisson",
"spike",
"train",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/neural_correlations_utils.py#L370-L385 | train | 198,906 |
numenta/htmresearch | htmresearch/support/neural_correlations_utils.py | raster | def raster(event_times_list, color='k'):
"""
Creates a raster from spike trains.
@param event_times_list (array) matrix containing times in which a cell fired
@param color (string) color of spike in raster
@return ax (int) position of plot axes
"""
ax = plt.gca()
for ith, trial in enumerate(event_times_list):
plt.vlines(trial, ith + .5, ith + 1.5, color=color)
plt.ylim(.5, len(event_times_list) + .5)
return ax | python | def raster(event_times_list, color='k'):
"""
Creates a raster from spike trains.
@param event_times_list (array) matrix containing times in which a cell fired
@param color (string) color of spike in raster
@return ax (int) position of plot axes
"""
ax = plt.gca()
for ith, trial in enumerate(event_times_list):
plt.vlines(trial, ith + .5, ith + 1.5, color=color)
plt.ylim(.5, len(event_times_list) + .5)
return ax | [
"def",
"raster",
"(",
"event_times_list",
",",
"color",
"=",
"'k'",
")",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"for",
"ith",
",",
"trial",
"in",
"enumerate",
"(",
"event_times_list",
")",
":",
"plt",
".",
"vlines",
"(",
"trial",
",",
"ith",
... | Creates a raster from spike trains.
@param event_times_list (array) matrix containing times in which a cell fired
@param color (string) color of spike in raster
@return ax (int) position of plot axes | [
"Creates",
"a",
"raster",
"from",
"spike",
"trains",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/neural_correlations_utils.py#L388-L401 | train | 198,907 |
numenta/htmresearch | htmresearch/support/neural_correlations_utils.py | rasterPlot | def rasterPlot(spikeTrain, model):
"""
Plots raster and saves figure in working directory
@param spikeTrain (array) matrix of spike trains
@param model (string) string specifying the name of the origin of the spike trains
for the purpose of concatenating it to the filename (either TM or Poisson)
"""
nTrials = np.shape(spikeTrain)[0]
spikes = []
for i in range(nTrials):
spikes.append(spikeTrain[i].nonzero()[0].tolist())
plt.figure()
ax = raster(spikes)
plt.xlabel('Time')
plt.ylabel('Neuron')
# plt.show()
plt.savefig("raster" + str(model))
plt.close() | python | def rasterPlot(spikeTrain, model):
"""
Plots raster and saves figure in working directory
@param spikeTrain (array) matrix of spike trains
@param model (string) string specifying the name of the origin of the spike trains
for the purpose of concatenating it to the filename (either TM or Poisson)
"""
nTrials = np.shape(spikeTrain)[0]
spikes = []
for i in range(nTrials):
spikes.append(spikeTrain[i].nonzero()[0].tolist())
plt.figure()
ax = raster(spikes)
plt.xlabel('Time')
plt.ylabel('Neuron')
# plt.show()
plt.savefig("raster" + str(model))
plt.close() | [
"def",
"rasterPlot",
"(",
"spikeTrain",
",",
"model",
")",
":",
"nTrials",
"=",
"np",
".",
"shape",
"(",
"spikeTrain",
")",
"[",
"0",
"]",
"spikes",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"nTrials",
")",
":",
"spikes",
".",
"append",
"(",
... | Plots raster and saves figure in working directory
@param spikeTrain (array) matrix of spike trains
@param model (string) string specifying the name of the origin of the spike trains
for the purpose of concatenating it to the filename (either TM or Poisson) | [
"Plots",
"raster",
"and",
"saves",
"figure",
"in",
"working",
"directory"
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/neural_correlations_utils.py#L404-L422 | train | 198,908 |
numenta/htmresearch | htmresearch/support/neural_correlations_utils.py | saveTM | def saveTM(tm):
"""
Saves the temporal memory and the sequences generated for its training.
@param tm (TemporalMemory) temporal memory used during the experiment
"""
# Save the TM to a file for future use
proto1 = TemporalMemoryProto_capnp.TemporalMemoryProto.new_message()
tm.write(proto1)
# Write the proto to a file and read it back into a new proto
with open('tm.nta', 'wb') as f:
proto1.write(f) | python | def saveTM(tm):
"""
Saves the temporal memory and the sequences generated for its training.
@param tm (TemporalMemory) temporal memory used during the experiment
"""
# Save the TM to a file for future use
proto1 = TemporalMemoryProto_capnp.TemporalMemoryProto.new_message()
tm.write(proto1)
# Write the proto to a file and read it back into a new proto
with open('tm.nta', 'wb') as f:
proto1.write(f) | [
"def",
"saveTM",
"(",
"tm",
")",
":",
"# Save the TM to a file for future use",
"proto1",
"=",
"TemporalMemoryProto_capnp",
".",
"TemporalMemoryProto",
".",
"new_message",
"(",
")",
"tm",
".",
"write",
"(",
"proto1",
")",
"# Write the proto to a file and read it back into... | Saves the temporal memory and the sequences generated for its training.
@param tm (TemporalMemory) temporal memory used during the experiment | [
"Saves",
"the",
"temporal",
"memory",
"and",
"the",
"sequences",
"generated",
"for",
"its",
"training",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/neural_correlations_utils.py#L493-L504 | train | 198,909 |
numenta/htmresearch | htmresearch/support/csv_helper.py | mapLabelRefs | def mapLabelRefs(dataDict):
"""
Replace the label strings in dataDict with corresponding ints.
@return (tuple) (ordered list of category names, dataDict with names
replaced by array of category indices)
"""
labelRefs = [label for label in set(
itertools.chain.from_iterable([x[1] for x in dataDict.values()]))]
for recordNumber, data in dataDict.iteritems():
dataDict[recordNumber] = (data[0], numpy.array(
[labelRefs.index(label) for label in data[1]]), data[2])
return labelRefs, dataDict | python | def mapLabelRefs(dataDict):
"""
Replace the label strings in dataDict with corresponding ints.
@return (tuple) (ordered list of category names, dataDict with names
replaced by array of category indices)
"""
labelRefs = [label for label in set(
itertools.chain.from_iterable([x[1] for x in dataDict.values()]))]
for recordNumber, data in dataDict.iteritems():
dataDict[recordNumber] = (data[0], numpy.array(
[labelRefs.index(label) for label in data[1]]), data[2])
return labelRefs, dataDict | [
"def",
"mapLabelRefs",
"(",
"dataDict",
")",
":",
"labelRefs",
"=",
"[",
"label",
"for",
"label",
"in",
"set",
"(",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"[",
"x",
"[",
"1",
"]",
"for",
"x",
"in",
"dataDict",
".",
"values",
"(",
")",
... | Replace the label strings in dataDict with corresponding ints.
@return (tuple) (ordered list of category names, dataDict with names
replaced by array of category indices) | [
"Replace",
"the",
"label",
"strings",
"in",
"dataDict",
"with",
"corresponding",
"ints",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/csv_helper.py#L77-L91 | train | 198,910 |
numenta/htmresearch | htmresearch/support/csv_helper.py | bucketCSVs | def bucketCSVs(csvFile, bucketIdx=2):
"""Write the individual buckets in csvFile to their own CSV files."""
try:
with open(csvFile, "rU") as f:
reader = csv.reader(f)
headers = next(reader, None)
dataDict = OrderedDict()
for lineNumber, line in enumerate(reader):
if line[bucketIdx] in dataDict:
dataDict[line[bucketIdx]].append(line)
else:
# new bucket
dataDict[line[bucketIdx]] = [line]
except IOError as e:
print e
filePaths = []
for i, (_, lines) in enumerate(dataDict.iteritems()):
bucketFile = csvFile.replace(".", "_"+str(i)+".")
writeCSV(lines, headers, bucketFile)
filePaths.append(bucketFile)
return filePaths | python | def bucketCSVs(csvFile, bucketIdx=2):
"""Write the individual buckets in csvFile to their own CSV files."""
try:
with open(csvFile, "rU") as f:
reader = csv.reader(f)
headers = next(reader, None)
dataDict = OrderedDict()
for lineNumber, line in enumerate(reader):
if line[bucketIdx] in dataDict:
dataDict[line[bucketIdx]].append(line)
else:
# new bucket
dataDict[line[bucketIdx]] = [line]
except IOError as e:
print e
filePaths = []
for i, (_, lines) in enumerate(dataDict.iteritems()):
bucketFile = csvFile.replace(".", "_"+str(i)+".")
writeCSV(lines, headers, bucketFile)
filePaths.append(bucketFile)
return filePaths | [
"def",
"bucketCSVs",
"(",
"csvFile",
",",
"bucketIdx",
"=",
"2",
")",
":",
"try",
":",
"with",
"open",
"(",
"csvFile",
",",
"\"rU\"",
")",
"as",
"f",
":",
"reader",
"=",
"csv",
".",
"reader",
"(",
"f",
")",
"headers",
"=",
"next",
"(",
"reader",
... | Write the individual buckets in csvFile to their own CSV files. | [
"Write",
"the",
"individual",
"buckets",
"in",
"csvFile",
"to",
"their",
"own",
"CSV",
"files",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/csv_helper.py#L94-L116 | train | 198,911 |
numenta/htmresearch | htmresearch/support/csv_helper.py | readDir | def readDir(dirPath, numLabels, modify=False):
"""
Reads in data from a directory of CSV files; assumes the directory only
contains CSV files.
@param dirPath (str) Path to the directory.
@param numLabels (int) Number of columns of category labels.
@param modify (bool) Map the unix friendly category names
to the actual names. 0 -> /, _ -> " "
@return samplesDict (defaultdict) Keys are CSV names, values are
OrderedDicts, where the keys/values are as specified in readCSV().
"""
samplesDict = defaultdict(list)
for _, _, files in os.walk(dirPath):
for f in files:
basename, extension = os.path.splitext(os.path.basename(f))
if "." in basename and extension == ".csv":
category = basename.split(".")[-1]
if modify:
category = category.replace("0", "/")
category = category.replace("_", " ")
samplesDict[category] = readCSV(
os.path.join(dirPath, f), numLabels=numLabels)
return samplesDict | python | def readDir(dirPath, numLabels, modify=False):
"""
Reads in data from a directory of CSV files; assumes the directory only
contains CSV files.
@param dirPath (str) Path to the directory.
@param numLabels (int) Number of columns of category labels.
@param modify (bool) Map the unix friendly category names
to the actual names. 0 -> /, _ -> " "
@return samplesDict (defaultdict) Keys are CSV names, values are
OrderedDicts, where the keys/values are as specified in readCSV().
"""
samplesDict = defaultdict(list)
for _, _, files in os.walk(dirPath):
for f in files:
basename, extension = os.path.splitext(os.path.basename(f))
if "." in basename and extension == ".csv":
category = basename.split(".")[-1]
if modify:
category = category.replace("0", "/")
category = category.replace("_", " ")
samplesDict[category] = readCSV(
os.path.join(dirPath, f), numLabels=numLabels)
return samplesDict | [
"def",
"readDir",
"(",
"dirPath",
",",
"numLabels",
",",
"modify",
"=",
"False",
")",
":",
"samplesDict",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"_",
",",
"_",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"dirPath",
")",
":",
"for",
"f",
"in",... | Reads in data from a directory of CSV files; assumes the directory only
contains CSV files.
@param dirPath (str) Path to the directory.
@param numLabels (int) Number of columns of category labels.
@param modify (bool) Map the unix friendly category names
to the actual names. 0 -> /, _ -> " "
@return samplesDict (defaultdict) Keys are CSV names, values are
OrderedDicts, where the keys/values are as specified in readCSV(). | [
"Reads",
"in",
"data",
"from",
"a",
"directory",
"of",
"CSV",
"files",
";",
"assumes",
"the",
"directory",
"only",
"contains",
"CSV",
"files",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/csv_helper.py#L119-L144 | train | 198,912 |
numenta/htmresearch | htmresearch/support/csv_helper.py | writeCSV | def writeCSV(data, headers, csvFile):
"""Write data with column headers to a CSV."""
with open(csvFile, "wb") as f:
writer = csv.writer(f, delimiter=",")
writer.writerow(headers)
writer.writerows(data) | python | def writeCSV(data, headers, csvFile):
"""Write data with column headers to a CSV."""
with open(csvFile, "wb") as f:
writer = csv.writer(f, delimiter=",")
writer.writerow(headers)
writer.writerows(data) | [
"def",
"writeCSV",
"(",
"data",
",",
"headers",
",",
"csvFile",
")",
":",
"with",
"open",
"(",
"csvFile",
",",
"\"wb\"",
")",
"as",
"f",
":",
"writer",
"=",
"csv",
".",
"writer",
"(",
"f",
",",
"delimiter",
"=",
"\",\"",
")",
"writer",
".",
"writer... | Write data with column headers to a CSV. | [
"Write",
"data",
"with",
"column",
"headers",
"to",
"a",
"CSV",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/csv_helper.py#L147-L152 | train | 198,913 |
numenta/htmresearch | htmresearch/support/csv_helper.py | writeFromDict | def writeFromDict(dataDict, headers, csvFile):
"""
Write dictionary to a CSV, where keys are row numbers and values are a list.
"""
with open(csvFile, "wb") as f:
writer = csv.writer(f, delimiter=",")
writer.writerow(headers)
for row in sorted(dataDict.keys()):
writer.writerow(dataDict[row]) | python | def writeFromDict(dataDict, headers, csvFile):
"""
Write dictionary to a CSV, where keys are row numbers and values are a list.
"""
with open(csvFile, "wb") as f:
writer = csv.writer(f, delimiter=",")
writer.writerow(headers)
for row in sorted(dataDict.keys()):
writer.writerow(dataDict[row]) | [
"def",
"writeFromDict",
"(",
"dataDict",
",",
"headers",
",",
"csvFile",
")",
":",
"with",
"open",
"(",
"csvFile",
",",
"\"wb\"",
")",
"as",
"f",
":",
"writer",
"=",
"csv",
".",
"writer",
"(",
"f",
",",
"delimiter",
"=",
"\",\"",
")",
"writer",
".",
... | Write dictionary to a CSV, where keys are row numbers and values are a list. | [
"Write",
"dictionary",
"to",
"a",
"CSV",
"where",
"keys",
"are",
"row",
"numbers",
"and",
"values",
"are",
"a",
"list",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/csv_helper.py#L155-L163 | train | 198,914 |
numenta/htmresearch | htmresearch/support/csv_helper.py | readDataAndReshuffle | def readDataAndReshuffle(args, categoriesInOrderOfInterest=None):
"""
Read data file specified in args, optionally reshuffle categories, print out
some statistics, and return various data structures. This routine is pretty
specific and only used in some simple test scripts.
categoriesInOrderOfInterest (list) Optional list of integers representing
the priority order of various categories.
The categories in the original data file
will be reshuffled to the order in this
array, up to args.numLabels, if specified.
Returns the tuple:
(dataset, labelRefs, documentCategoryMap, documentTextMap)
Return format:
dataset = [
["fox eats carrots", [0], docId],
["fox eats peppers", [0], docId],
["carrots are healthy", [1], docId],
["peppers is healthy", [1], docId],
]
labelRefs = [Category0Name, Category1Name, ...]
documentCategoryMap = {
docId: [categoryIndex0, categoryIndex1, ...],
docId: [categoryIndex0, categoryIndex1, ...],
:
}
documentTextMap = {
docId: documentText,
docId: documentText,
:
}
"""
# Read data
dataDict = readCSV(args.dataPath, 1)
labelRefs, dataDict = mapLabelRefs(dataDict)
if "numLabels" in args:
numLabels = args.numLabels
else:
numLabels = len(labelRefs)
if categoriesInOrderOfInterest is None:
categoriesInOrderOfInterest = range(0,numLabels)
else:
categoriesInOrderOfInterest=categoriesInOrderOfInterest[0:numLabels]
# Select data based on categories of interest. Shift category indices down
# so we go from 0 to numLabels-1
dataSet = []
documentTextMap = {}
counts = numpy.zeros(len(labelRefs))
for document in dataDict.itervalues():
try:
docId = int(document[2])
except:
raise RuntimeError("docId "+str(docId)+" is not an integer")
oldCategoryIndex = document[1][0]
documentTextMap[docId] = document[0]
if oldCategoryIndex in categoriesInOrderOfInterest:
newIndex = categoriesInOrderOfInterest.index(oldCategoryIndex)
dataSet.append([document[0], [newIndex], docId])
counts[newIndex] += 1
# For each document, figure out which categories it belongs to
# Include the shifted category index
documentCategoryMap = {}
for doc in dataDict.iteritems():
docId = int(doc[1][2])
oldCategoryIndex = doc[1][1][0]
if oldCategoryIndex in categoriesInOrderOfInterest:
newIndex = categoriesInOrderOfInterest.index(oldCategoryIndex)
v = documentCategoryMap.get(docId, [])
v.append(newIndex)
documentCategoryMap[docId] = v
labelRefs = [labelRefs[i] for i in categoriesInOrderOfInterest]
print "Total number of unique documents",len(documentCategoryMap)
print "Category counts: ",counts
print "Categories in training/test data:", labelRefs
return dataSet, labelRefs, documentCategoryMap, documentTextMap | python | def readDataAndReshuffle(args, categoriesInOrderOfInterest=None):
"""
Read data file specified in args, optionally reshuffle categories, print out
some statistics, and return various data structures. This routine is pretty
specific and only used in some simple test scripts.
categoriesInOrderOfInterest (list) Optional list of integers representing
the priority order of various categories.
The categories in the original data file
will be reshuffled to the order in this
array, up to args.numLabels, if specified.
Returns the tuple:
(dataset, labelRefs, documentCategoryMap, documentTextMap)
Return format:
dataset = [
["fox eats carrots", [0], docId],
["fox eats peppers", [0], docId],
["carrots are healthy", [1], docId],
["peppers is healthy", [1], docId],
]
labelRefs = [Category0Name, Category1Name, ...]
documentCategoryMap = {
docId: [categoryIndex0, categoryIndex1, ...],
docId: [categoryIndex0, categoryIndex1, ...],
:
}
documentTextMap = {
docId: documentText,
docId: documentText,
:
}
"""
# Read data
dataDict = readCSV(args.dataPath, 1)
labelRefs, dataDict = mapLabelRefs(dataDict)
if "numLabels" in args:
numLabels = args.numLabels
else:
numLabels = len(labelRefs)
if categoriesInOrderOfInterest is None:
categoriesInOrderOfInterest = range(0,numLabels)
else:
categoriesInOrderOfInterest=categoriesInOrderOfInterest[0:numLabels]
# Select data based on categories of interest. Shift category indices down
# so we go from 0 to numLabels-1
dataSet = []
documentTextMap = {}
counts = numpy.zeros(len(labelRefs))
for document in dataDict.itervalues():
try:
docId = int(document[2])
except:
raise RuntimeError("docId "+str(docId)+" is not an integer")
oldCategoryIndex = document[1][0]
documentTextMap[docId] = document[0]
if oldCategoryIndex in categoriesInOrderOfInterest:
newIndex = categoriesInOrderOfInterest.index(oldCategoryIndex)
dataSet.append([document[0], [newIndex], docId])
counts[newIndex] += 1
# For each document, figure out which categories it belongs to
# Include the shifted category index
documentCategoryMap = {}
for doc in dataDict.iteritems():
docId = int(doc[1][2])
oldCategoryIndex = doc[1][1][0]
if oldCategoryIndex in categoriesInOrderOfInterest:
newIndex = categoriesInOrderOfInterest.index(oldCategoryIndex)
v = documentCategoryMap.get(docId, [])
v.append(newIndex)
documentCategoryMap[docId] = v
labelRefs = [labelRefs[i] for i in categoriesInOrderOfInterest]
print "Total number of unique documents",len(documentCategoryMap)
print "Category counts: ",counts
print "Categories in training/test data:", labelRefs
return dataSet, labelRefs, documentCategoryMap, documentTextMap | [
"def",
"readDataAndReshuffle",
"(",
"args",
",",
"categoriesInOrderOfInterest",
"=",
"None",
")",
":",
"# Read data",
"dataDict",
"=",
"readCSV",
"(",
"args",
".",
"dataPath",
",",
"1",
")",
"labelRefs",
",",
"dataDict",
"=",
"mapLabelRefs",
"(",
"dataDict",
"... | Read data file specified in args, optionally reshuffle categories, print out
some statistics, and return various data structures. This routine is pretty
specific and only used in some simple test scripts.
categoriesInOrderOfInterest (list) Optional list of integers representing
the priority order of various categories.
The categories in the original data file
will be reshuffled to the order in this
array, up to args.numLabels, if specified.
Returns the tuple:
(dataset, labelRefs, documentCategoryMap, documentTextMap)
Return format:
dataset = [
["fox eats carrots", [0], docId],
["fox eats peppers", [0], docId],
["carrots are healthy", [1], docId],
["peppers is healthy", [1], docId],
]
labelRefs = [Category0Name, Category1Name, ...]
documentCategoryMap = {
docId: [categoryIndex0, categoryIndex1, ...],
docId: [categoryIndex0, categoryIndex1, ...],
:
}
documentTextMap = {
docId: documentText,
docId: documentText,
:
} | [
"Read",
"data",
"file",
"specified",
"in",
"args",
"optionally",
"reshuffle",
"categories",
"print",
"out",
"some",
"statistics",
"and",
"return",
"various",
"data",
"structures",
".",
"This",
"routine",
"is",
"pretty",
"specific",
"and",
"only",
"used",
"in",
... | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/csv_helper.py#L166-L252 | train | 198,915 |
numenta/htmresearch | htmresearch/algorithms/temporal_memory_factory.py | createModel | def createModel(modelName, **kwargs):
"""
Return a classification model of the appropriate type. The model could be any
supported subclass of ClassficationModel based on modelName.
@param modelName (str) A supported temporal memory type
@param kwargs (dict) Constructor argument for the class that will be
instantiated. Keyword parameters specific to each
model type should be passed in here.
"""
if modelName not in TemporalMemoryTypes.getTypes():
raise RuntimeError("Unknown model type: " + modelName)
return getattr(TemporalMemoryTypes, modelName)(**kwargs) | python | def createModel(modelName, **kwargs):
"""
Return a classification model of the appropriate type. The model could be any
supported subclass of ClassficationModel based on modelName.
@param modelName (str) A supported temporal memory type
@param kwargs (dict) Constructor argument for the class that will be
instantiated. Keyword parameters specific to each
model type should be passed in here.
"""
if modelName not in TemporalMemoryTypes.getTypes():
raise RuntimeError("Unknown model type: " + modelName)
return getattr(TemporalMemoryTypes, modelName)(**kwargs) | [
"def",
"createModel",
"(",
"modelName",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"modelName",
"not",
"in",
"TemporalMemoryTypes",
".",
"getTypes",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Unknown model type: \"",
"+",
"modelName",
")",
"return",
"getatt... | Return a classification model of the appropriate type. The model could be any
supported subclass of ClassficationModel based on modelName.
@param modelName (str) A supported temporal memory type
@param kwargs (dict) Constructor argument for the class that will be
instantiated. Keyword parameters specific to each
model type should be passed in here. | [
"Return",
"a",
"classification",
"model",
"of",
"the",
"appropriate",
"type",
".",
"The",
"model",
"could",
"be",
"any",
"supported",
"subclass",
"of",
"ClassficationModel",
"based",
"on",
"modelName",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/temporal_memory_factory.py#L77-L92 | train | 198,916 |
numenta/htmresearch | htmresearch/algorithms/temporal_memory_factory.py | getConstructorArguments | def getConstructorArguments(modelName):
"""
Return constructor arguments and associated default values for the
given model type.
@param modelName (str) A supported temporal memory type
@return argNames (list of str) a list of strings corresponding to constructor
arguments for the given model type, excluding
'self'.
@return defaults (list) a list of default values for each argument
"""
if modelName not in TemporalMemoryTypes.getTypes():
raise RuntimeError("Unknown model type: " + modelName)
argspec = inspect.getargspec(
getattr(TemporalMemoryTypes, modelName).__init__)
return (argspec.args[1:], argspec.defaults) | python | def getConstructorArguments(modelName):
"""
Return constructor arguments and associated default values for the
given model type.
@param modelName (str) A supported temporal memory type
@return argNames (list of str) a list of strings corresponding to constructor
arguments for the given model type, excluding
'self'.
@return defaults (list) a list of default values for each argument
"""
if modelName not in TemporalMemoryTypes.getTypes():
raise RuntimeError("Unknown model type: " + modelName)
argspec = inspect.getargspec(
getattr(TemporalMemoryTypes, modelName).__init__)
return (argspec.args[1:], argspec.defaults) | [
"def",
"getConstructorArguments",
"(",
"modelName",
")",
":",
"if",
"modelName",
"not",
"in",
"TemporalMemoryTypes",
".",
"getTypes",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Unknown model type: \"",
"+",
"modelName",
")",
"argspec",
"=",
"inspect",
".",
... | Return constructor arguments and associated default values for the
given model type.
@param modelName (str) A supported temporal memory type
@return argNames (list of str) a list of strings corresponding to constructor
arguments for the given model type, excluding
'self'.
@return defaults (list) a list of default values for each argument | [
"Return",
"constructor",
"arguments",
"and",
"associated",
"default",
"values",
"for",
"the",
"given",
"model",
"type",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/temporal_memory_factory.py#L95-L113 | train | 198,917 |
numenta/htmresearch | htmresearch/algorithms/temporal_memory_factory.py | TemporalMemoryTypes.getTypes | def getTypes(cls):
""" Get sequence of acceptable model types. Iterates through class
attributes and separates the user-defined enumerations from the default
attributes implicit to Python classes. i.e. this function returns the names
of the attributes explicitly defined above.
"""
for attrName in dir(cls):
attrValue = getattr(cls, attrName)
if (isinstance(attrValue, type)):
yield attrName | python | def getTypes(cls):
""" Get sequence of acceptable model types. Iterates through class
attributes and separates the user-defined enumerations from the default
attributes implicit to Python classes. i.e. this function returns the names
of the attributes explicitly defined above.
"""
for attrName in dir(cls):
attrValue = getattr(cls, attrName)
if (isinstance(attrValue, type)):
yield attrName | [
"def",
"getTypes",
"(",
"cls",
")",
":",
"for",
"attrName",
"in",
"dir",
"(",
"cls",
")",
":",
"attrValue",
"=",
"getattr",
"(",
"cls",
",",
"attrName",
")",
"if",
"(",
"isinstance",
"(",
"attrValue",
",",
"type",
")",
")",
":",
"yield",
"attrName"
] | Get sequence of acceptable model types. Iterates through class
attributes and separates the user-defined enumerations from the default
attributes implicit to Python classes. i.e. this function returns the names
of the attributes explicitly defined above. | [
"Get",
"sequence",
"of",
"acceptable",
"model",
"types",
".",
"Iterates",
"through",
"class",
"attributes",
"and",
"separates",
"the",
"user",
"-",
"defined",
"enumerations",
"from",
"the",
"default",
"attributes",
"implicit",
"to",
"Python",
"classes",
".",
"i"... | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/temporal_memory_factory.py#L64-L74 | train | 198,918 |
numenta/htmresearch | htmresearch/frameworks/poirazi_neuron_model/neuron_model.py | Matrix_Neuron.initialize_dendrites | def initialize_dendrites(self):
"""
Initialize all the dendrites of the neuron to a set of random connections
"""
# Wipe any preexisting connections by creating a new connection matrix
self.dendrites = SM32()
self.dendrites.reshape(self.dim, self.num_dendrites)
for row in range(self.num_dendrites):
synapses = numpy.random.choice(self.dim, self.dendrite_length, replace = False)
for synapse in synapses:
self.dendrites[synapse, row] = 1 | python | def initialize_dendrites(self):
"""
Initialize all the dendrites of the neuron to a set of random connections
"""
# Wipe any preexisting connections by creating a new connection matrix
self.dendrites = SM32()
self.dendrites.reshape(self.dim, self.num_dendrites)
for row in range(self.num_dendrites):
synapses = numpy.random.choice(self.dim, self.dendrite_length, replace = False)
for synapse in synapses:
self.dendrites[synapse, row] = 1 | [
"def",
"initialize_dendrites",
"(",
"self",
")",
":",
"# Wipe any preexisting connections by creating a new connection matrix",
"self",
".",
"dendrites",
"=",
"SM32",
"(",
")",
"self",
".",
"dendrites",
".",
"reshape",
"(",
"self",
".",
"dim",
",",
"self",
".",
"n... | Initialize all the dendrites of the neuron to a set of random connections | [
"Initialize",
"all",
"the",
"dendrites",
"of",
"the",
"neuron",
"to",
"a",
"set",
"of",
"random",
"connections"
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/poirazi_neuron_model/neuron_model.py#L77-L88 | train | 198,919 |
numenta/htmresearch | htmresearch/frameworks/poirazi_neuron_model/neuron_model.py | Matrix_Neuron.calculate_activation | def calculate_activation(self, datapoint):
"""
Only for a single datapoint
"""
activations = datapoint * self.dendrites
activations = self.nonlinearity(activations)
return activations.sum() | python | def calculate_activation(self, datapoint):
"""
Only for a single datapoint
"""
activations = datapoint * self.dendrites
activations = self.nonlinearity(activations)
return activations.sum() | [
"def",
"calculate_activation",
"(",
"self",
",",
"datapoint",
")",
":",
"activations",
"=",
"datapoint",
"*",
"self",
".",
"dendrites",
"activations",
"=",
"self",
".",
"nonlinearity",
"(",
"activations",
")",
"return",
"activations",
".",
"sum",
"(",
")"
] | Only for a single datapoint | [
"Only",
"for",
"a",
"single",
"datapoint"
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/poirazi_neuron_model/neuron_model.py#L95-L102 | train | 198,920 |
numenta/htmresearch | htmresearch/frameworks/poirazi_neuron_model/neuron_model.py | Matrix_Neuron.HTM_style_initialize_on_data | def HTM_style_initialize_on_data(self, data, labels):
"""
Uses a style of initialization inspired by the temporal memory. When a new
positive example is found, a dendrite is chosen and a number of synapses are
created to the example.
This works intelligently with an amount of data larger than the number of
available dendrites. In this case, data is clustered, and then similar
datapoints are allotted to shared dendrites, with as many overlapping bits
as possible chosen. In practice, it is still better to simply allocate
enough dendrites to have one per datapoint, but this method at least allows
initialization to work on larger amounts of data.
"""
current_dendrite = 0
self.dendrites = SM32()
self.dendrites.reshape(self.dim, self.num_dendrites)
# We want to avoid training on any negative examples
data = copy.deepcopy(data)
data.deleteRows([i for i, v in enumerate(labels) if v != 1])
if data.nRows() > self.num_dendrites:
print "Neuron using clustering to initialize dendrites"
data = (data.toDense())
model = KMeans(n_clusters = self.num_dendrites, n_jobs=1)
clusters = model.fit_predict(data)
multisets = [[Counter(), []] for i in range(self.num_dendrites)]
sparse_data = [[i for i, d in enumerate(datapoint) if d == 1] for datapoint in data]
for datapoint, cluster in zip(sparse_data, clusters):
multisets[cluster][0] = multisets[cluster][0] + Counter(datapoint)
multisets[cluster][1].append(set(datapoint))
for i, multiset in enumerate(multisets):
shared_elements = set(map(lambda x: x[0], filter(lambda x: x[1] > 1, multiset[0].most_common(self.dendrite_length))))
dendrite_connections = shared_elements
while len(shared_elements) < self.dendrite_length:
most_distant_point = multiset[1][numpy.argmin([len(dendrite_connections.intersection(point)) for point in multiset[1]])]
new_connection = random.sample(most_distant_point - dendrite_connections, 1)[0]
dendrite_connections.add(new_connection)
for synapse in dendrite_connections:
self.dendrites[synapse, current_dendrite] = 1.
current_dendrite += 1
else:
for i in range(data.nRows()):
ones = data.rowNonZeros(i)[0]
dendrite_connections = numpy.random.choice(ones, size = self.dendrite_length, replace = False)
for synapse in dendrite_connections:
self.dendrites[synapse, current_dendrite] = 1.
current_dendrite += 1
self.initialize_permanences() | python | def HTM_style_initialize_on_data(self, data, labels):
"""
Uses a style of initialization inspired by the temporal memory. When a new
positive example is found, a dendrite is chosen and a number of synapses are
created to the example.
This works intelligently with an amount of data larger than the number of
available dendrites. In this case, data is clustered, and then similar
datapoints are allotted to shared dendrites, with as many overlapping bits
as possible chosen. In practice, it is still better to simply allocate
enough dendrites to have one per datapoint, but this method at least allows
initialization to work on larger amounts of data.
"""
current_dendrite = 0
self.dendrites = SM32()
self.dendrites.reshape(self.dim, self.num_dendrites)
# We want to avoid training on any negative examples
data = copy.deepcopy(data)
data.deleteRows([i for i, v in enumerate(labels) if v != 1])
if data.nRows() > self.num_dendrites:
print "Neuron using clustering to initialize dendrites"
data = (data.toDense())
model = KMeans(n_clusters = self.num_dendrites, n_jobs=1)
clusters = model.fit_predict(data)
multisets = [[Counter(), []] for i in range(self.num_dendrites)]
sparse_data = [[i for i, d in enumerate(datapoint) if d == 1] for datapoint in data]
for datapoint, cluster in zip(sparse_data, clusters):
multisets[cluster][0] = multisets[cluster][0] + Counter(datapoint)
multisets[cluster][1].append(set(datapoint))
for i, multiset in enumerate(multisets):
shared_elements = set(map(lambda x: x[0], filter(lambda x: x[1] > 1, multiset[0].most_common(self.dendrite_length))))
dendrite_connections = shared_elements
while len(shared_elements) < self.dendrite_length:
most_distant_point = multiset[1][numpy.argmin([len(dendrite_connections.intersection(point)) for point in multiset[1]])]
new_connection = random.sample(most_distant_point - dendrite_connections, 1)[0]
dendrite_connections.add(new_connection)
for synapse in dendrite_connections:
self.dendrites[synapse, current_dendrite] = 1.
current_dendrite += 1
else:
for i in range(data.nRows()):
ones = data.rowNonZeros(i)[0]
dendrite_connections = numpy.random.choice(ones, size = self.dendrite_length, replace = False)
for synapse in dendrite_connections:
self.dendrites[synapse, current_dendrite] = 1.
current_dendrite += 1
self.initialize_permanences() | [
"def",
"HTM_style_initialize_on_data",
"(",
"self",
",",
"data",
",",
"labels",
")",
":",
"current_dendrite",
"=",
"0",
"self",
".",
"dendrites",
"=",
"SM32",
"(",
")",
"self",
".",
"dendrites",
".",
"reshape",
"(",
"self",
".",
"dim",
",",
"self",
".",
... | Uses a style of initialization inspired by the temporal memory. When a new
positive example is found, a dendrite is chosen and a number of synapses are
created to the example.
This works intelligently with an amount of data larger than the number of
available dendrites. In this case, data is clustered, and then similar
datapoints are allotted to shared dendrites, with as many overlapping bits
as possible chosen. In practice, it is still better to simply allocate
enough dendrites to have one per datapoint, but this method at least allows
initialization to work on larger amounts of data. | [
"Uses",
"a",
"style",
"of",
"initialization",
"inspired",
"by",
"the",
"temporal",
"memory",
".",
"When",
"a",
"new",
"positive",
"example",
"is",
"found",
"a",
"dendrite",
"is",
"chosen",
"and",
"a",
"number",
"of",
"synapses",
"are",
"created",
"to",
"th... | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/poirazi_neuron_model/neuron_model.py#L110-L164 | train | 198,921 |
numenta/htmresearch | htmresearch/frameworks/poirazi_neuron_model/neuron_model.py | Matrix_Neuron.HTM_style_train_on_datapoint | def HTM_style_train_on_datapoint(self, datapoint, label):
"""
Run a version of permanence-based training on a datapoint. Due to the fixed dendrite count and dendrite length,
we are forced to more efficiently use each synapse, deleting synapses and resetting them if they are not found useful.
"""
activations = datapoint * self.dendrites
self.nonlinearity(activations)
#activations will quite likely still be sparse if using a threshold nonlinearity, so want to keep it sparse
activation = numpy.sign(activations.sum())
if label >= 1 and activation >= 0.5:
strongest_branch = activations.rowMax(0)[0]
datapoint.transpose()
inc_vector = self.dendrites.getSlice(0, self.dim, strongest_branch, strongest_branch + 1) * self.permanence_increment
inc_vector.elementNZMultiply(datapoint)
dec_vector = self.dendrites.getSlice(0, self.dim, strongest_branch, strongest_branch + 1) * self.permanence_decrement
dec_vector.elementNZMultiply(1 - datapoint)
self.permanences.setSlice(0, strongest_branch, self.permanences.getSlice(0, self.dim, strongest_branch, strongest_branch + 1) + inc_vector - dec_vector)
positions, scores = self.permanences.colNonZeros(strongest_branch)[0], self.permanences.colNonZeros(strongest_branch)[1]
for position, score in zip(positions, scores):
if score < self.permanence_threshold:
self.dendrites[position, strongest_branch] = 0
self.permanences[position, strongest_branch] = 0
new_connection = random.sample(set(datapoint.colNonZeros(0)[0]) - set(self.dendrites.colNonZeros(strongest_branch)[0]), 1)[0]
self.dendrites[new_connection, strongest_branch] = 1.
self.permanences[new_connection, strongest_branch] = self.initial_permanence
elif label < 1 and activation >= 0.5:
# Need to weaken some connections
strongest_branch = activations.rowMax(0)[0]
dec_vector = self.dendrites.getSlice(0, self.dim, strongest_branch, strongest_branch + 1) * self.permanence_decrement
datapoint.transpose()
dec_vector.elementNZMultiply(datapoint)
self.permanences.setSlice(0, strongest_branch, self.permanences.getSlice(0, self.dim, strongest_branch, strongest_branch + 1) - dec_vector)
elif label >= 1 and activation < 0.5:
# Need to create some new connections
weakest_branch = numpy.argmin(self.permanences.colSums())
if numpy.median(self.permanences.getCol(weakest_branch)) < self.permanence_threshold:
self.permanences.setColToZero(weakest_branch)
self.dendrites.setColToZero(weakest_branch)
ones = datapoint.rowNonZeros(0)[0]
dendrite_connections = numpy.random.choice(ones, size = self.dendrite_length, replace = False)
for synapse in dendrite_connections:
self.dendrites[synapse, weakest_branch] = 1.
self.permanences[synapse, weakest_branch] = self.initial_permanence | python | def HTM_style_train_on_datapoint(self, datapoint, label):
"""
Run a version of permanence-based training on a datapoint. Due to the fixed dendrite count and dendrite length,
we are forced to more efficiently use each synapse, deleting synapses and resetting them if they are not found useful.
"""
activations = datapoint * self.dendrites
self.nonlinearity(activations)
#activations will quite likely still be sparse if using a threshold nonlinearity, so want to keep it sparse
activation = numpy.sign(activations.sum())
if label >= 1 and activation >= 0.5:
strongest_branch = activations.rowMax(0)[0]
datapoint.transpose()
inc_vector = self.dendrites.getSlice(0, self.dim, strongest_branch, strongest_branch + 1) * self.permanence_increment
inc_vector.elementNZMultiply(datapoint)
dec_vector = self.dendrites.getSlice(0, self.dim, strongest_branch, strongest_branch + 1) * self.permanence_decrement
dec_vector.elementNZMultiply(1 - datapoint)
self.permanences.setSlice(0, strongest_branch, self.permanences.getSlice(0, self.dim, strongest_branch, strongest_branch + 1) + inc_vector - dec_vector)
positions, scores = self.permanences.colNonZeros(strongest_branch)[0], self.permanences.colNonZeros(strongest_branch)[1]
for position, score in zip(positions, scores):
if score < self.permanence_threshold:
self.dendrites[position, strongest_branch] = 0
self.permanences[position, strongest_branch] = 0
new_connection = random.sample(set(datapoint.colNonZeros(0)[0]) - set(self.dendrites.colNonZeros(strongest_branch)[0]), 1)[0]
self.dendrites[new_connection, strongest_branch] = 1.
self.permanences[new_connection, strongest_branch] = self.initial_permanence
elif label < 1 and activation >= 0.5:
# Need to weaken some connections
strongest_branch = activations.rowMax(0)[0]
dec_vector = self.dendrites.getSlice(0, self.dim, strongest_branch, strongest_branch + 1) * self.permanence_decrement
datapoint.transpose()
dec_vector.elementNZMultiply(datapoint)
self.permanences.setSlice(0, strongest_branch, self.permanences.getSlice(0, self.dim, strongest_branch, strongest_branch + 1) - dec_vector)
elif label >= 1 and activation < 0.5:
# Need to create some new connections
weakest_branch = numpy.argmin(self.permanences.colSums())
if numpy.median(self.permanences.getCol(weakest_branch)) < self.permanence_threshold:
self.permanences.setColToZero(weakest_branch)
self.dendrites.setColToZero(weakest_branch)
ones = datapoint.rowNonZeros(0)[0]
dendrite_connections = numpy.random.choice(ones, size = self.dendrite_length, replace = False)
for synapse in dendrite_connections:
self.dendrites[synapse, weakest_branch] = 1.
self.permanences[synapse, weakest_branch] = self.initial_permanence | [
"def",
"HTM_style_train_on_datapoint",
"(",
"self",
",",
"datapoint",
",",
"label",
")",
":",
"activations",
"=",
"datapoint",
"*",
"self",
".",
"dendrites",
"self",
".",
"nonlinearity",
"(",
"activations",
")",
"#activations will quite likely still be sparse if using a... | Run a version of permanence-based training on a datapoint. Due to the fixed dendrite count and dendrite length,
we are forced to more efficiently use each synapse, deleting synapses and resetting them if they are not found useful. | [
"Run",
"a",
"version",
"of",
"permanence",
"-",
"based",
"training",
"on",
"a",
"datapoint",
".",
"Due",
"to",
"the",
"fixed",
"dendrite",
"count",
"and",
"dendrite",
"length",
"we",
"are",
"forced",
"to",
"more",
"efficiently",
"use",
"each",
"synapse",
"... | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/poirazi_neuron_model/neuron_model.py#L226-L282 | train | 198,922 |
numenta/htmresearch | htmresearch/regions/TemporalPoolerRegion.py | TemporalPoolerRegion.initialize | def initialize(self):
"""
Initialize the self._poolerClass
"""
# Retrieve the necessary extra arguments that were handled automatically
autoArgs = {name: getattr(self, name) for name in self._poolerArgNames}
autoArgs["inputDimensions"] = [self._inputWidth]
autoArgs["columnDimensions"] = [self._columnCount]
autoArgs["potentialRadius"] = self._inputWidth
autoArgs["historyLength"] = self._historyLength
autoArgs["minHistory"] = self._minHistory
# Allocate the pooler
self._pooler = self._poolerClass(**autoArgs) | python | def initialize(self):
"""
Initialize the self._poolerClass
"""
# Retrieve the necessary extra arguments that were handled automatically
autoArgs = {name: getattr(self, name) for name in self._poolerArgNames}
autoArgs["inputDimensions"] = [self._inputWidth]
autoArgs["columnDimensions"] = [self._columnCount]
autoArgs["potentialRadius"] = self._inputWidth
autoArgs["historyLength"] = self._historyLength
autoArgs["minHistory"] = self._minHistory
# Allocate the pooler
self._pooler = self._poolerClass(**autoArgs) | [
"def",
"initialize",
"(",
"self",
")",
":",
"# Retrieve the necessary extra arguments that were handled automatically",
"autoArgs",
"=",
"{",
"name",
":",
"getattr",
"(",
"self",
",",
"name",
")",
"for",
"name",
"in",
"self",
".",
"_poolerArgNames",
"}",
"autoArgs",... | Initialize the self._poolerClass | [
"Initialize",
"the",
"self",
".",
"_poolerClass"
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/regions/TemporalPoolerRegion.py#L311-L325 | train | 198,923 |
numenta/htmresearch | htmresearch/regions/TemporalPoolerRegion.py | TemporalPoolerRegion.compute | def compute(self, inputs, outputs):
"""
Run one iteration of TemporalPoolerRegion's 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 pooled
representation to this point and any history will then be reset. The output
at the next compute will start fresh.
"""
resetSignal = False
if 'resetIn' in inputs:
if len(inputs['resetIn']) != 1:
raise Exception("resetIn has invalid length")
if inputs['resetIn'][0] != 0:
resetSignal = True
outputs["mostActiveCells"][:] = numpy.zeros(
self._columnCount, dtype=GetNTAReal())
if self._poolerType == "simpleUnion":
self._pooler.unionIntoArray(inputs["activeCells"],
outputs["mostActiveCells"],
forceOutput = resetSignal)
else:
predictedActiveCells = inputs["predictedActiveCells"] if (
"predictedActiveCells" in inputs) else numpy.zeros(self._inputWidth,
dtype=uintDType)
mostActiveCellsIndices = self._pooler.compute(inputs["activeCells"],
predictedActiveCells,
self.learningMode)
outputs["mostActiveCells"][mostActiveCellsIndices] = 1
if resetSignal:
self.reset() | python | def compute(self, inputs, outputs):
"""
Run one iteration of TemporalPoolerRegion's 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 pooled
representation to this point and any history will then be reset. The output
at the next compute will start fresh.
"""
resetSignal = False
if 'resetIn' in inputs:
if len(inputs['resetIn']) != 1:
raise Exception("resetIn has invalid length")
if inputs['resetIn'][0] != 0:
resetSignal = True
outputs["mostActiveCells"][:] = numpy.zeros(
self._columnCount, dtype=GetNTAReal())
if self._poolerType == "simpleUnion":
self._pooler.unionIntoArray(inputs["activeCells"],
outputs["mostActiveCells"],
forceOutput = resetSignal)
else:
predictedActiveCells = inputs["predictedActiveCells"] if (
"predictedActiveCells" in inputs) else numpy.zeros(self._inputWidth,
dtype=uintDType)
mostActiveCellsIndices = self._pooler.compute(inputs["activeCells"],
predictedActiveCells,
self.learningMode)
outputs["mostActiveCells"][mostActiveCellsIndices] = 1
if resetSignal:
self.reset() | [
"def",
"compute",
"(",
"self",
",",
"inputs",
",",
"outputs",
")",
":",
"resetSignal",
"=",
"False",
"if",
"'resetIn'",
"in",
"inputs",
":",
"if",
"len",
"(",
"inputs",
"[",
"'resetIn'",
"]",
")",
"!=",
"1",
":",
"raise",
"Exception",
"(",
"\"resetIn h... | Run one iteration of TemporalPoolerRegion's 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 pooled
representation to this point and any history will then be reset. The output
at the next compute will start fresh. | [
"Run",
"one",
"iteration",
"of",
"TemporalPoolerRegion",
"s",
"compute",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/regions/TemporalPoolerRegion.py#L328-L365 | train | 198,924 |
numenta/htmresearch | htmresearch/regions/TemporalPoolerRegion.py | TemporalPoolerRegion.getSpec | def getSpec(cls):
"""
Return the Spec for TemporalPoolerRegion.
The parameters collection is constructed based on the parameters specified
by the various components (poolerSpec and otherSpec)
"""
spec = cls.getBaseSpec()
p, o = _getAdditionalSpecs()
spec["parameters"].update(p)
spec["parameters"].update(o)
return spec | python | def getSpec(cls):
"""
Return the Spec for TemporalPoolerRegion.
The parameters collection is constructed based on the parameters specified
by the various components (poolerSpec and otherSpec)
"""
spec = cls.getBaseSpec()
p, o = _getAdditionalSpecs()
spec["parameters"].update(p)
spec["parameters"].update(o)
return spec | [
"def",
"getSpec",
"(",
"cls",
")",
":",
"spec",
"=",
"cls",
".",
"getBaseSpec",
"(",
")",
"p",
",",
"o",
"=",
"_getAdditionalSpecs",
"(",
")",
"spec",
"[",
"\"parameters\"",
"]",
".",
"update",
"(",
"p",
")",
"spec",
"[",
"\"parameters\"",
"]",
".",
... | Return the Spec for TemporalPoolerRegion.
The parameters collection is constructed based on the parameters specified
by the various components (poolerSpec and otherSpec) | [
"Return",
"the",
"Spec",
"for",
"TemporalPoolerRegion",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/regions/TemporalPoolerRegion.py#L439-L451 | train | 198,925 |
numenta/htmresearch | projects/union_path_integration/plot_comparison.py | computeCapacity | def computeCapacity(results, threshold):
"""Returns largest number of objects with accuracy above threshold."""
closestBelow = None
closestAbove = None
for numObjects, accuracy in sorted(results):
if accuracy >= threshold:
if closestAbove is None or closestAbove[0] < numObjects:
closestAbove = (numObjects, accuracy)
closestBelow = None
else:
if closestBelow is None:
closestBelow = (numObjects, accuracy)
if closestBelow is None or closestAbove is None:
print closestBelow, threshold, closestAbove
raise ValueError(
"Results must include a value above and below threshold of {}".format(threshold))
print " Capacity threshold is between {} and {}".format(closestAbove[0], closestBelow[0])
return closestAbove[0] | python | def computeCapacity(results, threshold):
"""Returns largest number of objects with accuracy above threshold."""
closestBelow = None
closestAbove = None
for numObjects, accuracy in sorted(results):
if accuracy >= threshold:
if closestAbove is None or closestAbove[0] < numObjects:
closestAbove = (numObjects, accuracy)
closestBelow = None
else:
if closestBelow is None:
closestBelow = (numObjects, accuracy)
if closestBelow is None or closestAbove is None:
print closestBelow, threshold, closestAbove
raise ValueError(
"Results must include a value above and below threshold of {}".format(threshold))
print " Capacity threshold is between {} and {}".format(closestAbove[0], closestBelow[0])
return closestAbove[0] | [
"def",
"computeCapacity",
"(",
"results",
",",
"threshold",
")",
":",
"closestBelow",
"=",
"None",
"closestAbove",
"=",
"None",
"for",
"numObjects",
",",
"accuracy",
"in",
"sorted",
"(",
"results",
")",
":",
"if",
"accuracy",
">=",
"threshold",
":",
"if",
... | Returns largest number of objects with accuracy above threshold. | [
"Returns",
"largest",
"number",
"of",
"objects",
"with",
"accuracy",
"above",
"threshold",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/union_path_integration/plot_comparison.py#L36-L55 | train | 198,926 |
numenta/htmresearch | htmresearch/algorithms/single_layer_location_memory.py | SingleLayerLocationMemory.reset | def reset(self):
"""
Deactivate all cells.
"""
self.activeCells = np.empty(0, dtype="uint32")
self.activeDeltaSegments = np.empty(0, dtype="uint32")
self.activeFeatureLocationSegments = np.empty(0, dtype="uint32") | python | def reset(self):
"""
Deactivate all cells.
"""
self.activeCells = np.empty(0, dtype="uint32")
self.activeDeltaSegments = np.empty(0, dtype="uint32")
self.activeFeatureLocationSegments = np.empty(0, dtype="uint32") | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"activeCells",
"=",
"np",
".",
"empty",
"(",
"0",
",",
"dtype",
"=",
"\"uint32\"",
")",
"self",
".",
"activeDeltaSegments",
"=",
"np",
".",
"empty",
"(",
"0",
",",
"dtype",
"=",
"\"uint32\"",
")",
... | Deactivate all cells. | [
"Deactivate",
"all",
"cells",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/single_layer_location_memory.py#L101-L108 | train | 198,927 |
numenta/htmresearch | htmresearch/algorithms/single_layer_location_memory.py | SingleLayerLocationMemory.compute | def compute(self, deltaLocation=(), newLocation=(),
featureLocationInput=(), featureLocationGrowthCandidates=(),
learn=True):
"""
Run one time step of the Location Memory algorithm.
@param deltaLocation (sorted numpy array)
@param newLocation (sorted numpy array)
@param featureLocationInput (sorted numpy array)
@param featureLocationGrowthCandidates (sorted numpy array)
"""
prevActiveCells = self.activeCells
self.activeDeltaSegments = np.where(
(self.internalConnections.computeActivity(
prevActiveCells, self.connectedPermanence
) >= self.activationThreshold)
&
(self.deltaConnections.computeActivity(
deltaLocation, self.connectedPermanence
) >= self.activationThreshold))[0]
# When we're moving, the feature-location input has no effect.
if len(deltaLocation) == 0:
self.activeFeatureLocationSegments = np.where(
self.featureLocationConnections.computeActivity(
featureLocationInput, self.connectedPermanence
) >= self.activationThreshold)[0]
else:
self.activeFeatureLocationSegments = np.empty(0, dtype="uint32")
if len(newLocation) > 0:
# Drive activations by relaying this location SDR.
self.activeCells = newLocation
if learn:
# Learn the delta.
self._learnTransition(prevActiveCells, deltaLocation, newLocation)
# Learn the featureLocationInput.
self._learnFeatureLocationPair(newLocation, featureLocationInput,
featureLocationGrowthCandidates)
elif len(prevActiveCells) > 0:
if len(deltaLocation) > 0:
# Drive activations by applying the deltaLocation to the current location.
# Completely ignore the featureLocationInput. It's outdated, associated
# with the previous location.
cellsForDeltaSegments = self.internalConnections.mapSegmentsToCells(
self.activeDeltaSegments)
self.activeCells = np.unique(cellsForDeltaSegments)
else:
# Keep previous active cells active.
# Modulate with the featureLocationInput.
if len(self.activeFeatureLocationSegments) > 0:
cellsForFeatureLocationSegments = (
self.featureLocationConnections.mapSegmentsToCells(
self.activeFeatureLocationSegments))
self.activeCells = np.intersect1d(prevActiveCells,
cellsForFeatureLocationSegments)
else:
self.activeCells = prevActiveCells
elif len(featureLocationInput) > 0:
# Drive activations with the featureLocationInput.
cellsForFeatureLocationSegments = (
self.featureLocationConnections.mapSegmentsToCells(
self.activeFeatureLocationSegments))
self.activeCells = np.unique(cellsForFeatureLocationSegments) | python | def compute(self, deltaLocation=(), newLocation=(),
featureLocationInput=(), featureLocationGrowthCandidates=(),
learn=True):
"""
Run one time step of the Location Memory algorithm.
@param deltaLocation (sorted numpy array)
@param newLocation (sorted numpy array)
@param featureLocationInput (sorted numpy array)
@param featureLocationGrowthCandidates (sorted numpy array)
"""
prevActiveCells = self.activeCells
self.activeDeltaSegments = np.where(
(self.internalConnections.computeActivity(
prevActiveCells, self.connectedPermanence
) >= self.activationThreshold)
&
(self.deltaConnections.computeActivity(
deltaLocation, self.connectedPermanence
) >= self.activationThreshold))[0]
# When we're moving, the feature-location input has no effect.
if len(deltaLocation) == 0:
self.activeFeatureLocationSegments = np.where(
self.featureLocationConnections.computeActivity(
featureLocationInput, self.connectedPermanence
) >= self.activationThreshold)[0]
else:
self.activeFeatureLocationSegments = np.empty(0, dtype="uint32")
if len(newLocation) > 0:
# Drive activations by relaying this location SDR.
self.activeCells = newLocation
if learn:
# Learn the delta.
self._learnTransition(prevActiveCells, deltaLocation, newLocation)
# Learn the featureLocationInput.
self._learnFeatureLocationPair(newLocation, featureLocationInput,
featureLocationGrowthCandidates)
elif len(prevActiveCells) > 0:
if len(deltaLocation) > 0:
# Drive activations by applying the deltaLocation to the current location.
# Completely ignore the featureLocationInput. It's outdated, associated
# with the previous location.
cellsForDeltaSegments = self.internalConnections.mapSegmentsToCells(
self.activeDeltaSegments)
self.activeCells = np.unique(cellsForDeltaSegments)
else:
# Keep previous active cells active.
# Modulate with the featureLocationInput.
if len(self.activeFeatureLocationSegments) > 0:
cellsForFeatureLocationSegments = (
self.featureLocationConnections.mapSegmentsToCells(
self.activeFeatureLocationSegments))
self.activeCells = np.intersect1d(prevActiveCells,
cellsForFeatureLocationSegments)
else:
self.activeCells = prevActiveCells
elif len(featureLocationInput) > 0:
# Drive activations with the featureLocationInput.
cellsForFeatureLocationSegments = (
self.featureLocationConnections.mapSegmentsToCells(
self.activeFeatureLocationSegments))
self.activeCells = np.unique(cellsForFeatureLocationSegments) | [
"def",
"compute",
"(",
"self",
",",
"deltaLocation",
"=",
"(",
")",
",",
"newLocation",
"=",
"(",
")",
",",
"featureLocationInput",
"=",
"(",
")",
",",
"featureLocationGrowthCandidates",
"=",
"(",
")",
",",
"learn",
"=",
"True",
")",
":",
"prevActiveCells"... | Run one time step of the Location Memory algorithm.
@param deltaLocation (sorted numpy array)
@param newLocation (sorted numpy array)
@param featureLocationInput (sorted numpy array)
@param featureLocationGrowthCandidates (sorted numpy array) | [
"Run",
"one",
"time",
"step",
"of",
"the",
"Location",
"Memory",
"algorithm",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/single_layer_location_memory.py#L111-L187 | train | 198,928 |
numenta/htmresearch | htmresearch/regions/GridCellLocationRegion.py | GridCellLocationRegion.initialize | def initialize(self):
""" Initialize grid cell modules """
if self._modules is None:
self._modules = []
for i in xrange(self.moduleCount):
self._modules.append(ThresholdedGaussian2DLocationModule(
cellsPerAxis=self.cellsPerAxis,
scale=self.scale[i],
orientation=self.orientation[i],
anchorInputSize=self.anchorInputSize,
activeFiringRate=self.activeFiringRate,
bumpSigma=self.bumpSigma,
activationThreshold=self.activationThreshold,
initialPermanence=self.initialPermanence,
connectedPermanence=self.connectedPermanence,
learningThreshold=self.learningThreshold,
sampleSize=self.sampleSize,
permanenceIncrement=self.permanenceIncrement,
permanenceDecrement=self.permanenceDecrement,
maxSynapsesPerSegment=self.maxSynapsesPerSegment,
bumpOverlapMethod=self.bumpOverlapMethod,
seed=self.seed))
# Create a projection matrix for each module used to convert higher
# dimension displacements to 2D
if self.dimensions > 2:
self._projection = [
self.createProjectionMatrix(dimensions=self.dimensions)
for _ in xrange(self.moduleCount)] | python | def initialize(self):
""" Initialize grid cell modules """
if self._modules is None:
self._modules = []
for i in xrange(self.moduleCount):
self._modules.append(ThresholdedGaussian2DLocationModule(
cellsPerAxis=self.cellsPerAxis,
scale=self.scale[i],
orientation=self.orientation[i],
anchorInputSize=self.anchorInputSize,
activeFiringRate=self.activeFiringRate,
bumpSigma=self.bumpSigma,
activationThreshold=self.activationThreshold,
initialPermanence=self.initialPermanence,
connectedPermanence=self.connectedPermanence,
learningThreshold=self.learningThreshold,
sampleSize=self.sampleSize,
permanenceIncrement=self.permanenceIncrement,
permanenceDecrement=self.permanenceDecrement,
maxSynapsesPerSegment=self.maxSynapsesPerSegment,
bumpOverlapMethod=self.bumpOverlapMethod,
seed=self.seed))
# Create a projection matrix for each module used to convert higher
# dimension displacements to 2D
if self.dimensions > 2:
self._projection = [
self.createProjectionMatrix(dimensions=self.dimensions)
for _ in xrange(self.moduleCount)] | [
"def",
"initialize",
"(",
"self",
")",
":",
"if",
"self",
".",
"_modules",
"is",
"None",
":",
"self",
".",
"_modules",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"self",
".",
"moduleCount",
")",
":",
"self",
".",
"_modules",
".",
"append",
"("... | Initialize grid cell modules | [
"Initialize",
"grid",
"cell",
"modules"
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/regions/GridCellLocationRegion.py#L366-L395 | train | 198,929 |
numenta/htmresearch | htmresearch/regions/GridCellLocationRegion.py | GridCellLocationRegion.compute | def compute(self, inputs, outputs):
"""
Compute the location based on the 'displacement' and 'anchorInput' by first
applying the movement, if 'displacement' is present in the 'input' array
and then applying the sensation if 'anchorInput' is present in the input
array. The 'anchorGrowthCandidates' input array is used during learning
See :meth:`ThresholdedGaussian2DLocationModule.movementCompute` and
:meth:`ThresholdedGaussian2DLocationModule.sensoryCompute`
"""
if inputs.get("resetIn", False):
self.reset()
if self.learningMode:
# Initialize to random location after reset when learning
self.activateRandomLocation()
# send empty output
outputs["activeCells"][:] = 0
outputs["learnableCells"][:] = 0
outputs["sensoryAssociatedCells"][:] = 0
return
displacement = inputs.get("displacement", np.array([]))
anchorInput = inputs.get("anchorInput", np.array([])).nonzero()[0]
anchorGrowthCandidates = inputs.get("anchorGrowthCandidates", np.array([])).nonzero()[0]
# Concatenate the output of all modules
activeCells = np.array([], dtype=np.uint32)
learnableCells = np.array([], dtype=np.uint32)
sensoryAssociatedCells = np.array([], dtype=np.uint32)
# Only process input when data is available
shouldMove = displacement.any()
shouldSense = anchorInput.any() or anchorGrowthCandidates.any()
if shouldMove and len(displacement) != self.dimensions:
raise TypeError("displacement must have {} dimensions".format(self.dimensions))
# Handles dual phase movement/sensation processing
if self.dualPhase:
if self._sensing:
shouldMove = False
else:
shouldSense = False
# Toggle between movement and sensation
self._sensing = not self._sensing
for i in xrange(self.moduleCount):
module = self._modules[i]
# Compute movement
if shouldMove:
movement = displacement
if self.dimensions > 2:
# Project n-dimension displacements to 2D
movement = np.matmul(self._projection[i], movement)
module.movementCompute(movement)
# Compute sensation
if shouldSense:
module.sensoryCompute(anchorInput, anchorGrowthCandidates,
self.learningMode)
# Concatenate outputs
start = i * self.cellCount
activeCells = np.append(activeCells,
module.getActiveCells() + start)
learnableCells = np.append(learnableCells,
module.getLearnableCells() + start)
sensoryAssociatedCells = np.append(sensoryAssociatedCells,
module.getSensoryAssociatedCells() + start)
outputs["activeCells"][:] = 0
outputs["activeCells"][activeCells] = 1
outputs["learnableCells"][:] = 0
outputs["learnableCells"][learnableCells] = 1
outputs["sensoryAssociatedCells"][:] = 0
outputs["sensoryAssociatedCells"][sensoryAssociatedCells] = 1 | python | def compute(self, inputs, outputs):
"""
Compute the location based on the 'displacement' and 'anchorInput' by first
applying the movement, if 'displacement' is present in the 'input' array
and then applying the sensation if 'anchorInput' is present in the input
array. The 'anchorGrowthCandidates' input array is used during learning
See :meth:`ThresholdedGaussian2DLocationModule.movementCompute` and
:meth:`ThresholdedGaussian2DLocationModule.sensoryCompute`
"""
if inputs.get("resetIn", False):
self.reset()
if self.learningMode:
# Initialize to random location after reset when learning
self.activateRandomLocation()
# send empty output
outputs["activeCells"][:] = 0
outputs["learnableCells"][:] = 0
outputs["sensoryAssociatedCells"][:] = 0
return
displacement = inputs.get("displacement", np.array([]))
anchorInput = inputs.get("anchorInput", np.array([])).nonzero()[0]
anchorGrowthCandidates = inputs.get("anchorGrowthCandidates", np.array([])).nonzero()[0]
# Concatenate the output of all modules
activeCells = np.array([], dtype=np.uint32)
learnableCells = np.array([], dtype=np.uint32)
sensoryAssociatedCells = np.array([], dtype=np.uint32)
# Only process input when data is available
shouldMove = displacement.any()
shouldSense = anchorInput.any() or anchorGrowthCandidates.any()
if shouldMove and len(displacement) != self.dimensions:
raise TypeError("displacement must have {} dimensions".format(self.dimensions))
# Handles dual phase movement/sensation processing
if self.dualPhase:
if self._sensing:
shouldMove = False
else:
shouldSense = False
# Toggle between movement and sensation
self._sensing = not self._sensing
for i in xrange(self.moduleCount):
module = self._modules[i]
# Compute movement
if shouldMove:
movement = displacement
if self.dimensions > 2:
# Project n-dimension displacements to 2D
movement = np.matmul(self._projection[i], movement)
module.movementCompute(movement)
# Compute sensation
if shouldSense:
module.sensoryCompute(anchorInput, anchorGrowthCandidates,
self.learningMode)
# Concatenate outputs
start = i * self.cellCount
activeCells = np.append(activeCells,
module.getActiveCells() + start)
learnableCells = np.append(learnableCells,
module.getLearnableCells() + start)
sensoryAssociatedCells = np.append(sensoryAssociatedCells,
module.getSensoryAssociatedCells() + start)
outputs["activeCells"][:] = 0
outputs["activeCells"][activeCells] = 1
outputs["learnableCells"][:] = 0
outputs["learnableCells"][learnableCells] = 1
outputs["sensoryAssociatedCells"][:] = 0
outputs["sensoryAssociatedCells"][sensoryAssociatedCells] = 1 | [
"def",
"compute",
"(",
"self",
",",
"inputs",
",",
"outputs",
")",
":",
"if",
"inputs",
".",
"get",
"(",
"\"resetIn\"",
",",
"False",
")",
":",
"self",
".",
"reset",
"(",
")",
"if",
"self",
".",
"learningMode",
":",
"# Initialize to random location after r... | Compute the location based on the 'displacement' and 'anchorInput' by first
applying the movement, if 'displacement' is present in the 'input' array
and then applying the sensation if 'anchorInput' is present in the input
array. The 'anchorGrowthCandidates' input array is used during learning
See :meth:`ThresholdedGaussian2DLocationModule.movementCompute` and
:meth:`ThresholdedGaussian2DLocationModule.sensoryCompute` | [
"Compute",
"the",
"location",
"based",
"on",
"the",
"displacement",
"and",
"anchorInput",
"by",
"first",
"applying",
"the",
"movement",
"if",
"displacement",
"is",
"present",
"in",
"the",
"input",
"array",
"and",
"then",
"applying",
"the",
"sensation",
"if",
"... | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/regions/GridCellLocationRegion.py#L398-L478 | train | 198,930 |
numenta/htmresearch | htmresearch/regions/GridCellLocationRegion.py | GridCellLocationRegion.setParameter | def setParameter(self, parameterName, index, parameterValue):
"""
Set the value of a Spec parameter.
"""
spec = self.getSpec()
if parameterName not in spec['parameters']:
raise Exception("Unknown parameter: " + parameterName)
setattr(self, parameterName, parameterValue) | python | def setParameter(self, parameterName, index, parameterValue):
"""
Set the value of a Spec parameter.
"""
spec = self.getSpec()
if parameterName not in spec['parameters']:
raise Exception("Unknown parameter: " + parameterName)
setattr(self, parameterName, parameterValue) | [
"def",
"setParameter",
"(",
"self",
",",
"parameterName",
",",
"index",
",",
"parameterValue",
")",
":",
"spec",
"=",
"self",
".",
"getSpec",
"(",
")",
"if",
"parameterName",
"not",
"in",
"spec",
"[",
"'parameters'",
"]",
":",
"raise",
"Exception",
"(",
... | Set the value of a Spec parameter. | [
"Set",
"the",
"value",
"of",
"a",
"Spec",
"parameter",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/regions/GridCellLocationRegion.py#L492-L500 | train | 198,931 |
numenta/htmresearch | htmresearch/regions/GridCellLocationRegion.py | GridCellLocationRegion.getOutputElementCount | def getOutputElementCount(self, name):
"""
Returns the size of the output array
"""
if name in ["activeCells", "learnableCells", "sensoryAssociatedCells"]:
return self.cellCount * self.moduleCount
else:
raise Exception("Invalid output name specified: " + name) | python | def getOutputElementCount(self, name):
"""
Returns the size of the output array
"""
if name in ["activeCells", "learnableCells", "sensoryAssociatedCells"]:
return self.cellCount * self.moduleCount
else:
raise Exception("Invalid output name specified: " + name) | [
"def",
"getOutputElementCount",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"[",
"\"activeCells\"",
",",
"\"learnableCells\"",
",",
"\"sensoryAssociatedCells\"",
"]",
":",
"return",
"self",
".",
"cellCount",
"*",
"self",
".",
"moduleCount",
"else",
... | Returns the size of the output array | [
"Returns",
"the",
"size",
"of",
"the",
"output",
"array"
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/regions/GridCellLocationRegion.py#L502-L509 | train | 198,932 |
numenta/htmresearch | htmresearch/frameworks/location/path_integration_union_narrowing.py | PIUNCorticalColumn.reset | def reset(self):
"""
Clear all cell activity.
"""
self.L4.reset()
for module in self.L6aModules:
module.reset() | python | def reset(self):
"""
Clear all cell activity.
"""
self.L4.reset()
for module in self.L6aModules:
module.reset() | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"L4",
".",
"reset",
"(",
")",
"for",
"module",
"in",
"self",
".",
"L6aModules",
":",
"module",
".",
"reset",
"(",
")"
] | Clear all cell activity. | [
"Clear",
"all",
"cell",
"activity",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/location/path_integration_union_narrowing.py#L255-L261 | train | 198,933 |
numenta/htmresearch | htmresearch/frameworks/location/path_integration_union_narrowing.py | PIUNCorticalColumn.getLocationRepresentation | def getLocationRepresentation(self):
"""
Get the full population representation of the location layer.
"""
activeCells = np.array([], dtype="uint32")
totalPrevCells = 0
for module in self.L6aModules:
activeCells = np.append(activeCells,
module.getActiveCells() + totalPrevCells)
totalPrevCells += module.numberOfCells()
return activeCells | python | def getLocationRepresentation(self):
"""
Get the full population representation of the location layer.
"""
activeCells = np.array([], dtype="uint32")
totalPrevCells = 0
for module in self.L6aModules:
activeCells = np.append(activeCells,
module.getActiveCells() + totalPrevCells)
totalPrevCells += module.numberOfCells()
return activeCells | [
"def",
"getLocationRepresentation",
"(",
"self",
")",
":",
"activeCells",
"=",
"np",
".",
"array",
"(",
"[",
"]",
",",
"dtype",
"=",
"\"uint32\"",
")",
"totalPrevCells",
"=",
"0",
"for",
"module",
"in",
"self",
".",
"L6aModules",
":",
"activeCells",
"=",
... | Get the full population representation of the location layer. | [
"Get",
"the",
"full",
"population",
"representation",
"of",
"the",
"location",
"layer",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/location/path_integration_union_narrowing.py#L279-L291 | train | 198,934 |
numenta/htmresearch | htmresearch/frameworks/location/path_integration_union_narrowing.py | PIUNCorticalColumn.getLearnableLocationRepresentation | def getLearnableLocationRepresentation(self):
"""
Get the cells in the location layer that should be associated with the
sensory input layer representation. In some models, this is identical to the
active cells. In others, it's a subset.
"""
learnableCells = np.array([], dtype="uint32")
totalPrevCells = 0
for module in self.L6aModules:
learnableCells = np.append(learnableCells,
module.getLearnableCells() + totalPrevCells)
totalPrevCells += module.numberOfCells()
return learnableCells | python | def getLearnableLocationRepresentation(self):
"""
Get the cells in the location layer that should be associated with the
sensory input layer representation. In some models, this is identical to the
active cells. In others, it's a subset.
"""
learnableCells = np.array([], dtype="uint32")
totalPrevCells = 0
for module in self.L6aModules:
learnableCells = np.append(learnableCells,
module.getLearnableCells() + totalPrevCells)
totalPrevCells += module.numberOfCells()
return learnableCells | [
"def",
"getLearnableLocationRepresentation",
"(",
"self",
")",
":",
"learnableCells",
"=",
"np",
".",
"array",
"(",
"[",
"]",
",",
"dtype",
"=",
"\"uint32\"",
")",
"totalPrevCells",
"=",
"0",
"for",
"module",
"in",
"self",
".",
"L6aModules",
":",
"learnableC... | Get the cells in the location layer that should be associated with the
sensory input layer representation. In some models, this is identical to the
active cells. In others, it's a subset. | [
"Get",
"the",
"cells",
"in",
"the",
"location",
"layer",
"that",
"should",
"be",
"associated",
"with",
"the",
"sensory",
"input",
"layer",
"representation",
".",
"In",
"some",
"models",
"this",
"is",
"identical",
"to",
"the",
"active",
"cells",
".",
"In",
... | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/location/path_integration_union_narrowing.py#L294-L308 | train | 198,935 |
numenta/htmresearch | htmresearch/frameworks/location/path_integration_union_narrowing.py | PIUNExperiment.learnObject | def learnObject(self,
objectDescription,
randomLocation=False,
useNoise=False,
noisyTrainingTime=1):
"""
Train the network to recognize the specified object. Move the sensor to one of
its features and activate a random location representation in the location
layer. Move the sensor over the object, updating the location representation
through path integration. At each point on the object, form reciprocal
connections between the represention of the location and the representation
of the sensory input.
@param objectDescription (dict)
For example:
{"name": "Object 1",
"features": [{"top": 0, "left": 0, "width": 10, "height": 10, "name": "A"},
{"top": 0, "left": 10, "width": 10, "height": 10, "name": "B"}]}
@return locationsAreUnique (bool)
True if this object was assigned a unique set of locations. False if a
location on this object has the same location representation as another
location somewhere else.
"""
self.reset()
self.column.activateRandomLocation()
locationsAreUnique = True
if randomLocation or useNoise:
numIters = noisyTrainingTime
else:
numIters = 1
for i in xrange(numIters):
for iFeature, feature in enumerate(objectDescription["features"]):
self._move(feature, randomLocation=randomLocation, useNoise=useNoise)
featureSDR = self.features[feature["name"]]
self._sense(featureSDR, learn=True, waitForSettle=False)
locationRepresentation = self.column.getSensoryAssociatedLocationRepresentation()
self.locationRepresentations[(objectDescription["name"],
iFeature)].append(locationRepresentation)
self.inputRepresentations[(objectDescription["name"],
iFeature, feature["name"])] = (
self.column.L4.getWinnerCells())
locationTuple = tuple(locationRepresentation)
locationsAreUnique = (locationsAreUnique and
locationTuple not in self.representationSet)
self.representationSet.add(tuple(locationRepresentation))
self.learnedObjects.append(objectDescription)
return locationsAreUnique | python | def learnObject(self,
objectDescription,
randomLocation=False,
useNoise=False,
noisyTrainingTime=1):
"""
Train the network to recognize the specified object. Move the sensor to one of
its features and activate a random location representation in the location
layer. Move the sensor over the object, updating the location representation
through path integration. At each point on the object, form reciprocal
connections between the represention of the location and the representation
of the sensory input.
@param objectDescription (dict)
For example:
{"name": "Object 1",
"features": [{"top": 0, "left": 0, "width": 10, "height": 10, "name": "A"},
{"top": 0, "left": 10, "width": 10, "height": 10, "name": "B"}]}
@return locationsAreUnique (bool)
True if this object was assigned a unique set of locations. False if a
location on this object has the same location representation as another
location somewhere else.
"""
self.reset()
self.column.activateRandomLocation()
locationsAreUnique = True
if randomLocation or useNoise:
numIters = noisyTrainingTime
else:
numIters = 1
for i in xrange(numIters):
for iFeature, feature in enumerate(objectDescription["features"]):
self._move(feature, randomLocation=randomLocation, useNoise=useNoise)
featureSDR = self.features[feature["name"]]
self._sense(featureSDR, learn=True, waitForSettle=False)
locationRepresentation = self.column.getSensoryAssociatedLocationRepresentation()
self.locationRepresentations[(objectDescription["name"],
iFeature)].append(locationRepresentation)
self.inputRepresentations[(objectDescription["name"],
iFeature, feature["name"])] = (
self.column.L4.getWinnerCells())
locationTuple = tuple(locationRepresentation)
locationsAreUnique = (locationsAreUnique and
locationTuple not in self.representationSet)
self.representationSet.add(tuple(locationRepresentation))
self.learnedObjects.append(objectDescription)
return locationsAreUnique | [
"def",
"learnObject",
"(",
"self",
",",
"objectDescription",
",",
"randomLocation",
"=",
"False",
",",
"useNoise",
"=",
"False",
",",
"noisyTrainingTime",
"=",
"1",
")",
":",
"self",
".",
"reset",
"(",
")",
"self",
".",
"column",
".",
"activateRandomLocation... | Train the network to recognize the specified object. Move the sensor to one of
its features and activate a random location representation in the location
layer. Move the sensor over the object, updating the location representation
through path integration. At each point on the object, form reciprocal
connections between the represention of the location and the representation
of the sensory input.
@param objectDescription (dict)
For example:
{"name": "Object 1",
"features": [{"top": 0, "left": 0, "width": 10, "height": 10, "name": "A"},
{"top": 0, "left": 10, "width": 10, "height": 10, "name": "B"}]}
@return locationsAreUnique (bool)
True if this object was assigned a unique set of locations. False if a
location on this object has the same location representation as another
location somewhere else. | [
"Train",
"the",
"network",
"to",
"recognize",
"the",
"specified",
"object",
".",
"Move",
"the",
"sensor",
"to",
"one",
"of",
"its",
"features",
"and",
"activate",
"a",
"random",
"location",
"representation",
"in",
"the",
"location",
"layer",
".",
"Move",
"th... | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/location/path_integration_union_narrowing.py#L407-L461 | train | 198,936 |
numenta/htmresearch | htmresearch/frameworks/location/path_integration_union_narrowing.py | PIUNExperiment._move | def _move(self, feature, randomLocation = False, useNoise = True):
"""
Move the sensor to the center of the specified feature. If the sensor is
currently at another location, send the displacement into the cortical
column so that it can perform path integration.
"""
if randomLocation:
locationOnObject = {
"top": feature["top"] + np.random.rand()*feature["height"],
"left": feature["left"] + np.random.rand()*feature["width"],
}
else:
locationOnObject = {
"top": feature["top"] + feature["height"]/2.,
"left": feature["left"] + feature["width"]/2.
}
if self.locationOnObject is not None:
displacement = {"top": locationOnObject["top"] -
self.locationOnObject["top"],
"left": locationOnObject["left"] -
self.locationOnObject["left"]}
if useNoise:
params = self.column.movementCompute(displacement,
self.noiseFactor,
self.moduleNoiseFactor)
else:
params = self.column.movementCompute(displacement, 0, 0)
for monitor in self.monitors.values():
monitor.afterLocationShift(**params)
else:
for monitor in self.monitors.values():
monitor.afterLocationInitialize()
self.locationOnObject = locationOnObject
for monitor in self.monitors.values():
monitor.afterLocationChanged(locationOnObject) | python | def _move(self, feature, randomLocation = False, useNoise = True):
"""
Move the sensor to the center of the specified feature. If the sensor is
currently at another location, send the displacement into the cortical
column so that it can perform path integration.
"""
if randomLocation:
locationOnObject = {
"top": feature["top"] + np.random.rand()*feature["height"],
"left": feature["left"] + np.random.rand()*feature["width"],
}
else:
locationOnObject = {
"top": feature["top"] + feature["height"]/2.,
"left": feature["left"] + feature["width"]/2.
}
if self.locationOnObject is not None:
displacement = {"top": locationOnObject["top"] -
self.locationOnObject["top"],
"left": locationOnObject["left"] -
self.locationOnObject["left"]}
if useNoise:
params = self.column.movementCompute(displacement,
self.noiseFactor,
self.moduleNoiseFactor)
else:
params = self.column.movementCompute(displacement, 0, 0)
for monitor in self.monitors.values():
monitor.afterLocationShift(**params)
else:
for monitor in self.monitors.values():
monitor.afterLocationInitialize()
self.locationOnObject = locationOnObject
for monitor in self.monitors.values():
monitor.afterLocationChanged(locationOnObject) | [
"def",
"_move",
"(",
"self",
",",
"feature",
",",
"randomLocation",
"=",
"False",
",",
"useNoise",
"=",
"True",
")",
":",
"if",
"randomLocation",
":",
"locationOnObject",
"=",
"{",
"\"top\"",
":",
"feature",
"[",
"\"top\"",
"]",
"+",
"np",
".",
"random",... | Move the sensor to the center of the specified feature. If the sensor is
currently at another location, send the displacement into the cortical
column so that it can perform path integration. | [
"Move",
"the",
"sensor",
"to",
"the",
"center",
"of",
"the",
"specified",
"feature",
".",
"If",
"the",
"sensor",
"is",
"currently",
"at",
"another",
"location",
"send",
"the",
"displacement",
"into",
"the",
"cortical",
"column",
"so",
"that",
"it",
"can",
... | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/location/path_integration_union_narrowing.py#L556-L594 | train | 198,937 |
numenta/htmresearch | htmresearch/frameworks/location/path_integration_union_narrowing.py | PIUNExperiment._sense | def _sense(self, featureSDR, learn, waitForSettle):
"""
Send the sensory input into the network. Optionally, send it multiple times
until the network settles.
"""
for monitor in self.monitors.values():
monitor.beforeSense(featureSDR)
iteration = 0
prevCellActivity = None
while True:
(inputParams,
locationParams) = self.column.sensoryCompute(featureSDR, learn)
if waitForSettle:
cellActivity = (set(self.column.getSensoryRepresentation()),
set(self.column.getLocationRepresentation()))
if cellActivity == prevCellActivity:
# It settled. Don't even log this timestep.
break
prevCellActivity = cellActivity
for monitor in self.monitors.values():
if iteration > 0:
monitor.beforeSensoryRepetition()
monitor.afterInputCompute(**inputParams)
monitor.afterLocationAnchor(**locationParams)
iteration += 1
if not waitForSettle or iteration >= self.maxSettlingTime:
break | python | def _sense(self, featureSDR, learn, waitForSettle):
"""
Send the sensory input into the network. Optionally, send it multiple times
until the network settles.
"""
for monitor in self.monitors.values():
monitor.beforeSense(featureSDR)
iteration = 0
prevCellActivity = None
while True:
(inputParams,
locationParams) = self.column.sensoryCompute(featureSDR, learn)
if waitForSettle:
cellActivity = (set(self.column.getSensoryRepresentation()),
set(self.column.getLocationRepresentation()))
if cellActivity == prevCellActivity:
# It settled. Don't even log this timestep.
break
prevCellActivity = cellActivity
for monitor in self.monitors.values():
if iteration > 0:
monitor.beforeSensoryRepetition()
monitor.afterInputCompute(**inputParams)
monitor.afterLocationAnchor(**locationParams)
iteration += 1
if not waitForSettle or iteration >= self.maxSettlingTime:
break | [
"def",
"_sense",
"(",
"self",
",",
"featureSDR",
",",
"learn",
",",
"waitForSettle",
")",
":",
"for",
"monitor",
"in",
"self",
".",
"monitors",
".",
"values",
"(",
")",
":",
"monitor",
".",
"beforeSense",
"(",
"featureSDR",
")",
"iteration",
"=",
"0",
... | Send the sensory input into the network. Optionally, send it multiple times
until the network settles. | [
"Send",
"the",
"sensory",
"input",
"into",
"the",
"network",
".",
"Optionally",
"send",
"it",
"multiple",
"times",
"until",
"the",
"network",
"settles",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/location/path_integration_union_narrowing.py#L597-L630 | train | 198,938 |
numenta/htmresearch | htmresearch/frameworks/layers/object_machine_factory.py | createObjectMachine | def createObjectMachine(machineType, **kwargs):
"""
Return an object machine of the appropriate type.
@param machineType (str) A supported ObjectMachine type
@param kwargs (dict) Constructor argument for the class that will be
instantiated. Keyword parameters specific to each
model type should be passed in here.
"""
if machineType not in ObjectMachineTypes.getTypes():
raise RuntimeError("Unknown model type: " + machineType)
return getattr(ObjectMachineTypes, machineType)(**kwargs) | python | def createObjectMachine(machineType, **kwargs):
"""
Return an object machine of the appropriate type.
@param machineType (str) A supported ObjectMachine type
@param kwargs (dict) Constructor argument for the class that will be
instantiated. Keyword parameters specific to each
model type should be passed in here.
"""
if machineType not in ObjectMachineTypes.getTypes():
raise RuntimeError("Unknown model type: " + machineType)
return getattr(ObjectMachineTypes, machineType)(**kwargs) | [
"def",
"createObjectMachine",
"(",
"machineType",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"machineType",
"not",
"in",
"ObjectMachineTypes",
".",
"getTypes",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Unknown model type: \"",
"+",
"machineType",
")",
"retur... | Return an object machine of the appropriate type.
@param machineType (str) A supported ObjectMachine type
@param kwargs (dict) Constructor argument for the class that will be
instantiated. Keyword parameters specific to each
model type should be passed in here. | [
"Return",
"an",
"object",
"machine",
"of",
"the",
"appropriate",
"type",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/object_machine_factory.py#L62-L76 | train | 198,939 |
numenta/htmresearch | htmresearch/frameworks/pytorch/modules/k_winners.py | getEntropies | def getEntropies(m):
"""
Recursively get the current and max entropies from every child module
:param m: any module
:return: (currentEntropy, maxEntropy)
"""
entropy = 0.0
max_entropy = 0.0
for module in m.children():
e, m = getEntropies(module)
entropy += e
max_entropy += m
e, m = getEntropy(m)
entropy += e
max_entropy += m
return entropy, max_entropy | python | def getEntropies(m):
"""
Recursively get the current and max entropies from every child module
:param m: any module
:return: (currentEntropy, maxEntropy)
"""
entropy = 0.0
max_entropy = 0.0
for module in m.children():
e, m = getEntropies(module)
entropy += e
max_entropy += m
e, m = getEntropy(m)
entropy += e
max_entropy += m
return entropy, max_entropy | [
"def",
"getEntropies",
"(",
"m",
")",
":",
"entropy",
"=",
"0.0",
"max_entropy",
"=",
"0.0",
"for",
"module",
"in",
"m",
".",
"children",
"(",
")",
":",
"e",
",",
"m",
"=",
"getEntropies",
"(",
"module",
")",
"entropy",
"+=",
"e",
"max_entropy",
"+="... | Recursively get the current and max entropies from every child module
:param m: any module
:return: (currentEntropy, maxEntropy) | [
"Recursively",
"get",
"the",
"current",
"and",
"max",
"entropies",
"from",
"every",
"child",
"module"
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/pytorch/modules/k_winners.py#L49-L68 | train | 198,940 |
numenta/htmresearch | htmresearch/frameworks/pytorch/modules/k_winners.py | updateBoostStrength | def updateBoostStrength(m):
"""
Function used to update KWinner modules boost strength after each epoch.
Call using :meth:`torch.nn.Module.apply` after each epoch if required
For example: ``m.apply(updateBoostStrength)``
:param m: KWinner module
"""
if isinstance(m, KWinnersBase):
if m.training:
m.boostStrength = m.boostStrength * m.boostStrengthFactor | python | def updateBoostStrength(m):
"""
Function used to update KWinner modules boost strength after each epoch.
Call using :meth:`torch.nn.Module.apply` after each epoch if required
For example: ``m.apply(updateBoostStrength)``
:param m: KWinner module
"""
if isinstance(m, KWinnersBase):
if m.training:
m.boostStrength = m.boostStrength * m.boostStrengthFactor | [
"def",
"updateBoostStrength",
"(",
"m",
")",
":",
"if",
"isinstance",
"(",
"m",
",",
"KWinnersBase",
")",
":",
"if",
"m",
".",
"training",
":",
"m",
".",
"boostStrength",
"=",
"m",
".",
"boostStrength",
"*",
"m",
".",
"boostStrengthFactor"
] | Function used to update KWinner modules boost strength after each epoch.
Call using :meth:`torch.nn.Module.apply` after each epoch if required
For example: ``m.apply(updateBoostStrength)``
:param m: KWinner module | [
"Function",
"used",
"to",
"update",
"KWinner",
"modules",
"boost",
"strength",
"after",
"each",
"epoch",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/pytorch/modules/k_winners.py#L71-L82 | train | 198,941 |
numenta/htmresearch | htmresearch/frameworks/pytorch/modules/k_winners.py | KWinnersBase.updateBoostStrength | def updateBoostStrength(self):
"""
Update boost strength using given strength factor during training
"""
if self.training:
self.boostStrength = self.boostStrength * self.boostStrengthFactor | python | def updateBoostStrength(self):
"""
Update boost strength using given strength factor during training
"""
if self.training:
self.boostStrength = self.boostStrength * self.boostStrengthFactor | [
"def",
"updateBoostStrength",
"(",
"self",
")",
":",
"if",
"self",
".",
"training",
":",
"self",
".",
"boostStrength",
"=",
"self",
".",
"boostStrength",
"*",
"self",
".",
"boostStrengthFactor"
] | Update boost strength using given strength factor during training | [
"Update",
"boost",
"strength",
"using",
"given",
"strength",
"factor",
"during",
"training"
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/pytorch/modules/k_winners.py#L154-L159 | train | 198,942 |
numenta/htmresearch | htmresearch/frameworks/pytorch/modules/k_winners.py | KWinnersBase.entropy | def entropy(self):
"""
Returns the current total entropy of this layer
"""
if self.k < self.n:
_, entropy = binaryEntropy(self.dutyCycle)
return entropy
else:
return 0 | python | def entropy(self):
"""
Returns the current total entropy of this layer
"""
if self.k < self.n:
_, entropy = binaryEntropy(self.dutyCycle)
return entropy
else:
return 0 | [
"def",
"entropy",
"(",
"self",
")",
":",
"if",
"self",
".",
"k",
"<",
"self",
".",
"n",
":",
"_",
",",
"entropy",
"=",
"binaryEntropy",
"(",
"self",
".",
"dutyCycle",
")",
"return",
"entropy",
"else",
":",
"return",
"0"
] | Returns the current total entropy of this layer | [
"Returns",
"the",
"current",
"total",
"entropy",
"of",
"this",
"layer"
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/pytorch/modules/k_winners.py#L162-L170 | train | 198,943 |
numenta/htmresearch | htmresearch/frameworks/layers/sensor_placement.py | greedySensorPositions | def greedySensorPositions(numSensors, numLocations):
"""
Returns an infinite sequence of sensor placements.
Each return value is a tuple of locations, one location per sensor.
Positions are selected using a simple greedy algorithm. The first priority of
the algorithm is "touch every position an equal number of times". The second
priority is "each individual sensor should touch each position an equal number
of times".
@param numSensors (int)
The number of sensors
@param numLocations (int)
The number of locations
@return (generator of tuples)
The next locations for each sensor. The tuple's length is `numSensors`.
"""
locationViewCounts = [0] * numLocations
locationViewCountsBySensor = [[0] * numLocations
for _ in xrange(numSensors)]
placement = random.sample(xrange(numLocations), numSensors)
while True:
yield tuple(placement)
# Update statistics.
for sensor, location in enumerate(placement):
locationViewCounts[location] += 1
locationViewCountsBySensor[sensor][location] += 1
# Choose the locations with the lowest view counts. Break ties randomly.
nextLocationsRanked = sorted(xrange(numLocations),
key=lambda x: (locationViewCounts[x],
random.random()))
nextLocations = nextLocationsRanked[:numSensors]
# For each sensor (in random order), choose the location that has touched
# the least, breaking ties randomly.
sensors = range(numSensors)
random.shuffle(sensors)
for sensor in sensors:
viewCount = min(locationViewCountsBySensor[sensor][location]
for location in nextLocations)
location = random.choice([x for x in nextLocations
if locationViewCountsBySensor[sensor][x]
== viewCount])
nextLocations.remove(location)
placement[sensor] = location | python | def greedySensorPositions(numSensors, numLocations):
"""
Returns an infinite sequence of sensor placements.
Each return value is a tuple of locations, one location per sensor.
Positions are selected using a simple greedy algorithm. The first priority of
the algorithm is "touch every position an equal number of times". The second
priority is "each individual sensor should touch each position an equal number
of times".
@param numSensors (int)
The number of sensors
@param numLocations (int)
The number of locations
@return (generator of tuples)
The next locations for each sensor. The tuple's length is `numSensors`.
"""
locationViewCounts = [0] * numLocations
locationViewCountsBySensor = [[0] * numLocations
for _ in xrange(numSensors)]
placement = random.sample(xrange(numLocations), numSensors)
while True:
yield tuple(placement)
# Update statistics.
for sensor, location in enumerate(placement):
locationViewCounts[location] += 1
locationViewCountsBySensor[sensor][location] += 1
# Choose the locations with the lowest view counts. Break ties randomly.
nextLocationsRanked = sorted(xrange(numLocations),
key=lambda x: (locationViewCounts[x],
random.random()))
nextLocations = nextLocationsRanked[:numSensors]
# For each sensor (in random order), choose the location that has touched
# the least, breaking ties randomly.
sensors = range(numSensors)
random.shuffle(sensors)
for sensor in sensors:
viewCount = min(locationViewCountsBySensor[sensor][location]
for location in nextLocations)
location = random.choice([x for x in nextLocations
if locationViewCountsBySensor[sensor][x]
== viewCount])
nextLocations.remove(location)
placement[sensor] = location | [
"def",
"greedySensorPositions",
"(",
"numSensors",
",",
"numLocations",
")",
":",
"locationViewCounts",
"=",
"[",
"0",
"]",
"*",
"numLocations",
"locationViewCountsBySensor",
"=",
"[",
"[",
"0",
"]",
"*",
"numLocations",
"for",
"_",
"in",
"xrange",
"(",
"numSe... | Returns an infinite sequence of sensor placements.
Each return value is a tuple of locations, one location per sensor.
Positions are selected using a simple greedy algorithm. The first priority of
the algorithm is "touch every position an equal number of times". The second
priority is "each individual sensor should touch each position an equal number
of times".
@param numSensors (int)
The number of sensors
@param numLocations (int)
The number of locations
@return (generator of tuples)
The next locations for each sensor. The tuple's length is `numSensors`. | [
"Returns",
"an",
"infinite",
"sequence",
"of",
"sensor",
"placements",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/sensor_placement.py#L26-L78 | train | 198,944 |
numenta/htmresearch | htmresearch/regions/ApicalTMPairRegion.py | ApicalTMPairRegion.initialize | def initialize(self):
"""
Initialize the self._tm if not already initialized.
"""
if self._tm is None:
params = {
"columnCount": self.columnCount,
"basalInputSize": self.basalInputWidth,
"apicalInputSize": self.apicalInputWidth,
"cellsPerColumn": self.cellsPerColumn,
"activationThreshold": self.activationThreshold,
"initialPermanence": self.initialPermanence,
"connectedPermanence": self.connectedPermanence,
"minThreshold": self.minThreshold,
"sampleSize": self.sampleSize,
"permanenceIncrement": self.permanenceIncrement,
"permanenceDecrement": self.permanenceDecrement,
"basalPredictedSegmentDecrement": self.basalPredictedSegmentDecrement,
"apicalPredictedSegmentDecrement": self.apicalPredictedSegmentDecrement,
"maxSynapsesPerSegment": self.maxSynapsesPerSegment,
"seed": self.seed,
}
if self.implementation == "ApicalTiebreakCPP":
params["learnOnOneCell"] = self.learnOnOneCell
params["maxSegmentsPerCell"] = self.maxSegmentsPerCell
import htmresearch_core.experimental
cls = htmresearch_core.experimental.ApicalTiebreakPairMemory
elif self.implementation == "ApicalTiebreak":
params["reducedBasalThreshold"] = self.reducedBasalThreshold
import htmresearch.algorithms.apical_tiebreak_temporal_memory
cls = htmresearch.algorithms.apical_tiebreak_temporal_memory.ApicalTiebreakPairMemory
elif self.implementation == "ApicalDependent":
params["reducedBasalThreshold"] = self.reducedBasalThreshold
import htmresearch.algorithms.apical_dependent_temporal_memory
cls = htmresearch.algorithms.apical_dependent_temporal_memory.TripleMemory
else:
raise ValueError("Unrecognized implementation %s" % self.implementation)
self._tm = cls(**params) | python | def initialize(self):
"""
Initialize the self._tm if not already initialized.
"""
if self._tm is None:
params = {
"columnCount": self.columnCount,
"basalInputSize": self.basalInputWidth,
"apicalInputSize": self.apicalInputWidth,
"cellsPerColumn": self.cellsPerColumn,
"activationThreshold": self.activationThreshold,
"initialPermanence": self.initialPermanence,
"connectedPermanence": self.connectedPermanence,
"minThreshold": self.minThreshold,
"sampleSize": self.sampleSize,
"permanenceIncrement": self.permanenceIncrement,
"permanenceDecrement": self.permanenceDecrement,
"basalPredictedSegmentDecrement": self.basalPredictedSegmentDecrement,
"apicalPredictedSegmentDecrement": self.apicalPredictedSegmentDecrement,
"maxSynapsesPerSegment": self.maxSynapsesPerSegment,
"seed": self.seed,
}
if self.implementation == "ApicalTiebreakCPP":
params["learnOnOneCell"] = self.learnOnOneCell
params["maxSegmentsPerCell"] = self.maxSegmentsPerCell
import htmresearch_core.experimental
cls = htmresearch_core.experimental.ApicalTiebreakPairMemory
elif self.implementation == "ApicalTiebreak":
params["reducedBasalThreshold"] = self.reducedBasalThreshold
import htmresearch.algorithms.apical_tiebreak_temporal_memory
cls = htmresearch.algorithms.apical_tiebreak_temporal_memory.ApicalTiebreakPairMemory
elif self.implementation == "ApicalDependent":
params["reducedBasalThreshold"] = self.reducedBasalThreshold
import htmresearch.algorithms.apical_dependent_temporal_memory
cls = htmresearch.algorithms.apical_dependent_temporal_memory.TripleMemory
else:
raise ValueError("Unrecognized implementation %s" % self.implementation)
self._tm = cls(**params) | [
"def",
"initialize",
"(",
"self",
")",
":",
"if",
"self",
".",
"_tm",
"is",
"None",
":",
"params",
"=",
"{",
"\"columnCount\"",
":",
"self",
".",
"columnCount",
",",
"\"basalInputSize\"",
":",
"self",
".",
"basalInputWidth",
",",
"\"apicalInputSize\"",
":",
... | Initialize the self._tm if not already initialized. | [
"Initialize",
"the",
"self",
".",
"_tm",
"if",
"not",
"already",
"initialized",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/regions/ApicalTMPairRegion.py#L374-L420 | train | 198,945 |
numenta/htmresearch | htmresearch/regions/ApicalTMPairRegion.py | ApicalTMPairRegion.getOutputElementCount | def getOutputElementCount(self, name):
"""
Return the number of elements for the given output.
"""
if name in ["activeCells", "predictedCells", "predictedActiveCells",
"winnerCells"]:
return self.cellsPerColumn * self.columnCount
else:
raise Exception("Invalid output name specified: %s" % name) | python | def getOutputElementCount(self, name):
"""
Return the number of elements for the given output.
"""
if name in ["activeCells", "predictedCells", "predictedActiveCells",
"winnerCells"]:
return self.cellsPerColumn * self.columnCount
else:
raise Exception("Invalid output name specified: %s" % name) | [
"def",
"getOutputElementCount",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"[",
"\"activeCells\"",
",",
"\"predictedCells\"",
",",
"\"predictedActiveCells\"",
",",
"\"winnerCells\"",
"]",
":",
"return",
"self",
".",
"cellsPerColumn",
"*",
"self",
".... | Return the number of elements for the given output. | [
"Return",
"the",
"number",
"of",
"elements",
"for",
"the",
"given",
"output",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/regions/ApicalTMPairRegion.py#L504-L512 | train | 198,946 |
numenta/htmresearch | projects/feedback/feedback_experiment.py | FeedbackExperiment.learnSequences | def learnSequences(self, sequences):
"""
Learns all provided sequences. Always reset the network in between
sequences.
Sequences format:
sequences = [
[
set([16, 22, 32]), # S0, position 0
set([13, 15, 33]) # S0, position 1
],
[
set([6, 12, 52]), # S1, position 0
set([6, 2, 15]) # S1, position 1
],
]
Note that the order of each sequence is important. It denotes the sequence
number and will be used during inference to plot accuracy.
Parameters:
----------------------------
@param sequences (list)
Sequences to learn, in the canonical format specified above
"""
# This method goes through four phases:
# 1) We first train L4 on the sequences, over multiple passes
# 2) We then train L2 in one pass.
# 3) We then continue training on L4 so the apical segments learn
# 4) We run inference to store L2 representations for each sequence
# retrieve L2 representations
# print "1) Train L4 sequence memory"
# We're now using online learning, so both layers should be trying to learn
# at all times.
sequence_order = range(len(sequences))
if self.config["L2Params"]["onlineLearning"]:
# Train L2 and L4
self._setLearningMode(l4Learning=True, l2Learning=True)
for _ in xrange(self.numLearningPoints):
random.shuffle(sequence_order)
for i in sequence_order:
sequence = sequences[i]
for s in sequence:
self.sensorInputs[0].addDataToQueue(list(s), 0, 0)
self.network.run(1)
# This is equivalent to, and faster than, giving the network no input
# for a period of time.
self.sendReset()
else:
# Train L4
self._setLearningMode(l4Learning=True, l2Learning=False)
for _ in xrange(self.numLearningPoints):
random.shuffle(sequence_order)
for i in sequence_order:
sequence = sequences[i]
for s in sequence:
self.sensorInputs[0].addDataToQueue(list(s), 0, 0)
self.network.run(1)
# This is equivalent to, and faster than, giving the network no input
# for a period of time.
self.sendReset()
# Train L2
self._setLearningMode(l4Learning=False, l2Learning=True)
for i in sequence_order:
sequence = sequences[i]
for s in sequence:
self.sensorInputs[0].addDataToQueue(list(s), 0, 0)
self.network.run(1)
self.sendReset()
# Train L4 apical segments
self._setLearningMode(l4Learning=True, l2Learning=False)
for _ in xrange(5):
for i in sequence_order:
sequence = sequences[i]
for s in sequence:
self.sensorInputs[0].addDataToQueue(list(s), 0, 0)
self.network.run(1)
self.sendReset()
self._setLearningMode(l4Learning=False, l2Learning=False)
self.sendReset()
for sequenceNum, sequence in enumerate(sequences):
for s in sequence:
self.sensorInputs[0].addDataToQueue(list(s), 0, 0)
self.network.run(1)
self.objectL2Representations[sequenceNum] = self.getL2Representations()
self.sendReset()
return | python | def learnSequences(self, sequences):
"""
Learns all provided sequences. Always reset the network in between
sequences.
Sequences format:
sequences = [
[
set([16, 22, 32]), # S0, position 0
set([13, 15, 33]) # S0, position 1
],
[
set([6, 12, 52]), # S1, position 0
set([6, 2, 15]) # S1, position 1
],
]
Note that the order of each sequence is important. It denotes the sequence
number and will be used during inference to plot accuracy.
Parameters:
----------------------------
@param sequences (list)
Sequences to learn, in the canonical format specified above
"""
# This method goes through four phases:
# 1) We first train L4 on the sequences, over multiple passes
# 2) We then train L2 in one pass.
# 3) We then continue training on L4 so the apical segments learn
# 4) We run inference to store L2 representations for each sequence
# retrieve L2 representations
# print "1) Train L4 sequence memory"
# We're now using online learning, so both layers should be trying to learn
# at all times.
sequence_order = range(len(sequences))
if self.config["L2Params"]["onlineLearning"]:
# Train L2 and L4
self._setLearningMode(l4Learning=True, l2Learning=True)
for _ in xrange(self.numLearningPoints):
random.shuffle(sequence_order)
for i in sequence_order:
sequence = sequences[i]
for s in sequence:
self.sensorInputs[0].addDataToQueue(list(s), 0, 0)
self.network.run(1)
# This is equivalent to, and faster than, giving the network no input
# for a period of time.
self.sendReset()
else:
# Train L4
self._setLearningMode(l4Learning=True, l2Learning=False)
for _ in xrange(self.numLearningPoints):
random.shuffle(sequence_order)
for i in sequence_order:
sequence = sequences[i]
for s in sequence:
self.sensorInputs[0].addDataToQueue(list(s), 0, 0)
self.network.run(1)
# This is equivalent to, and faster than, giving the network no input
# for a period of time.
self.sendReset()
# Train L2
self._setLearningMode(l4Learning=False, l2Learning=True)
for i in sequence_order:
sequence = sequences[i]
for s in sequence:
self.sensorInputs[0].addDataToQueue(list(s), 0, 0)
self.network.run(1)
self.sendReset()
# Train L4 apical segments
self._setLearningMode(l4Learning=True, l2Learning=False)
for _ in xrange(5):
for i in sequence_order:
sequence = sequences[i]
for s in sequence:
self.sensorInputs[0].addDataToQueue(list(s), 0, 0)
self.network.run(1)
self.sendReset()
self._setLearningMode(l4Learning=False, l2Learning=False)
self.sendReset()
for sequenceNum, sequence in enumerate(sequences):
for s in sequence:
self.sensorInputs[0].addDataToQueue(list(s), 0, 0)
self.network.run(1)
self.objectL2Representations[sequenceNum] = self.getL2Representations()
self.sendReset()
return | [
"def",
"learnSequences",
"(",
"self",
",",
"sequences",
")",
":",
"# This method goes through four phases:",
"# 1) We first train L4 on the sequences, over multiple passes",
"# 2) We then train L2 in one pass.",
"# 3) We then continue training on L4 so the apical segments learn",
"# ... | Learns all provided sequences. Always reset the network in between
sequences.
Sequences format:
sequences = [
[
set([16, 22, 32]), # S0, position 0
set([13, 15, 33]) # S0, position 1
],
[
set([6, 12, 52]), # S1, position 0
set([6, 2, 15]) # S1, position 1
],
]
Note that the order of each sequence is important. It denotes the sequence
number and will be used during inference to plot accuracy.
Parameters:
----------------------------
@param sequences (list)
Sequences to learn, in the canonical format specified above | [
"Learns",
"all",
"provided",
"sequences",
".",
"Always",
"reset",
"the",
"network",
"in",
"between",
"sequences",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/feedback/feedback_experiment.py#L197-L292 | train | 198,947 |
numenta/htmresearch | projects/feedback/feedback_experiment.py | FeedbackExperiment.getL4PredictedActiveCells | def getL4PredictedActiveCells(self):
"""
Returns the predicted active cells in each column in L4.
"""
predictedActive = []
for i in xrange(self.numColumns):
region = self.network.regions["L4Column_" + str(i)]
predictedActive.append(
region.getOutputData("predictedActiveCells").nonzero()[0])
return predictedActive | python | def getL4PredictedActiveCells(self):
"""
Returns the predicted active cells in each column in L4.
"""
predictedActive = []
for i in xrange(self.numColumns):
region = self.network.regions["L4Column_" + str(i)]
predictedActive.append(
region.getOutputData("predictedActiveCells").nonzero()[0])
return predictedActive | [
"def",
"getL4PredictedActiveCells",
"(",
"self",
")",
":",
"predictedActive",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"self",
".",
"numColumns",
")",
":",
"region",
"=",
"self",
".",
"network",
".",
"regions",
"[",
"\"L4Column_\"",
"+",
"str",
"(... | Returns the predicted active cells in each column in L4. | [
"Returns",
"the",
"predicted",
"active",
"cells",
"in",
"each",
"column",
"in",
"L4",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/feedback/feedback_experiment.py#L397-L406 | train | 198,948 |
numenta/htmresearch | projects/feedback/feedback_experiment.py | FeedbackExperiment._setLearningMode | def _setLearningMode(self, l4Learning = False, l2Learning=False):
"""
Sets the learning mode for L4 and L2.
"""
for column in self.L4Columns:
column.setParameter("learn", 0, l4Learning)
for column in self.L2Columns:
column.setParameter("learningMode", 0, l2Learning) | python | def _setLearningMode(self, l4Learning = False, l2Learning=False):
"""
Sets the learning mode for L4 and L2.
"""
for column in self.L4Columns:
column.setParameter("learn", 0, l4Learning)
for column in self.L2Columns:
column.setParameter("learningMode", 0, l2Learning) | [
"def",
"_setLearningMode",
"(",
"self",
",",
"l4Learning",
"=",
"False",
",",
"l2Learning",
"=",
"False",
")",
":",
"for",
"column",
"in",
"self",
".",
"L4Columns",
":",
"column",
".",
"setParameter",
"(",
"\"learn\"",
",",
"0",
",",
"l4Learning",
")",
"... | Sets the learning mode for L4 and L2. | [
"Sets",
"the",
"learning",
"mode",
"for",
"L4",
"and",
"L2",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/feedback/feedback_experiment.py#L472-L479 | train | 198,949 |
numenta/htmresearch | projects/combined_sequences/combined_sequences.py | printDiagnosticsAfterTraining | def printDiagnosticsAfterTraining(exp, verbosity=0):
"""Useful diagnostics a trained system for debugging."""
print "Number of connected synapses per cell"
l2 = exp.getAlgorithmInstance("L2")
numConnectedCells = 0
connectedSynapses = 0
for c in range(4096):
cp = l2.numberOfConnectedProximalSynapses([c])
if cp>0:
# print c, ":", cp
numConnectedCells += 1
connectedSynapses += cp
print "Num L2 cells with connected synapses:", numConnectedCells
if numConnectedCells > 0:
print "Avg connected synapses per connected cell:", float(connectedSynapses)/numConnectedCells
print | python | def printDiagnosticsAfterTraining(exp, verbosity=0):
"""Useful diagnostics a trained system for debugging."""
print "Number of connected synapses per cell"
l2 = exp.getAlgorithmInstance("L2")
numConnectedCells = 0
connectedSynapses = 0
for c in range(4096):
cp = l2.numberOfConnectedProximalSynapses([c])
if cp>0:
# print c, ":", cp
numConnectedCells += 1
connectedSynapses += cp
print "Num L2 cells with connected synapses:", numConnectedCells
if numConnectedCells > 0:
print "Avg connected synapses per connected cell:", float(connectedSynapses)/numConnectedCells
print | [
"def",
"printDiagnosticsAfterTraining",
"(",
"exp",
",",
"verbosity",
"=",
"0",
")",
":",
"print",
"\"Number of connected synapses per cell\"",
"l2",
"=",
"exp",
".",
"getAlgorithmInstance",
"(",
"\"L2\"",
")",
"numConnectedCells",
"=",
"0",
"connectedSynapses",
"=",
... | Useful diagnostics a trained system for debugging. | [
"Useful",
"diagnostics",
"a",
"trained",
"system",
"for",
"debugging",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/combined_sequences/combined_sequences.py#L78-L96 | train | 198,950 |
numenta/htmresearch | projects/combined_sequences/combined_sequences.py | trainSequences | def trainSequences(sequences, exp, idOffset=0):
"""Train the network on all the sequences"""
for seqId in sequences:
# Make sure we learn enough times to deal with high order sequences and
# remove extra predictions.
iterations = 3*len(sequences[seqId])
for p in range(iterations):
# Ensure we generate new random location for each sequence presentation
s = sequences.provideObjectsToLearn([seqId])
objectSDRs = dict()
objectSDRs[seqId + idOffset] = s[seqId]
exp.learnObjects(objectSDRs, reset=False)
# TM needs reset between sequences, but not other regions
exp.TMColumns[0].reset()
# L2 needs resets when we switch to new object
exp.sendReset() | python | def trainSequences(sequences, exp, idOffset=0):
"""Train the network on all the sequences"""
for seqId in sequences:
# Make sure we learn enough times to deal with high order sequences and
# remove extra predictions.
iterations = 3*len(sequences[seqId])
for p in range(iterations):
# Ensure we generate new random location for each sequence presentation
s = sequences.provideObjectsToLearn([seqId])
objectSDRs = dict()
objectSDRs[seqId + idOffset] = s[seqId]
exp.learnObjects(objectSDRs, reset=False)
# TM needs reset between sequences, but not other regions
exp.TMColumns[0].reset()
# L2 needs resets when we switch to new object
exp.sendReset() | [
"def",
"trainSequences",
"(",
"sequences",
",",
"exp",
",",
"idOffset",
"=",
"0",
")",
":",
"for",
"seqId",
"in",
"sequences",
":",
"# Make sure we learn enough times to deal with high order sequences and",
"# remove extra predictions.",
"iterations",
"=",
"3",
"*",
"le... | Train the network on all the sequences | [
"Train",
"the",
"network",
"on",
"all",
"the",
"sequences"
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/combined_sequences/combined_sequences.py#L99-L117 | train | 198,951 |
numenta/htmresearch | projects/combined_sequences/combined_sequences.py | trainObjects | def trainObjects(objects, exp, numRepeatsPerObject, experimentIdOffset=0):
"""
Train the network on all the objects by randomly traversing points on
each object. We offset the id of each object to avoid confusion with
any sequences that might have been learned.
"""
# We want to traverse the features of each object randomly a few times before
# moving on to the next object. Create the SDRs that we need for this.
objectsToLearn = objects.provideObjectsToLearn()
objectTraversals = {}
for objectId in objectsToLearn:
objectTraversals[objectId + experimentIdOffset] = objects.randomTraversal(
objectsToLearn[objectId], numRepeatsPerObject)
# Train the network on all the SDRs for all the objects
exp.learnObjects(objectTraversals) | python | def trainObjects(objects, exp, numRepeatsPerObject, experimentIdOffset=0):
"""
Train the network on all the objects by randomly traversing points on
each object. We offset the id of each object to avoid confusion with
any sequences that might have been learned.
"""
# We want to traverse the features of each object randomly a few times before
# moving on to the next object. Create the SDRs that we need for this.
objectsToLearn = objects.provideObjectsToLearn()
objectTraversals = {}
for objectId in objectsToLearn:
objectTraversals[objectId + experimentIdOffset] = objects.randomTraversal(
objectsToLearn[objectId], numRepeatsPerObject)
# Train the network on all the SDRs for all the objects
exp.learnObjects(objectTraversals) | [
"def",
"trainObjects",
"(",
"objects",
",",
"exp",
",",
"numRepeatsPerObject",
",",
"experimentIdOffset",
"=",
"0",
")",
":",
"# We want to traverse the features of each object randomly a few times before",
"# moving on to the next object. Create the SDRs that we need for this.",
"ob... | Train the network on all the objects by randomly traversing points on
each object. We offset the id of each object to avoid confusion with
any sequences that might have been learned. | [
"Train",
"the",
"network",
"on",
"all",
"the",
"objects",
"by",
"randomly",
"traversing",
"points",
"on",
"each",
"object",
".",
"We",
"offset",
"the",
"id",
"of",
"each",
"object",
"to",
"avoid",
"confusion",
"with",
"any",
"sequences",
"that",
"might",
"... | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/combined_sequences/combined_sequences.py#L120-L135 | train | 198,952 |
numenta/htmresearch | projects/combined_sequences/combined_sequences.py | inferObject | def inferObject(exp, objectId, objects, objectName):
"""
Run inference on the given object.
objectName is the name of this object in the experiment.
"""
# Create sequence of random sensations for this object for one column. The
# total number of sensations is equal to the number of points on the object.
# No point should be visited more than once.
objectSensations = {}
objectSensations[0] = []
obj = objects[objectId]
objectCopy = [pair for pair in obj]
random.shuffle(objectCopy)
for pair in objectCopy:
objectSensations[0].append(pair)
inferConfig = {
"numSteps": len(objectSensations[0]),
"pairs": objectSensations,
"includeRandomLocation": False,
}
inferenceSDRs = objects.provideObjectToInfer(inferConfig)
exp.infer(inferenceSDRs, objectName=objectName) | python | def inferObject(exp, objectId, objects, objectName):
"""
Run inference on the given object.
objectName is the name of this object in the experiment.
"""
# Create sequence of random sensations for this object for one column. The
# total number of sensations is equal to the number of points on the object.
# No point should be visited more than once.
objectSensations = {}
objectSensations[0] = []
obj = objects[objectId]
objectCopy = [pair for pair in obj]
random.shuffle(objectCopy)
for pair in objectCopy:
objectSensations[0].append(pair)
inferConfig = {
"numSteps": len(objectSensations[0]),
"pairs": objectSensations,
"includeRandomLocation": False,
}
inferenceSDRs = objects.provideObjectToInfer(inferConfig)
exp.infer(inferenceSDRs, objectName=objectName) | [
"def",
"inferObject",
"(",
"exp",
",",
"objectId",
",",
"objects",
",",
"objectName",
")",
":",
"# Create sequence of random sensations for this object for one column. The",
"# total number of sensations is equal to the number of points on the object.",
"# No point should be visited more... | Run inference on the given object.
objectName is the name of this object in the experiment. | [
"Run",
"inference",
"on",
"the",
"given",
"object",
".",
"objectName",
"is",
"the",
"name",
"of",
"this",
"object",
"in",
"the",
"experiment",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/combined_sequences/combined_sequences.py#L155-L180 | train | 198,953 |
numenta/htmresearch | projects/combined_sequences/combined_sequences.py | createSuperimposedSensorySDRs | def createSuperimposedSensorySDRs(sequenceSensations, objectSensations):
"""
Given two lists of sensations, create a new list where the sensory SDRs are
union of the individual sensory SDRs. Keep the location SDRs from the object.
A list of sensations has the following format:
[
{
0: (set([1, 5, 10]), set([6, 12, 52]), # location, feature for CC0
},
{
0: (set([5, 46, 50]), set([8, 10, 11]), # location, feature for CC0
},
]
We assume there is only one cortical column, and that the two input lists have
identical length.
"""
assert len(sequenceSensations) == len(objectSensations)
superimposedSensations = []
for i, objectSensation in enumerate(objectSensations):
# print "sequence loc:", sequenceSensations[i][0][0]
# print "object loc: ",objectSensation[0][0]
# print
# print "sequence feat:", sequenceSensations[i][0][1]
# print "object feat: ",objectSensation[0][1]
# print
newSensation = {
0: (objectSensation[0][0],
sequenceSensations[i][0][1].union(objectSensation[0][1]))
}
# newSensation = {
# 0: (objectSensation[0][0],objectSensation[0][1])
# }
superimposedSensations.append(newSensation)
# print newSensation
# print
# print
return superimposedSensations | python | def createSuperimposedSensorySDRs(sequenceSensations, objectSensations):
"""
Given two lists of sensations, create a new list where the sensory SDRs are
union of the individual sensory SDRs. Keep the location SDRs from the object.
A list of sensations has the following format:
[
{
0: (set([1, 5, 10]), set([6, 12, 52]), # location, feature for CC0
},
{
0: (set([5, 46, 50]), set([8, 10, 11]), # location, feature for CC0
},
]
We assume there is only one cortical column, and that the two input lists have
identical length.
"""
assert len(sequenceSensations) == len(objectSensations)
superimposedSensations = []
for i, objectSensation in enumerate(objectSensations):
# print "sequence loc:", sequenceSensations[i][0][0]
# print "object loc: ",objectSensation[0][0]
# print
# print "sequence feat:", sequenceSensations[i][0][1]
# print "object feat: ",objectSensation[0][1]
# print
newSensation = {
0: (objectSensation[0][0],
sequenceSensations[i][0][1].union(objectSensation[0][1]))
}
# newSensation = {
# 0: (objectSensation[0][0],objectSensation[0][1])
# }
superimposedSensations.append(newSensation)
# print newSensation
# print
# print
return superimposedSensations | [
"def",
"createSuperimposedSensorySDRs",
"(",
"sequenceSensations",
",",
"objectSensations",
")",
":",
"assert",
"len",
"(",
"sequenceSensations",
")",
"==",
"len",
"(",
"objectSensations",
")",
"superimposedSensations",
"=",
"[",
"]",
"for",
"i",
",",
"objectSensati... | Given two lists of sensations, create a new list where the sensory SDRs are
union of the individual sensory SDRs. Keep the location SDRs from the object.
A list of sensations has the following format:
[
{
0: (set([1, 5, 10]), set([6, 12, 52]), # location, feature for CC0
},
{
0: (set([5, 46, 50]), set([8, 10, 11]), # location, feature for CC0
},
]
We assume there is only one cortical column, and that the two input lists have
identical length. | [
"Given",
"two",
"lists",
"of",
"sensations",
"create",
"a",
"new",
"list",
"where",
"the",
"sensory",
"SDRs",
"are",
"union",
"of",
"the",
"individual",
"sensory",
"SDRs",
".",
"Keep",
"the",
"location",
"SDRs",
"from",
"the",
"object",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/combined_sequences/combined_sequences.py#L206-L246 | train | 198,954 |
numenta/htmresearch | projects/combined_sequences/combined_sequences.py | runExperimentPool | def runExperimentPool(numSequences,
numFeatures,
numLocations,
numObjects,
numWorkers=7,
nTrials=1,
seqLength=10,
figure="",
numRepetitions=1,
synPermProximalDecL2=[0.001],
minThresholdProximalL2=[10],
sampleSizeProximalL2=[15],
inputSize=[1024],
basalPredictedSegmentDecrement=[0.0006],
resultsName="convergence_results.pkl"):
"""
Run a bunch of experiments using a pool of numWorkers multiple processes. For
numSequences, numFeatures, and numLocations pass in a list containing valid
values for that parameter. The cross product of everything is run, and each
combination is run nTrials times.
Returns a list of dict containing detailed results from each experiment. Also
pickles and saves all the results in resultsName for later analysis.
If numWorkers == 1, the experiments will be run in a single thread. This makes
it easier to debug.
Example:
results = runExperimentPool(
numSequences=[10, 20],
numFeatures=[5, 13],
numWorkers=8,
nTrials=5)
"""
# Create function arguments for every possibility
args = []
for bd in basalPredictedSegmentDecrement:
for i in inputSize:
for thresh in minThresholdProximalL2:
for dec in synPermProximalDecL2:
for s in sampleSizeProximalL2:
for o in reversed(numSequences):
for l in numLocations:
for f in numFeatures:
for no in numObjects:
for t in range(nTrials):
args.append(
{"numSequences": o,
"numFeatures": f,
"numObjects": no,
"trialNum": t,
"seqLength": seqLength,
"numLocations": l,
"sampleSizeProximalL2": s,
"synPermProximalDecL2": dec,
"minThresholdProximalL2": thresh,
"numRepetitions": numRepetitions,
"figure": figure,
"inputSize": i,
"basalPredictedSegmentDecrement": bd,
}
)
print "{} experiments to run, {} workers".format(len(args), numWorkers)
# Run the pool
if numWorkers > 1:
pool = Pool(processes=numWorkers)
result = pool.map(runExperiment, args)
else:
result = []
for arg in args:
result.append(runExperiment(arg))
# Pickle results for later use
with open(resultsName,"wb") as f:
cPickle.dump(result,f)
return result | python | def runExperimentPool(numSequences,
numFeatures,
numLocations,
numObjects,
numWorkers=7,
nTrials=1,
seqLength=10,
figure="",
numRepetitions=1,
synPermProximalDecL2=[0.001],
minThresholdProximalL2=[10],
sampleSizeProximalL2=[15],
inputSize=[1024],
basalPredictedSegmentDecrement=[0.0006],
resultsName="convergence_results.pkl"):
"""
Run a bunch of experiments using a pool of numWorkers multiple processes. For
numSequences, numFeatures, and numLocations pass in a list containing valid
values for that parameter. The cross product of everything is run, and each
combination is run nTrials times.
Returns a list of dict containing detailed results from each experiment. Also
pickles and saves all the results in resultsName for later analysis.
If numWorkers == 1, the experiments will be run in a single thread. This makes
it easier to debug.
Example:
results = runExperimentPool(
numSequences=[10, 20],
numFeatures=[5, 13],
numWorkers=8,
nTrials=5)
"""
# Create function arguments for every possibility
args = []
for bd in basalPredictedSegmentDecrement:
for i in inputSize:
for thresh in minThresholdProximalL2:
for dec in synPermProximalDecL2:
for s in sampleSizeProximalL2:
for o in reversed(numSequences):
for l in numLocations:
for f in numFeatures:
for no in numObjects:
for t in range(nTrials):
args.append(
{"numSequences": o,
"numFeatures": f,
"numObjects": no,
"trialNum": t,
"seqLength": seqLength,
"numLocations": l,
"sampleSizeProximalL2": s,
"synPermProximalDecL2": dec,
"minThresholdProximalL2": thresh,
"numRepetitions": numRepetitions,
"figure": figure,
"inputSize": i,
"basalPredictedSegmentDecrement": bd,
}
)
print "{} experiments to run, {} workers".format(len(args), numWorkers)
# Run the pool
if numWorkers > 1:
pool = Pool(processes=numWorkers)
result = pool.map(runExperiment, args)
else:
result = []
for arg in args:
result.append(runExperiment(arg))
# Pickle results for later use
with open(resultsName,"wb") as f:
cPickle.dump(result,f)
return result | [
"def",
"runExperimentPool",
"(",
"numSequences",
",",
"numFeatures",
",",
"numLocations",
",",
"numObjects",
",",
"numWorkers",
"=",
"7",
",",
"nTrials",
"=",
"1",
",",
"seqLength",
"=",
"10",
",",
"figure",
"=",
"\"\"",
",",
"numRepetitions",
"=",
"1",
",... | Run a bunch of experiments using a pool of numWorkers multiple processes. For
numSequences, numFeatures, and numLocations pass in a list containing valid
values for that parameter. The cross product of everything is run, and each
combination is run nTrials times.
Returns a list of dict containing detailed results from each experiment. Also
pickles and saves all the results in resultsName for later analysis.
If numWorkers == 1, the experiments will be run in a single thread. This makes
it easier to debug.
Example:
results = runExperimentPool(
numSequences=[10, 20],
numFeatures=[5, 13],
numWorkers=8,
nTrials=5) | [
"Run",
"a",
"bunch",
"of",
"experiments",
"using",
"a",
"pool",
"of",
"numWorkers",
"multiple",
"processes",
".",
"For",
"numSequences",
"numFeatures",
"and",
"numLocations",
"pass",
"in",
"a",
"list",
"containing",
"valid",
"values",
"for",
"that",
"parameter",... | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/combined_sequences/combined_sequences.py#L581-L659 | train | 198,955 |
numenta/htmresearch | projects/combined_sequences/combined_sequences.py | runExperiment5A | def runExperiment5A(dirName):
"""
This runs the first experiment in the section "Simulations with Sensorimotor
Sequences", an example sensorimotor sequence.
"""
# Results are put into a pkl file which can be used to generate the plots.
# dirName is the absolute path where the pkl file will be placed.
resultsFilename = os.path.join(dirName, "sensorimotor_sequence_example.pkl")
results = runExperiment(
{
"numSequences": 0,
"seqLength": 10,
"numFeatures": 100,
"trialNum": 4,
"numObjects": 50,
"numLocations": 100,
}
)
# Pickle results for plotting and possible later debugging
with open(resultsFilename, "wb") as f:
cPickle.dump(results, f) | python | def runExperiment5A(dirName):
"""
This runs the first experiment in the section "Simulations with Sensorimotor
Sequences", an example sensorimotor sequence.
"""
# Results are put into a pkl file which can be used to generate the plots.
# dirName is the absolute path where the pkl file will be placed.
resultsFilename = os.path.join(dirName, "sensorimotor_sequence_example.pkl")
results = runExperiment(
{
"numSequences": 0,
"seqLength": 10,
"numFeatures": 100,
"trialNum": 4,
"numObjects": 50,
"numLocations": 100,
}
)
# Pickle results for plotting and possible later debugging
with open(resultsFilename, "wb") as f:
cPickle.dump(results, f) | [
"def",
"runExperiment5A",
"(",
"dirName",
")",
":",
"# Results are put into a pkl file which can be used to generate the plots.",
"# dirName is the absolute path where the pkl file will be placed.",
"resultsFilename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirName",
",",
"\"s... | This runs the first experiment in the section "Simulations with Sensorimotor
Sequences", an example sensorimotor sequence. | [
"This",
"runs",
"the",
"first",
"experiment",
"in",
"the",
"section",
"Simulations",
"with",
"Sensorimotor",
"Sequences",
"an",
"example",
"sensorimotor",
"sequence",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/combined_sequences/combined_sequences.py#L759-L780 | train | 198,956 |
numenta/htmresearch | projects/combined_sequences/combined_sequences.py | runExperiment5B | def runExperiment5B(dirName):
"""
This runs the second experiment in the section "Simulations with Sensorimotor
Sequences". It averages over many parameter combinations. This experiment
could take several hours. You can run faster versions by reducing the number
of trials.
"""
# Results are put into a pkl file which can be used to generate the plots.
# dirName is the absolute path where the pkl file will be placed.
resultsName = os.path.join(dirName, "sensorimotor_batch_results_more_objects.pkl")
# We run 10 trials for each column number and then analyze results
numTrials = 10
featureRange = [10, 50, 100, 150, 500]
objectRange = [110, 130, 200, 300]
locationRange = [100]
# Comment this out if you are re-running analysis on already saved results.
# Very useful for debugging the plots
runExperimentPool(
numSequences=[0],
numObjects=objectRange,
numFeatures=featureRange,
numLocations=locationRange,
nTrials=numTrials,
numWorkers=cpu_count() - 1,
numRepetitions=10,
resultsName=resultsName) | python | def runExperiment5B(dirName):
"""
This runs the second experiment in the section "Simulations with Sensorimotor
Sequences". It averages over many parameter combinations. This experiment
could take several hours. You can run faster versions by reducing the number
of trials.
"""
# Results are put into a pkl file which can be used to generate the plots.
# dirName is the absolute path where the pkl file will be placed.
resultsName = os.path.join(dirName, "sensorimotor_batch_results_more_objects.pkl")
# We run 10 trials for each column number and then analyze results
numTrials = 10
featureRange = [10, 50, 100, 150, 500]
objectRange = [110, 130, 200, 300]
locationRange = [100]
# Comment this out if you are re-running analysis on already saved results.
# Very useful for debugging the plots
runExperimentPool(
numSequences=[0],
numObjects=objectRange,
numFeatures=featureRange,
numLocations=locationRange,
nTrials=numTrials,
numWorkers=cpu_count() - 1,
numRepetitions=10,
resultsName=resultsName) | [
"def",
"runExperiment5B",
"(",
"dirName",
")",
":",
"# Results are put into a pkl file which can be used to generate the plots.",
"# dirName is the absolute path where the pkl file will be placed.",
"resultsName",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirName",
",",
"\"senso... | This runs the second experiment in the section "Simulations with Sensorimotor
Sequences". It averages over many parameter combinations. This experiment
could take several hours. You can run faster versions by reducing the number
of trials. | [
"This",
"runs",
"the",
"second",
"experiment",
"in",
"the",
"section",
"Simulations",
"with",
"Sensorimotor",
"Sequences",
".",
"It",
"averages",
"over",
"many",
"parameter",
"combinations",
".",
"This",
"experiment",
"could",
"take",
"several",
"hours",
".",
"Y... | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/combined_sequences/combined_sequences.py#L783-L810 | train | 198,957 |
numenta/htmresearch | projects/combined_sequences/combined_sequences.py | runExperiment6 | def runExperiment6(dirName):
"""
This runs the experiment the section "Simulations with Combined Sequences",
an example stream containing a mixture of temporal and sensorimotor sequences.
"""
# Results are put into a pkl file which can be used to generate the plots.
# dirName is the absolute path where the pkl file will be placed.
resultsFilename = os.path.join(dirName, "combined_results.pkl")
results = runExperiment(
{
"numSequences": 50,
"seqLength": 10,
"numObjects": 50,
"numFeatures": 500,
"trialNum": 8,
"numLocations": 100,
"settlingTime": 1,
"figure": "6",
"numRepetitions": 30,
"basalPredictedSegmentDecrement": 0.001,
"stripStats": False,
}
)
# Pickle results for plotting and possible later debugging
with open(resultsFilename, "wb") as f:
cPickle.dump(results, f) | python | def runExperiment6(dirName):
"""
This runs the experiment the section "Simulations with Combined Sequences",
an example stream containing a mixture of temporal and sensorimotor sequences.
"""
# Results are put into a pkl file which can be used to generate the plots.
# dirName is the absolute path where the pkl file will be placed.
resultsFilename = os.path.join(dirName, "combined_results.pkl")
results = runExperiment(
{
"numSequences": 50,
"seqLength": 10,
"numObjects": 50,
"numFeatures": 500,
"trialNum": 8,
"numLocations": 100,
"settlingTime": 1,
"figure": "6",
"numRepetitions": 30,
"basalPredictedSegmentDecrement": 0.001,
"stripStats": False,
}
)
# Pickle results for plotting and possible later debugging
with open(resultsFilename, "wb") as f:
cPickle.dump(results, f) | [
"def",
"runExperiment6",
"(",
"dirName",
")",
":",
"# Results are put into a pkl file which can be used to generate the plots.",
"# dirName is the absolute path where the pkl file will be placed.",
"resultsFilename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirName",
",",
"\"co... | This runs the experiment the section "Simulations with Combined Sequences",
an example stream containing a mixture of temporal and sensorimotor sequences. | [
"This",
"runs",
"the",
"experiment",
"the",
"section",
"Simulations",
"with",
"Combined",
"Sequences",
"an",
"example",
"stream",
"containing",
"a",
"mixture",
"of",
"temporal",
"and",
"sensorimotor",
"sequences",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/combined_sequences/combined_sequences.py#L813-L839 | train | 198,958 |
numenta/htmresearch | projects/combined_sequences/combined_sequences.py | runExperimentS | def runExperimentS(dirName):
"""
This runs an experiment where the network is trained on stream containing a
mixture of temporal and sensorimotor sequences.
"""
# Results are put into a pkl file which can be used to generate the plots.
# dirName is the absolute path where the pkl file will be placed.
resultsFilename = os.path.join(dirName, "superimposed_training.pkl")
results = runExperiment(
{
"numSequences": 50,
"numObjects": 50,
"seqLength": 10,
"numFeatures": 100,
"trialNum": 8,
"numLocations": 100,
"numRepetitions": 30,
"sampleSizeProximalL2": 15,
"minThresholdProximalL2": 10,
"figure": "S",
"stripStats": False,
}
)
# Pickle results for plotting and possible later debugging
with open(resultsFilename, "wb") as f:
cPickle.dump(results, f)
# Debugging
with open(resultsFilename, "rb") as f:
r = cPickle.load(f)
r.pop("objects")
r.pop("sequences")
stat = r.pop("statistics")
pprint.pprint(r)
sObject = 0
sSequence = 0
for i in range(0, 50):
sObject += sum(stat[i]['L4 PredictedActive C0'])
for i in range(50, 100):
sSequence += sum(stat[i]['L4 PredictedActive C0'])
print sObject, sSequence | python | def runExperimentS(dirName):
"""
This runs an experiment where the network is trained on stream containing a
mixture of temporal and sensorimotor sequences.
"""
# Results are put into a pkl file which can be used to generate the plots.
# dirName is the absolute path where the pkl file will be placed.
resultsFilename = os.path.join(dirName, "superimposed_training.pkl")
results = runExperiment(
{
"numSequences": 50,
"numObjects": 50,
"seqLength": 10,
"numFeatures": 100,
"trialNum": 8,
"numLocations": 100,
"numRepetitions": 30,
"sampleSizeProximalL2": 15,
"minThresholdProximalL2": 10,
"figure": "S",
"stripStats": False,
}
)
# Pickle results for plotting and possible later debugging
with open(resultsFilename, "wb") as f:
cPickle.dump(results, f)
# Debugging
with open(resultsFilename, "rb") as f:
r = cPickle.load(f)
r.pop("objects")
r.pop("sequences")
stat = r.pop("statistics")
pprint.pprint(r)
sObject = 0
sSequence = 0
for i in range(0, 50):
sObject += sum(stat[i]['L4 PredictedActive C0'])
for i in range(50, 100):
sSequence += sum(stat[i]['L4 PredictedActive C0'])
print sObject, sSequence | [
"def",
"runExperimentS",
"(",
"dirName",
")",
":",
"# Results are put into a pkl file which can be used to generate the plots.",
"# dirName is the absolute path where the pkl file will be placed.",
"resultsFilename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirName",
",",
"\"su... | This runs an experiment where the network is trained on stream containing a
mixture of temporal and sensorimotor sequences. | [
"This",
"runs",
"an",
"experiment",
"where",
"the",
"network",
"is",
"trained",
"on",
"stream",
"containing",
"a",
"mixture",
"of",
"temporal",
"and",
"sensorimotor",
"sequences",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/combined_sequences/combined_sequences.py#L872-L914 | train | 198,959 |
numenta/htmresearch | projects/combined_sequences/combined_sequences.py | runExperimentSP | def runExperimentSP(dirName):
"""
This runs a pool of experiments where the network is trained on stream
containing a mixture of temporal and sensorimotor sequences.
"""
# Results are put into a pkl file which can be used to generate the plots.
# dirName is the absolute path where the pkl file will be placed.
resultsFilename = os.path.join(dirName, "superimposed_128mcs.pkl")
# We run a bunch of trials with these combinations
numTrials = 10
featureRange = [1000]
objectRange = [50]
# Comment this out if you are re-running analysis on already saved results.
runExperimentPool(
numSequences=objectRange,
numObjects=objectRange,
numFeatures=featureRange,
numLocations=[100],
nTrials=numTrials,
numWorkers=cpu_count() - 1,
resultsName=resultsFilename,
figure="S",
numRepetitions=30,
sampleSizeProximalL2=[15],
minThresholdProximalL2=[10],
synPermProximalDecL2=[0.001],
# basalPredictedSegmentDecrement=[0.0, 0.001, 0.002, 0.003, 0.004, 0.005],
basalPredictedSegmentDecrement=[0.0, 0.001, 0.002, 0.003, 0.004, 0.005, 0.01, 0.02, 0.04, 0.08, 0.12],
inputSize=[128],
)
print "Done with experiments" | python | def runExperimentSP(dirName):
"""
This runs a pool of experiments where the network is trained on stream
containing a mixture of temporal and sensorimotor sequences.
"""
# Results are put into a pkl file which can be used to generate the plots.
# dirName is the absolute path where the pkl file will be placed.
resultsFilename = os.path.join(dirName, "superimposed_128mcs.pkl")
# We run a bunch of trials with these combinations
numTrials = 10
featureRange = [1000]
objectRange = [50]
# Comment this out if you are re-running analysis on already saved results.
runExperimentPool(
numSequences=objectRange,
numObjects=objectRange,
numFeatures=featureRange,
numLocations=[100],
nTrials=numTrials,
numWorkers=cpu_count() - 1,
resultsName=resultsFilename,
figure="S",
numRepetitions=30,
sampleSizeProximalL2=[15],
minThresholdProximalL2=[10],
synPermProximalDecL2=[0.001],
# basalPredictedSegmentDecrement=[0.0, 0.001, 0.002, 0.003, 0.004, 0.005],
basalPredictedSegmentDecrement=[0.0, 0.001, 0.002, 0.003, 0.004, 0.005, 0.01, 0.02, 0.04, 0.08, 0.12],
inputSize=[128],
)
print "Done with experiments" | [
"def",
"runExperimentSP",
"(",
"dirName",
")",
":",
"# Results are put into a pkl file which can be used to generate the plots.",
"# dirName is the absolute path where the pkl file will be placed.",
"resultsFilename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirName",
",",
"\"s... | This runs a pool of experiments where the network is trained on stream
containing a mixture of temporal and sensorimotor sequences. | [
"This",
"runs",
"a",
"pool",
"of",
"experiments",
"where",
"the",
"network",
"is",
"trained",
"on",
"stream",
"containing",
"a",
"mixture",
"of",
"temporal",
"and",
"sensorimotor",
"sequences",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/combined_sequences/combined_sequences.py#L918-L951 | train | 198,960 |
numenta/htmresearch | htmresearch/algorithms/TM.py | TM.reset | def reset(self,):
""" Reset the state of all cells.
This is normally used between sequences while training. All internal states
are reset to 0.
"""
self.activeState['t-1'].fill(0)
self.activeState['t'].fill(0)
self.predictedState['t-1'].fill(0)
self.predictedState['t'].fill(0)
self.learnState['t-1'].fill(0)
self.learnState['t'].fill(0)
self.confidence['t-1'].fill(0)
self.confidence['t'].fill(0)
# Flush the segment update queue
self.segmentUpdates = {}
self._internalStats['nInfersSinceReset'] = 0
#To be removed
self._internalStats['curPredictionScore'] = 0
#New prediction score
self._internalStats['curPredictionScore2'] = 0
self._internalStats['curFalseNegativeScore'] = 0
self._internalStats['curFalsePositiveScore'] = 0
self._internalStats['curMissing'] = 0
self._internalStats['curExtra'] = 0
# When a reset occurs, set prevSequenceSignature to the signature of the
# just-completed sequence and start accumulating histogram for the next
# sequence.
self._internalStats['prevSequenceSignature'] = None
if self.collectSequenceStats:
if self._internalStats['confHistogram'].sum() > 0:
sig = self._internalStats['confHistogram'].copy()
sig.reshape(self.numberOfCols * self.cellsPerColumn)
self._internalStats['prevSequenceSignature'] = sig
self._internalStats['confHistogram'].fill(0)
self.resetCalled = True | python | def reset(self,):
""" Reset the state of all cells.
This is normally used between sequences while training. All internal states
are reset to 0.
"""
self.activeState['t-1'].fill(0)
self.activeState['t'].fill(0)
self.predictedState['t-1'].fill(0)
self.predictedState['t'].fill(0)
self.learnState['t-1'].fill(0)
self.learnState['t'].fill(0)
self.confidence['t-1'].fill(0)
self.confidence['t'].fill(0)
# Flush the segment update queue
self.segmentUpdates = {}
self._internalStats['nInfersSinceReset'] = 0
#To be removed
self._internalStats['curPredictionScore'] = 0
#New prediction score
self._internalStats['curPredictionScore2'] = 0
self._internalStats['curFalseNegativeScore'] = 0
self._internalStats['curFalsePositiveScore'] = 0
self._internalStats['curMissing'] = 0
self._internalStats['curExtra'] = 0
# When a reset occurs, set prevSequenceSignature to the signature of the
# just-completed sequence and start accumulating histogram for the next
# sequence.
self._internalStats['prevSequenceSignature'] = None
if self.collectSequenceStats:
if self._internalStats['confHistogram'].sum() > 0:
sig = self._internalStats['confHistogram'].copy()
sig.reshape(self.numberOfCols * self.cellsPerColumn)
self._internalStats['prevSequenceSignature'] = sig
self._internalStats['confHistogram'].fill(0)
self.resetCalled = True | [
"def",
"reset",
"(",
"self",
",",
")",
":",
"self",
".",
"activeState",
"[",
"'t-1'",
"]",
".",
"fill",
"(",
"0",
")",
"self",
".",
"activeState",
"[",
"'t'",
"]",
".",
"fill",
"(",
"0",
")",
"self",
".",
"predictedState",
"[",
"'t-1'",
"]",
".",... | Reset the state of all cells.
This is normally used between sequences while training. All internal states
are reset to 0. | [
"Reset",
"the",
"state",
"of",
"all",
"cells",
".",
"This",
"is",
"normally",
"used",
"between",
"sequences",
"while",
"training",
".",
"All",
"internal",
"states",
"are",
"reset",
"to",
"0",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/TM.py#L309-L351 | train | 198,961 |
numenta/htmresearch | htmresearch/algorithms/TM.py | TM.printComputeEnd | def printComputeEnd(self, output, learn=False):
""" Called at the end of inference to print out various diagnostic
information based on the current verbosity level.
"""
if self.verbosity >= 3:
print "----- computeEnd summary: "
print "numBurstingCols: %s, " % (self.activeState['t'].min(axis=1).sum()),
print "curPredScore2: %s, " % (self._internalStats['curPredictionScore2']),
print "curFalsePosScore: %s, " % (self._internalStats['curFalsePositiveScore']),
print "1-curFalseNegScore: %s, " % (1-self._internalStats['curFalseNegativeScore']),
print "numPredictedCells[t-1]: %s" % (self.predictedState['t-1'].sum()),
print "numSegments: ",self.getNumSegments()
print "----- activeState (%d on) ------" \
% (self.activeState['t'].sum())
self.printActiveIndices(self.activeState['t'])
if self.verbosity >= 5:
self.printState(self.activeState['t'])
print "----- predictedState (%d on)-----" \
% (self.predictedState['t'].sum())
self.printActiveIndices(self.predictedState['t'])
if self.verbosity >= 5:
self.printState(self.predictedState['t'])
print "----- cell confidence -----"
self.printActiveIndices(self.confidence['t'], andValues=True)
if self.verbosity >= 5:
self.printConfidence(self.confidence['t'])
print "----- confidence[t-1] for currently active cells -----"
cc = self.confidence['t-1'] * self.activeState['t']
self.printActiveIndices(cc, andValues=True)
if self.verbosity == 4:
print "Cells, predicted segments only:"
self.printCells(predictedOnly=True)
elif self.verbosity >= 5:
print "Cells, all segments:"
self.printCells(predictedOnly=False)
print | python | def printComputeEnd(self, output, learn=False):
""" Called at the end of inference to print out various diagnostic
information based on the current verbosity level.
"""
if self.verbosity >= 3:
print "----- computeEnd summary: "
print "numBurstingCols: %s, " % (self.activeState['t'].min(axis=1).sum()),
print "curPredScore2: %s, " % (self._internalStats['curPredictionScore2']),
print "curFalsePosScore: %s, " % (self._internalStats['curFalsePositiveScore']),
print "1-curFalseNegScore: %s, " % (1-self._internalStats['curFalseNegativeScore']),
print "numPredictedCells[t-1]: %s" % (self.predictedState['t-1'].sum()),
print "numSegments: ",self.getNumSegments()
print "----- activeState (%d on) ------" \
% (self.activeState['t'].sum())
self.printActiveIndices(self.activeState['t'])
if self.verbosity >= 5:
self.printState(self.activeState['t'])
print "----- predictedState (%d on)-----" \
% (self.predictedState['t'].sum())
self.printActiveIndices(self.predictedState['t'])
if self.verbosity >= 5:
self.printState(self.predictedState['t'])
print "----- cell confidence -----"
self.printActiveIndices(self.confidence['t'], andValues=True)
if self.verbosity >= 5:
self.printConfidence(self.confidence['t'])
print "----- confidence[t-1] for currently active cells -----"
cc = self.confidence['t-1'] * self.activeState['t']
self.printActiveIndices(cc, andValues=True)
if self.verbosity == 4:
print "Cells, predicted segments only:"
self.printCells(predictedOnly=True)
elif self.verbosity >= 5:
print "Cells, all segments:"
self.printCells(predictedOnly=False)
print | [
"def",
"printComputeEnd",
"(",
"self",
",",
"output",
",",
"learn",
"=",
"False",
")",
":",
"if",
"self",
".",
"verbosity",
">=",
"3",
":",
"print",
"\"----- computeEnd summary: \"",
"print",
"\"numBurstingCols: %s, \"",
"%",
"(",
"self",
".",
"activeState",
"... | Called at the end of inference to print out various diagnostic
information based on the current verbosity level. | [
"Called",
"at",
"the",
"end",
"of",
"inference",
"to",
"print",
"out",
"various",
"diagnostic",
"information",
"based",
"on",
"the",
"current",
"verbosity",
"level",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/TM.py#L659-L699 | train | 198,962 |
numenta/htmresearch | htmresearch/algorithms/TM.py | TM.computePhase2 | def computePhase2(self, doLearn=False):
"""
This is the phase 2 of learning, inference and multistep prediction. During
this phase, all the cell with lateral support have their predictedState
turned on and the firing segments are queued up for updates.
Parameters:
--------------------------------------------
doLearn: Boolean flag to queue segment updates during learning
retval: ?
"""
# Phase 2: compute predicted state for each cell
# - if a segment has enough horizontal connections firing because of
# bottomUpInput, it's set to be predicting, and we queue up the segment
# for reinforcement,
# - if pooling is on, try to find the best weakly activated segment to
# reinforce it, else create a new pooling segment.
for c in xrange(self.numberOfCols):
buPredicted = False # whether any cell in the column is predicted
for i in xrange(self.cellsPerColumn):
# Iterate over each of the segments of this cell
maxConfidence = 0
for s in self.cells[c][i]:
# sum(connected synapses) >= activationThreshold?
if self.isSegmentActive(s, self.activeState['t']):
self.predictedState['t'][c,i] = 1
buPredicted = True
maxConfidence = max(maxConfidence, s.dutyCycle(readOnly=True))
if doLearn:
s.totalActivations += 1 # increment activationFrequency
s.lastActiveIteration = self.iterationIdx
# mark this segment for learning
activeUpdate = self.getSegmentActiveSynapses(c,i,s,'t')
activeUpdate.phase1Flag = False
self.addToSegmentUpdates(c, i, activeUpdate)
# Store the max confidence seen among all the weak and strong segments
# as the cell's confidence.
self.confidence['t'][c,i] = maxConfidence | python | def computePhase2(self, doLearn=False):
"""
This is the phase 2 of learning, inference and multistep prediction. During
this phase, all the cell with lateral support have their predictedState
turned on and the firing segments are queued up for updates.
Parameters:
--------------------------------------------
doLearn: Boolean flag to queue segment updates during learning
retval: ?
"""
# Phase 2: compute predicted state for each cell
# - if a segment has enough horizontal connections firing because of
# bottomUpInput, it's set to be predicting, and we queue up the segment
# for reinforcement,
# - if pooling is on, try to find the best weakly activated segment to
# reinforce it, else create a new pooling segment.
for c in xrange(self.numberOfCols):
buPredicted = False # whether any cell in the column is predicted
for i in xrange(self.cellsPerColumn):
# Iterate over each of the segments of this cell
maxConfidence = 0
for s in self.cells[c][i]:
# sum(connected synapses) >= activationThreshold?
if self.isSegmentActive(s, self.activeState['t']):
self.predictedState['t'][c,i] = 1
buPredicted = True
maxConfidence = max(maxConfidence, s.dutyCycle(readOnly=True))
if doLearn:
s.totalActivations += 1 # increment activationFrequency
s.lastActiveIteration = self.iterationIdx
# mark this segment for learning
activeUpdate = self.getSegmentActiveSynapses(c,i,s,'t')
activeUpdate.phase1Flag = False
self.addToSegmentUpdates(c, i, activeUpdate)
# Store the max confidence seen among all the weak and strong segments
# as the cell's confidence.
self.confidence['t'][c,i] = maxConfidence | [
"def",
"computePhase2",
"(",
"self",
",",
"doLearn",
"=",
"False",
")",
":",
"# Phase 2: compute predicted state for each cell",
"# - if a segment has enough horizontal connections firing because of",
"# bottomUpInput, it's set to be predicting, and we queue up the segment",
"# for rei... | This is the phase 2 of learning, inference and multistep prediction. During
this phase, all the cell with lateral support have their predictedState
turned on and the firing segments are queued up for updates.
Parameters:
--------------------------------------------
doLearn: Boolean flag to queue segment updates during learning
retval: ? | [
"This",
"is",
"the",
"phase",
"2",
"of",
"learning",
"inference",
"and",
"multistep",
"prediction",
".",
"During",
"this",
"phase",
"all",
"the",
"cell",
"with",
"lateral",
"support",
"have",
"their",
"predictedState",
"turned",
"on",
"and",
"the",
"firing",
... | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/TM.py#L1036-L1079 | train | 198,963 |
numenta/htmresearch | htmresearch/algorithms/TM.py | TM.columnConfidences | def columnConfidences(self, cellConfidences=None):
""" Compute the column confidences given the cell confidences. If
None is passed in for cellConfidences, it uses the stored cell confidences
from the last compute.
Parameters:
----------------------------
cellConfidencs : cell confidences to use, or None to use the
the current cell confidences.
retval: : Column confidence scores.
"""
if cellConfidences is None:
cellConfidences = self.confidence['t']
colConfidences = cellConfidences.sum(axis=1)
# Make the max column confidence 1.0
#colConfidences /= colConfidences.max()
return colConfidences | python | def columnConfidences(self, cellConfidences=None):
""" Compute the column confidences given the cell confidences. If
None is passed in for cellConfidences, it uses the stored cell confidences
from the last compute.
Parameters:
----------------------------
cellConfidencs : cell confidences to use, or None to use the
the current cell confidences.
retval: : Column confidence scores.
"""
if cellConfidences is None:
cellConfidences = self.confidence['t']
colConfidences = cellConfidences.sum(axis=1)
# Make the max column confidence 1.0
#colConfidences /= colConfidences.max()
return colConfidences | [
"def",
"columnConfidences",
"(",
"self",
",",
"cellConfidences",
"=",
"None",
")",
":",
"if",
"cellConfidences",
"is",
"None",
":",
"cellConfidences",
"=",
"self",
".",
"confidence",
"[",
"'t'",
"]",
"colConfidences",
"=",
"cellConfidences",
".",
"sum",
"(",
... | Compute the column confidences given the cell confidences. If
None is passed in for cellConfidences, it uses the stored cell confidences
from the last compute.
Parameters:
----------------------------
cellConfidencs : cell confidences to use, or None to use the
the current cell confidences.
retval: : Column confidence scores. | [
"Compute",
"the",
"column",
"confidences",
"given",
"the",
"cell",
"confidences",
".",
"If",
"None",
"is",
"passed",
"in",
"for",
"cellConfidences",
"it",
"uses",
"the",
"stored",
"cell",
"confidences",
"from",
"the",
"last",
"compute",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/TM.py#L1378-L1399 | train | 198,964 |
numenta/htmresearch | htmresearch/algorithms/TM.py | TM.trimSegments | def trimSegments(self, minPermanence=None, minNumSyns=None):
""" This method deletes all synapses whose permanence is less than
minPermanence and deletes any segments that have less than
minNumSyns synapses remaining.
Parameters:
--------------------------------------------------------------
minPermanence: Any syn whose permamence is 0 or < minPermanence will
be deleted. If None is passed in, then
self.connectedPerm is used.
minNumSyns: Any segment with less than minNumSyns synapses remaining
in it will be deleted. If None is passed in, then
self.activationThreshold is used.
retval: (numSegsRemoved, numSynsRemoved)
"""
# Fill in defaults
if minPermanence is None:
minPermanence = self.connectedPerm
if minNumSyns is None:
minNumSyns = self.activationThreshold
# Loop through all cells
totalSegsRemoved, totalSynsRemoved = 0, 0
for c,i in product(xrange(self.numberOfCols), xrange(self.cellsPerColumn)):
(segsRemoved, synsRemoved) = self.trimSegmentsInCell(colIdx=c, cellIdx=i,
segList=self.cells[c][i], minPermanence=minPermanence,
minNumSyns=minNumSyns)
totalSegsRemoved += segsRemoved
totalSynsRemoved += synsRemoved
return totalSegsRemoved, totalSynsRemoved | python | def trimSegments(self, minPermanence=None, minNumSyns=None):
""" This method deletes all synapses whose permanence is less than
minPermanence and deletes any segments that have less than
minNumSyns synapses remaining.
Parameters:
--------------------------------------------------------------
minPermanence: Any syn whose permamence is 0 or < minPermanence will
be deleted. If None is passed in, then
self.connectedPerm is used.
minNumSyns: Any segment with less than minNumSyns synapses remaining
in it will be deleted. If None is passed in, then
self.activationThreshold is used.
retval: (numSegsRemoved, numSynsRemoved)
"""
# Fill in defaults
if minPermanence is None:
minPermanence = self.connectedPerm
if minNumSyns is None:
minNumSyns = self.activationThreshold
# Loop through all cells
totalSegsRemoved, totalSynsRemoved = 0, 0
for c,i in product(xrange(self.numberOfCols), xrange(self.cellsPerColumn)):
(segsRemoved, synsRemoved) = self.trimSegmentsInCell(colIdx=c, cellIdx=i,
segList=self.cells[c][i], minPermanence=minPermanence,
minNumSyns=minNumSyns)
totalSegsRemoved += segsRemoved
totalSynsRemoved += synsRemoved
return totalSegsRemoved, totalSynsRemoved | [
"def",
"trimSegments",
"(",
"self",
",",
"minPermanence",
"=",
"None",
",",
"minNumSyns",
"=",
"None",
")",
":",
"# Fill in defaults",
"if",
"minPermanence",
"is",
"None",
":",
"minPermanence",
"=",
"self",
".",
"connectedPerm",
"if",
"minNumSyns",
"is",
"None... | This method deletes all synapses whose permanence is less than
minPermanence and deletes any segments that have less than
minNumSyns synapses remaining.
Parameters:
--------------------------------------------------------------
minPermanence: Any syn whose permamence is 0 or < minPermanence will
be deleted. If None is passed in, then
self.connectedPerm is used.
minNumSyns: Any segment with less than minNumSyns synapses remaining
in it will be deleted. If None is passed in, then
self.activationThreshold is used.
retval: (numSegsRemoved, numSynsRemoved) | [
"This",
"method",
"deletes",
"all",
"synapses",
"whose",
"permanence",
"is",
"less",
"than",
"minPermanence",
"and",
"deletes",
"any",
"segments",
"that",
"have",
"less",
"than",
"minNumSyns",
"synapses",
"remaining",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/TM.py#L1477-L1510 | train | 198,965 |
numenta/htmresearch | htmresearch/algorithms/TM.py | TM.checkPrediction2 | def checkPrediction2(self, patternNZs, output=None, confidence=None,
details=False):
"""
This function will replace checkPrediction.
This function produces goodness-of-match scores for a set of input patterns, by
checking for their presense in the current and predicted output of the TP.
Returns a global count of the number of extra and missing bits, the
confidence scores for each input pattern, and (if requested) the
bits in each input pattern that were not present in the TP's prediction.
todo: Add option to check predictedState only.
Parameters:
==========
patternNZs: a list of input patterns that we want to check for. Each element
is a list of the non-zeros in that pattern.
output: The output of the TP. If not specified, then use the
TP's current output. This can be specified if you are
trying to check the prediction metric for an output from
the past.
confidence: The cell confidences. If not specified, then use the
TP's current self.confidence. This can be specified if you are
trying to check the prediction metrics for an output
from the past.
details: if True, also include details of missing bits per pattern.
Return value:
============
The following list is returned:
[
totalExtras,
totalMissing,
[conf_1, conf_2, ...],
[missing1, missing2, ...]
]
totalExtras: a global count of the number of 'extras', i.e. bits that
are on in the current output but not in the or of all the
passed in patterns
totalMissing: a global count of all the missing bits, i.e. the bits that
are on in the or of the patterns, but not in the current
output
conf_i the confidence score for the i'th pattern in patternsToCheck
missing_i the bits in the i'th pattern that were missing
in the output. This list is only returned if details is
True.
"""
# Get the non-zeros in each pattern
numPatterns = len(patternNZs)
# Compute the union of all the expected patterns
orAll = set()
orAll = orAll.union(*patternNZs)
# Get the list of active columns in the output
if output is None:
assert self.currentOutput is not None
output = self.currentOutput
output = set(output.sum(axis=1).nonzero()[0])
# Compute the total extra and missing in the output
totalExtras = len(output.difference(orAll))
totalMissing = len(orAll.difference(output))
# Get the percent confidence level per column by summing the confidence levels
# of the cells in the column. During training, each segment's confidence
# number is computed as a running average of how often it correctly
# predicted bottom-up activity on that column. A cell's confidence number
# is taken from the first active segment found in the cell. Note that
# confidence will only be non-zero for predicted columns.
if confidence is None:
confidence = self.confidence['t']
# Set the column confidence to be the max of the cell confidences in that
# column.
colConfidence = self.columnConfidences(confidence)
# Assign confidences to each pattern
confidences = []
for i in xrange(numPatterns):
# Sum of the column confidences for this pattern
positivePredictionSum = colConfidence[patternNZs[i]].sum()
# How many columns in this pattern
positiveColumnCount = len(patternNZs[i])
# Sum of all the column confidences
totalPredictionSum = colConfidence.sum()
# Total number of columns
totalColumnCount = len(colConfidence)
negativePredictionSum = totalPredictionSum - positivePredictionSum
negativeColumnCount = totalColumnCount - positiveColumnCount
# Compute the average confidence score per column for this pattern
if positiveColumnCount != 0:
positivePredictionScore = positivePredictionSum/positiveColumnCount
else:
positivePredictionScore = 0.0
# Compute the average confidence score per column for the other patterns
if negativeColumnCount != 0:
negativePredictionScore = negativePredictionSum/negativeColumnCount
else:
negativePredictionScore = 0.0
predictionScore = positivePredictionScore - negativePredictionScore
confidences.append((predictionScore,
positivePredictionScore,
negativePredictionScore))
# Include detail? (bits in each pattern that were missing from the output)
if details:
missingPatternBits = [set(pattern).difference(output) \
for pattern in patternNZs]
return (totalExtras, totalMissing, confidences, missingPatternBits)
else:
return (totalExtras, totalMissing, confidences) | python | def checkPrediction2(self, patternNZs, output=None, confidence=None,
details=False):
"""
This function will replace checkPrediction.
This function produces goodness-of-match scores for a set of input patterns, by
checking for their presense in the current and predicted output of the TP.
Returns a global count of the number of extra and missing bits, the
confidence scores for each input pattern, and (if requested) the
bits in each input pattern that were not present in the TP's prediction.
todo: Add option to check predictedState only.
Parameters:
==========
patternNZs: a list of input patterns that we want to check for. Each element
is a list of the non-zeros in that pattern.
output: The output of the TP. If not specified, then use the
TP's current output. This can be specified if you are
trying to check the prediction metric for an output from
the past.
confidence: The cell confidences. If not specified, then use the
TP's current self.confidence. This can be specified if you are
trying to check the prediction metrics for an output
from the past.
details: if True, also include details of missing bits per pattern.
Return value:
============
The following list is returned:
[
totalExtras,
totalMissing,
[conf_1, conf_2, ...],
[missing1, missing2, ...]
]
totalExtras: a global count of the number of 'extras', i.e. bits that
are on in the current output but not in the or of all the
passed in patterns
totalMissing: a global count of all the missing bits, i.e. the bits that
are on in the or of the patterns, but not in the current
output
conf_i the confidence score for the i'th pattern in patternsToCheck
missing_i the bits in the i'th pattern that were missing
in the output. This list is only returned if details is
True.
"""
# Get the non-zeros in each pattern
numPatterns = len(patternNZs)
# Compute the union of all the expected patterns
orAll = set()
orAll = orAll.union(*patternNZs)
# Get the list of active columns in the output
if output is None:
assert self.currentOutput is not None
output = self.currentOutput
output = set(output.sum(axis=1).nonzero()[0])
# Compute the total extra and missing in the output
totalExtras = len(output.difference(orAll))
totalMissing = len(orAll.difference(output))
# Get the percent confidence level per column by summing the confidence levels
# of the cells in the column. During training, each segment's confidence
# number is computed as a running average of how often it correctly
# predicted bottom-up activity on that column. A cell's confidence number
# is taken from the first active segment found in the cell. Note that
# confidence will only be non-zero for predicted columns.
if confidence is None:
confidence = self.confidence['t']
# Set the column confidence to be the max of the cell confidences in that
# column.
colConfidence = self.columnConfidences(confidence)
# Assign confidences to each pattern
confidences = []
for i in xrange(numPatterns):
# Sum of the column confidences for this pattern
positivePredictionSum = colConfidence[patternNZs[i]].sum()
# How many columns in this pattern
positiveColumnCount = len(patternNZs[i])
# Sum of all the column confidences
totalPredictionSum = colConfidence.sum()
# Total number of columns
totalColumnCount = len(colConfidence)
negativePredictionSum = totalPredictionSum - positivePredictionSum
negativeColumnCount = totalColumnCount - positiveColumnCount
# Compute the average confidence score per column for this pattern
if positiveColumnCount != 0:
positivePredictionScore = positivePredictionSum/positiveColumnCount
else:
positivePredictionScore = 0.0
# Compute the average confidence score per column for the other patterns
if negativeColumnCount != 0:
negativePredictionScore = negativePredictionSum/negativeColumnCount
else:
negativePredictionScore = 0.0
predictionScore = positivePredictionScore - negativePredictionScore
confidences.append((predictionScore,
positivePredictionScore,
negativePredictionScore))
# Include detail? (bits in each pattern that were missing from the output)
if details:
missingPatternBits = [set(pattern).difference(output) \
for pattern in patternNZs]
return (totalExtras, totalMissing, confidences, missingPatternBits)
else:
return (totalExtras, totalMissing, confidences) | [
"def",
"checkPrediction2",
"(",
"self",
",",
"patternNZs",
",",
"output",
"=",
"None",
",",
"confidence",
"=",
"None",
",",
"details",
"=",
"False",
")",
":",
"# Get the non-zeros in each pattern",
"numPatterns",
"=",
"len",
"(",
"patternNZs",
")",
"# Compute th... | This function will replace checkPrediction.
This function produces goodness-of-match scores for a set of input patterns, by
checking for their presense in the current and predicted output of the TP.
Returns a global count of the number of extra and missing bits, the
confidence scores for each input pattern, and (if requested) the
bits in each input pattern that were not present in the TP's prediction.
todo: Add option to check predictedState only.
Parameters:
==========
patternNZs: a list of input patterns that we want to check for. Each element
is a list of the non-zeros in that pattern.
output: The output of the TP. If not specified, then use the
TP's current output. This can be specified if you are
trying to check the prediction metric for an output from
the past.
confidence: The cell confidences. If not specified, then use the
TP's current self.confidence. This can be specified if you are
trying to check the prediction metrics for an output
from the past.
details: if True, also include details of missing bits per pattern.
Return value:
============
The following list is returned:
[
totalExtras,
totalMissing,
[conf_1, conf_2, ...],
[missing1, missing2, ...]
]
totalExtras: a global count of the number of 'extras', i.e. bits that
are on in the current output but not in the or of all the
passed in patterns
totalMissing: a global count of all the missing bits, i.e. the bits that
are on in the or of the patterns, but not in the current
output
conf_i the confidence score for the i'th pattern in patternsToCheck
missing_i the bits in the i'th pattern that were missing
in the output. This list is only returned if details is
True. | [
"This",
"function",
"will",
"replace",
"checkPrediction",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/TM.py#L1543-L1669 | train | 198,966 |
numenta/htmresearch | htmresearch/algorithms/TM.py | TM.isSegmentActive | def isSegmentActive(self, seg, activeState):
"""
A segment is active if it has >= activationThreshold connected
synapses that are active due to activeState.
Notes: studied various cutoffs, none of which seem to be worthwhile
list comprehension didn't help either
"""
# Computing in C - *much* faster
return isSegmentActive(seg.syns, activeState,
self.connectedPerm, self.activationThreshold) | python | def isSegmentActive(self, seg, activeState):
"""
A segment is active if it has >= activationThreshold connected
synapses that are active due to activeState.
Notes: studied various cutoffs, none of which seem to be worthwhile
list comprehension didn't help either
"""
# Computing in C - *much* faster
return isSegmentActive(seg.syns, activeState,
self.connectedPerm, self.activationThreshold) | [
"def",
"isSegmentActive",
"(",
"self",
",",
"seg",
",",
"activeState",
")",
":",
"# Computing in C - *much* faster",
"return",
"isSegmentActive",
"(",
"seg",
".",
"syns",
",",
"activeState",
",",
"self",
".",
"connectedPerm",
",",
"self",
".",
"activationThreshold... | A segment is active if it has >= activationThreshold connected
synapses that are active due to activeState.
Notes: studied various cutoffs, none of which seem to be worthwhile
list comprehension didn't help either | [
"A",
"segment",
"is",
"active",
"if",
"it",
"has",
">",
"=",
"activationThreshold",
"connected",
"synapses",
"that",
"are",
"active",
"due",
"to",
"activeState",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/TM.py#L1683-L1693 | train | 198,967 |
numenta/htmresearch | htmresearch/algorithms/TM.py | TM.getActiveSegment | def getActiveSegment(self, c, i, timeStep):
""" For a given cell, return the segment with the strongest _connected_
activation, i.e. sum up the activations of the connected synapses of the
segments only. That is, a segment is active only if it has enough connected
synapses.
"""
# todo: put back preference for sequence segments.
nSegments = len(self.cells[c][i])
bestActivation = self.activationThreshold
which = -1
for j,s in enumerate(self.cells[c][i]):
activity = self.getSegmentActivityLevel(s, self.activeState[timeStep], connectedSynapsesOnly = True)
if activity >= bestActivation:
bestActivation = activity
which = j
if which != -1:
return self.cells[c][i][which]
else:
return None | python | def getActiveSegment(self, c, i, timeStep):
""" For a given cell, return the segment with the strongest _connected_
activation, i.e. sum up the activations of the connected synapses of the
segments only. That is, a segment is active only if it has enough connected
synapses.
"""
# todo: put back preference for sequence segments.
nSegments = len(self.cells[c][i])
bestActivation = self.activationThreshold
which = -1
for j,s in enumerate(self.cells[c][i]):
activity = self.getSegmentActivityLevel(s, self.activeState[timeStep], connectedSynapsesOnly = True)
if activity >= bestActivation:
bestActivation = activity
which = j
if which != -1:
return self.cells[c][i][which]
else:
return None | [
"def",
"getActiveSegment",
"(",
"self",
",",
"c",
",",
"i",
",",
"timeStep",
")",
":",
"# todo: put back preference for sequence segments.",
"nSegments",
"=",
"len",
"(",
"self",
".",
"cells",
"[",
"c",
"]",
"[",
"i",
"]",
")",
"bestActivation",
"=",
"self",... | For a given cell, return the segment with the strongest _connected_
activation, i.e. sum up the activations of the connected synapses of the
segments only. That is, a segment is active only if it has enough connected
synapses. | [
"For",
"a",
"given",
"cell",
"return",
"the",
"segment",
"with",
"the",
"strongest",
"_connected_",
"activation",
"i",
".",
"e",
".",
"sum",
"up",
"the",
"activations",
"of",
"the",
"connected",
"synapses",
"of",
"the",
"segments",
"only",
".",
"That",
"is... | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/TM.py#L1737-L1762 | train | 198,968 |
numenta/htmresearch | htmresearch/algorithms/TM.py | TM.chooseCellsToLearnFrom | def chooseCellsToLearnFrom(self, c,i,s, n, timeStep):
"""Choose n random cells to learn from.
Returns tuples of (column index, cell index).
"""
if n <= 0:
return []
tmpCandidates = [] # tmp because we'll refine just below with activeSynapses
if timeStep == 't-1':
tmpCandidates = numpy.where(self.learnState['t-1'] == 1)
else:
tmpCandidates = numpy.where(self.learnState['t'] == 1)
# Candidates can be empty at this point, in which case we return
# an empty segment list. adaptSegments will do nothing when getting
# that list.
if len(tmpCandidates[0]) == 0:
return []
if s is None: # new segment
cands = [syn for syn in zip(tmpCandidates[0], tmpCandidates[1])]
else:
# We exclude any synapse that is already in this segment.
synapsesAlreadyInSegment = set((syn[0], syn[1]) for syn in s.syns)
cands = [syn for syn in zip(tmpCandidates[0], tmpCandidates[1]) \
if (syn[0], syn[1]) not in synapsesAlreadyInSegment]
if n == 1: # so that we don't shuffle if only one is needed
idx = self._random.getUInt32(len(cands))
return [cands[idx]] # col and cell idx in col
# If we need more than one candidate
self._random.getUInt32(10) # this required to line RNG with C++ (??)
indices = array([j for j in range(len(cands))], dtype='uint32')
tmp = zeros(min(n, len(indices)), dtype='uint32')
self._random.getUInt32Sample(indices, tmp, True)
return [cands[j] for j in tmp] | python | def chooseCellsToLearnFrom(self, c,i,s, n, timeStep):
"""Choose n random cells to learn from.
Returns tuples of (column index, cell index).
"""
if n <= 0:
return []
tmpCandidates = [] # tmp because we'll refine just below with activeSynapses
if timeStep == 't-1':
tmpCandidates = numpy.where(self.learnState['t-1'] == 1)
else:
tmpCandidates = numpy.where(self.learnState['t'] == 1)
# Candidates can be empty at this point, in which case we return
# an empty segment list. adaptSegments will do nothing when getting
# that list.
if len(tmpCandidates[0]) == 0:
return []
if s is None: # new segment
cands = [syn for syn in zip(tmpCandidates[0], tmpCandidates[1])]
else:
# We exclude any synapse that is already in this segment.
synapsesAlreadyInSegment = set((syn[0], syn[1]) for syn in s.syns)
cands = [syn for syn in zip(tmpCandidates[0], tmpCandidates[1]) \
if (syn[0], syn[1]) not in synapsesAlreadyInSegment]
if n == 1: # so that we don't shuffle if only one is needed
idx = self._random.getUInt32(len(cands))
return [cands[idx]] # col and cell idx in col
# If we need more than one candidate
self._random.getUInt32(10) # this required to line RNG with C++ (??)
indices = array([j for j in range(len(cands))], dtype='uint32')
tmp = zeros(min(n, len(indices)), dtype='uint32')
self._random.getUInt32Sample(indices, tmp, True)
return [cands[j] for j in tmp] | [
"def",
"chooseCellsToLearnFrom",
"(",
"self",
",",
"c",
",",
"i",
",",
"s",
",",
"n",
",",
"timeStep",
")",
":",
"if",
"n",
"<=",
"0",
":",
"return",
"[",
"]",
"tmpCandidates",
"=",
"[",
"]",
"# tmp because we'll refine just below with activeSynapses",
"if",... | Choose n random cells to learn from.
Returns tuples of (column index, cell index). | [
"Choose",
"n",
"random",
"cells",
"to",
"learn",
"from",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/TM.py#L1766-L1805 | train | 198,969 |
numenta/htmresearch | htmresearch/algorithms/TM.py | TM.getBestMatchingCell | def getBestMatchingCell(self, c, activeState):
"""Find weakly activated cell in column. Returns index and segment of most
activated segment above minThreshold.
"""
# Collect all cells in column c that have at least minThreshold in the most
# activated segment
bestActivityInCol = self.minThreshold
bestSegIdxInCol = -1
bestCellInCol = -1
for i in xrange(self.cellsPerColumn):
maxSegActivity = 0
maxSegIdx = 0
for j,s in enumerate(self.cells[c][i]):
activity = self.getSegmentActivityLevel(s, activeState, connectedSynapsesOnly =False)
if self.verbosity >= 6:
print " Segment Activity for column ", c, " cell ", i, " segment ", " j is ", activity
if activity > maxSegActivity:
maxSegActivity = activity
maxSegIdx = j
if maxSegActivity >= bestActivityInCol:
bestActivityInCol = maxSegActivity
bestSegIdxInCol = maxSegIdx
bestCellInCol = i
if self.verbosity >= 6:
print "Best Matching Cell In Col: ", bestCellInCol
if bestCellInCol == -1:
return (None, None)
else:
return bestCellInCol, self.cells[c][bestCellInCol][bestSegIdxInCol] | python | def getBestMatchingCell(self, c, activeState):
"""Find weakly activated cell in column. Returns index and segment of most
activated segment above minThreshold.
"""
# Collect all cells in column c that have at least minThreshold in the most
# activated segment
bestActivityInCol = self.minThreshold
bestSegIdxInCol = -1
bestCellInCol = -1
for i in xrange(self.cellsPerColumn):
maxSegActivity = 0
maxSegIdx = 0
for j,s in enumerate(self.cells[c][i]):
activity = self.getSegmentActivityLevel(s, activeState, connectedSynapsesOnly =False)
if self.verbosity >= 6:
print " Segment Activity for column ", c, " cell ", i, " segment ", " j is ", activity
if activity > maxSegActivity:
maxSegActivity = activity
maxSegIdx = j
if maxSegActivity >= bestActivityInCol:
bestActivityInCol = maxSegActivity
bestSegIdxInCol = maxSegIdx
bestCellInCol = i
if self.verbosity >= 6:
print "Best Matching Cell In Col: ", bestCellInCol
if bestCellInCol == -1:
return (None, None)
else:
return bestCellInCol, self.cells[c][bestCellInCol][bestSegIdxInCol] | [
"def",
"getBestMatchingCell",
"(",
"self",
",",
"c",
",",
"activeState",
")",
":",
"# Collect all cells in column c that have at least minThreshold in the most",
"# activated segment",
"bestActivityInCol",
"=",
"self",
".",
"minThreshold",
"bestSegIdxInCol",
"=",
"-",
"1",
... | Find weakly activated cell in column. Returns index and segment of most
activated segment above minThreshold. | [
"Find",
"weakly",
"activated",
"cell",
"in",
"column",
".",
"Returns",
"index",
"and",
"segment",
"of",
"most",
"activated",
"segment",
"above",
"minThreshold",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/TM.py#L1808-L1844 | train | 198,970 |
numenta/htmresearch | htmresearch/algorithms/TM.py | TM.getBestMatchingSegment | def getBestMatchingSegment(self, c, i, activeState):
"""For the given cell, find the segment with the largest number of active
synapses. This routine is aggressive in finding the best match. The
permanence value of synapses is allowed to be below connectedPerm. The number
of active synapses is allowed to be below activationThreshold, but must be
above minThreshold. The routine returns the segment index. If no segments are
found, then an index of -1 is returned.
"""
maxActivity, which = self.minThreshold, -1
for j,s in enumerate(self.cells[c][i]):
activity = self.getSegmentActivityLevel(s, activeState,
connectedSynapsesOnly=False)
if activity >= maxActivity:
maxActivity, which = activity, j
if which == -1:
return None
else:
return self.cells[c][i][which] | python | def getBestMatchingSegment(self, c, i, activeState):
"""For the given cell, find the segment with the largest number of active
synapses. This routine is aggressive in finding the best match. The
permanence value of synapses is allowed to be below connectedPerm. The number
of active synapses is allowed to be below activationThreshold, but must be
above minThreshold. The routine returns the segment index. If no segments are
found, then an index of -1 is returned.
"""
maxActivity, which = self.minThreshold, -1
for j,s in enumerate(self.cells[c][i]):
activity = self.getSegmentActivityLevel(s, activeState,
connectedSynapsesOnly=False)
if activity >= maxActivity:
maxActivity, which = activity, j
if which == -1:
return None
else:
return self.cells[c][i][which] | [
"def",
"getBestMatchingSegment",
"(",
"self",
",",
"c",
",",
"i",
",",
"activeState",
")",
":",
"maxActivity",
",",
"which",
"=",
"self",
".",
"minThreshold",
",",
"-",
"1",
"for",
"j",
",",
"s",
"in",
"enumerate",
"(",
"self",
".",
"cells",
"[",
"c"... | For the given cell, find the segment with the largest number of active
synapses. This routine is aggressive in finding the best match. The
permanence value of synapses is allowed to be below connectedPerm. The number
of active synapses is allowed to be below activationThreshold, but must be
above minThreshold. The routine returns the segment index. If no segments are
found, then an index of -1 is returned. | [
"For",
"the",
"given",
"cell",
"find",
"the",
"segment",
"with",
"the",
"largest",
"number",
"of",
"active",
"synapses",
".",
"This",
"routine",
"is",
"aggressive",
"in",
"finding",
"the",
"best",
"match",
".",
"The",
"permanence",
"value",
"of",
"synapses",... | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/TM.py#L1847-L1867 | train | 198,971 |
numenta/htmresearch | htmresearch/algorithms/TM.py | TM.getLeastUsedCell | def getLeastUsedCell(self, c):
"""For the least used cell in a column"""
segmentsPerCell = numpy.zeros(self.cellsPerColumn, dtype='uint32')
for i in range(self.cellsPerColumn):
segmentsPerCell[i] = self.getNumSegmentsInCell(c,i)
cellMinUsage = numpy.where(segmentsPerCell==segmentsPerCell.min())[0]
# return cellMinUsage[0] # return the first cell with minimum usage
# if multiple cells has minimum usage, randomly pick one
self._random.getUInt32(len(cellMinUsage))
return cellMinUsage[self._random.getUInt32(len(cellMinUsage))] | python | def getLeastUsedCell(self, c):
"""For the least used cell in a column"""
segmentsPerCell = numpy.zeros(self.cellsPerColumn, dtype='uint32')
for i in range(self.cellsPerColumn):
segmentsPerCell[i] = self.getNumSegmentsInCell(c,i)
cellMinUsage = numpy.where(segmentsPerCell==segmentsPerCell.min())[0]
# return cellMinUsage[0] # return the first cell with minimum usage
# if multiple cells has minimum usage, randomly pick one
self._random.getUInt32(len(cellMinUsage))
return cellMinUsage[self._random.getUInt32(len(cellMinUsage))] | [
"def",
"getLeastUsedCell",
"(",
"self",
",",
"c",
")",
":",
"segmentsPerCell",
"=",
"numpy",
".",
"zeros",
"(",
"self",
".",
"cellsPerColumn",
",",
"dtype",
"=",
"'uint32'",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"cellsPerColumn",
")",
":",
... | For the least used cell in a column | [
"For",
"the",
"least",
"used",
"cell",
"in",
"a",
"column"
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/TM.py#L1870-L1881 | train | 198,972 |
numenta/htmresearch | htmresearch/algorithms/TM.py | TM.updateSynapses | def updateSynapses(self, segment, synapses, delta):
"""Update a set of synapses of the given segment,
delta can be permanenceInc, or permanenceDec.
retval: True if synapse reached 0
"""
reached0 = False
if delta > 0:
for synapse in synapses:
segment[synapse][2] = newValue = segment[synapse][2] + delta
# Cap synapse permanence at permanenceMax
if newValue > self.permanenceMax:
segment[synapse][2] = self.permanenceMax
else:
for synapse in synapses:
segment[synapse][2] = newValue = segment[synapse][2] + delta
# Cap min synapse permanence to 0 in case there is no global decay
if newValue < 0:
segment[synapse][2] = 0
reached0 = True
return reached0 | python | def updateSynapses(self, segment, synapses, delta):
"""Update a set of synapses of the given segment,
delta can be permanenceInc, or permanenceDec.
retval: True if synapse reached 0
"""
reached0 = False
if delta > 0:
for synapse in synapses:
segment[synapse][2] = newValue = segment[synapse][2] + delta
# Cap synapse permanence at permanenceMax
if newValue > self.permanenceMax:
segment[synapse][2] = self.permanenceMax
else:
for synapse in synapses:
segment[synapse][2] = newValue = segment[synapse][2] + delta
# Cap min synapse permanence to 0 in case there is no global decay
if newValue < 0:
segment[synapse][2] = 0
reached0 = True
return reached0 | [
"def",
"updateSynapses",
"(",
"self",
",",
"segment",
",",
"synapses",
",",
"delta",
")",
":",
"reached0",
"=",
"False",
"if",
"delta",
">",
"0",
":",
"for",
"synapse",
"in",
"synapses",
":",
"segment",
"[",
"synapse",
"]",
"[",
"2",
"]",
"=",
"newVa... | Update a set of synapses of the given segment,
delta can be permanenceInc, or permanenceDec.
retval: True if synapse reached 0 | [
"Update",
"a",
"set",
"of",
"synapses",
"of",
"the",
"given",
"segment",
"delta",
"can",
"be",
"permanenceInc",
"or",
"permanenceDec",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/TM.py#L1884-L1910 | train | 198,973 |
numenta/htmresearch | htmresearch/algorithms/TM.py | TM.adaptSegment | def adaptSegment(self, segUpdate, positiveReinforcement):
"""This function applies segment update information to a segment in a
cell.
If positiveReinforcement is true then synapses on the active list
get their permanence counts incremented by permanenceInc. All other synapses
get their permanence counts decremented by permanenceDec.
If positiveReinforcement is false, then synapses on the active list get
their permanence counts decremented by permanenceDec. After this step,
any synapses in segmentUpdate that do yet exist get added with a
permanence count of initialPerm.
Parameters:
-----------------------------------------------------------
segUpdate: SegmentUpdate instance
positiveReinforcement: True for positive enforcement, false for
negative re-enforcement
retval: True if some synapses were decremented to 0
and the segment is a candidate for trimming
"""
# This will be set to True if detect that any syapses were decremented to
# 0
trimSegment = False
# segUpdate.segment is None when creating a new segment
c, i, segment = segUpdate.columnIdx, segUpdate.cellIdx, segUpdate.segment
# update.activeSynapses can be empty.
# If not, it can contain either or both integers and tuples.
# The integers are indices of synapses to update.
# The tuples represent new synapses to create (src col, src cell in col).
# We pre-process to separate these various element types.
# synToCreate is not empty only if positiveReinforcement is True.
# NOTE: the synapse indices start at *1* to skip the segment flags.
activeSynapses = segUpdate.activeSynapses
synToUpdate = set([syn for syn in activeSynapses if type(syn) == int])
if segment is not None: # modify an existing segment
if positiveReinforcement:
if self.verbosity >= 4:
print "Reinforcing segment for cell[%d,%d]" %(c,i),
segment.printSegment()
# Update frequency and positiveActivations
segment.positiveActivations += 1 # positiveActivations += 1
segment.dutyCycle(active=True)
# First, decrement synapses that are not active
# s is a synapse *index*, with index 0 in the segment being the tuple
# (segId, sequence segment flag). See below, creation of segments.
lastSynIndex = len(segment.syns) - 1
inactiveSynIndices = [s for s in xrange(0, lastSynIndex+1) \
if s not in synToUpdate]
trimSegment = segment.updateSynapses(inactiveSynIndices,
-self.permanenceDec)
# Now, increment active synapses
activeSynIndices = [syn for syn in synToUpdate if syn <= lastSynIndex]
segment.updateSynapses(activeSynIndices, self.permanenceInc)
# Finally, create new synapses if needed
# syn is now a tuple (src col, src cell)
synsToAdd = [syn for syn in activeSynapses if type(syn) != int]
for newSyn in synsToAdd:
segment.addSynapse(newSyn[0], newSyn[1], self.initialPerm)
if self.verbosity >= 4:
print " after",
segment.printSegment()
else: # positiveReinforcement is False
desc = ""
if self.verbosity >= 4:
print "Negatively Reinforcing %s segment for cell[%d,%d]" \
% (desc, c,i),
segment.printSegment()
# Decrease frequency count
segment.dutyCycle(active=True)
# We decrement all the "active" that were passed in
trimSegment = segment.updateSynapses(synToUpdate,
-self.permanenceDec)
if self.verbosity >= 4:
print " after",
segment.printSegment()
else: # segment is None: create a new segment
newSegment = Segment(tp=self, isSequenceSeg=segUpdate.sequenceSegment)
# numpy.float32 important so that we can match with C++
for synapse in activeSynapses:
newSegment.addSynapse(synapse[0], synapse[1], self.initialPerm)
if self.verbosity >= 3:
print "New segment for cell[%d,%d]" %(c,i),
newSegment.printSegment()
self.cells[c][i].append(newSegment)
return trimSegment | python | def adaptSegment(self, segUpdate, positiveReinforcement):
"""This function applies segment update information to a segment in a
cell.
If positiveReinforcement is true then synapses on the active list
get their permanence counts incremented by permanenceInc. All other synapses
get their permanence counts decremented by permanenceDec.
If positiveReinforcement is false, then synapses on the active list get
their permanence counts decremented by permanenceDec. After this step,
any synapses in segmentUpdate that do yet exist get added with a
permanence count of initialPerm.
Parameters:
-----------------------------------------------------------
segUpdate: SegmentUpdate instance
positiveReinforcement: True for positive enforcement, false for
negative re-enforcement
retval: True if some synapses were decremented to 0
and the segment is a candidate for trimming
"""
# This will be set to True if detect that any syapses were decremented to
# 0
trimSegment = False
# segUpdate.segment is None when creating a new segment
c, i, segment = segUpdate.columnIdx, segUpdate.cellIdx, segUpdate.segment
# update.activeSynapses can be empty.
# If not, it can contain either or both integers and tuples.
# The integers are indices of synapses to update.
# The tuples represent new synapses to create (src col, src cell in col).
# We pre-process to separate these various element types.
# synToCreate is not empty only if positiveReinforcement is True.
# NOTE: the synapse indices start at *1* to skip the segment flags.
activeSynapses = segUpdate.activeSynapses
synToUpdate = set([syn for syn in activeSynapses if type(syn) == int])
if segment is not None: # modify an existing segment
if positiveReinforcement:
if self.verbosity >= 4:
print "Reinforcing segment for cell[%d,%d]" %(c,i),
segment.printSegment()
# Update frequency and positiveActivations
segment.positiveActivations += 1 # positiveActivations += 1
segment.dutyCycle(active=True)
# First, decrement synapses that are not active
# s is a synapse *index*, with index 0 in the segment being the tuple
# (segId, sequence segment flag). See below, creation of segments.
lastSynIndex = len(segment.syns) - 1
inactiveSynIndices = [s for s in xrange(0, lastSynIndex+1) \
if s not in synToUpdate]
trimSegment = segment.updateSynapses(inactiveSynIndices,
-self.permanenceDec)
# Now, increment active synapses
activeSynIndices = [syn for syn in synToUpdate if syn <= lastSynIndex]
segment.updateSynapses(activeSynIndices, self.permanenceInc)
# Finally, create new synapses if needed
# syn is now a tuple (src col, src cell)
synsToAdd = [syn for syn in activeSynapses if type(syn) != int]
for newSyn in synsToAdd:
segment.addSynapse(newSyn[0], newSyn[1], self.initialPerm)
if self.verbosity >= 4:
print " after",
segment.printSegment()
else: # positiveReinforcement is False
desc = ""
if self.verbosity >= 4:
print "Negatively Reinforcing %s segment for cell[%d,%d]" \
% (desc, c,i),
segment.printSegment()
# Decrease frequency count
segment.dutyCycle(active=True)
# We decrement all the "active" that were passed in
trimSegment = segment.updateSynapses(synToUpdate,
-self.permanenceDec)
if self.verbosity >= 4:
print " after",
segment.printSegment()
else: # segment is None: create a new segment
newSegment = Segment(tp=self, isSequenceSeg=segUpdate.sequenceSegment)
# numpy.float32 important so that we can match with C++
for synapse in activeSynapses:
newSegment.addSynapse(synapse[0], synapse[1], self.initialPerm)
if self.verbosity >= 3:
print "New segment for cell[%d,%d]" %(c,i),
newSegment.printSegment()
self.cells[c][i].append(newSegment)
return trimSegment | [
"def",
"adaptSegment",
"(",
"self",
",",
"segUpdate",
",",
"positiveReinforcement",
")",
":",
"# This will be set to True if detect that any syapses were decremented to",
"# 0",
"trimSegment",
"=",
"False",
"# segUpdate.segment is None when creating a new segment",
"c",
",",
"i"... | This function applies segment update information to a segment in a
cell.
If positiveReinforcement is true then synapses on the active list
get their permanence counts incremented by permanenceInc. All other synapses
get their permanence counts decremented by permanenceDec.
If positiveReinforcement is false, then synapses on the active list get
their permanence counts decremented by permanenceDec. After this step,
any synapses in segmentUpdate that do yet exist get added with a
permanence count of initialPerm.
Parameters:
-----------------------------------------------------------
segUpdate: SegmentUpdate instance
positiveReinforcement: True for positive enforcement, false for
negative re-enforcement
retval: True if some synapses were decremented to 0
and the segment is a candidate for trimming | [
"This",
"function",
"applies",
"segment",
"update",
"information",
"to",
"a",
"segment",
"in",
"a",
"cell",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/TM.py#L1988-L2100 | train | 198,974 |
numenta/htmresearch | htmresearch/algorithms/TM.py | TM.getSegmentInfo | def getSegmentInfo(self, collectActiveData = False):
"""Returns information about the distribution of segments, synapses and
permanence values in the current TP. If requested, also returns information
regarding the number of currently active segments and synapses.
The method returns the following tuple:
(
nSegments, # total number of segments
nSynapses, # total number of synapses
nActiveSegs, # total no. of active segments
nActiveSynapses, # total no. of active synapses
distSegSizes, # a dict where d[n] = number of segments with n synapses
distNSegsPerCell, # a dict where d[n] = number of cells with n segments
distPermValues, # a dict where d[p] = number of synapses with perm = p/10
distAges, # a list of tuples (ageRange, numSegments)
)
nActiveSegs and nActiveSynapses are 0 if collectActiveData is False
"""
nSegments, nSynapses = 0, 0
nActiveSegs, nActiveSynapses = 0, 0
distSegSizes, distNSegsPerCell = {}, {}
distPermValues = {} # Num synapses with given permanence values
numAgeBuckets = 20
distAges = []
ageBucketSize = int((self.lrnIterationIdx+20) / 20)
for i in range(numAgeBuckets):
distAges.append(['%d-%d' % (i*ageBucketSize, (i+1)*ageBucketSize-1), 0])
for c in xrange(self.numberOfCols):
for i in xrange(self.cellsPerColumn):
if len(self.cells[c][i]) > 0:
nSegmentsThisCell = len(self.cells[c][i])
nSegments += nSegmentsThisCell
if distNSegsPerCell.has_key(nSegmentsThisCell):
distNSegsPerCell[nSegmentsThisCell] += 1
else:
distNSegsPerCell[nSegmentsThisCell] = 1
for seg in self.cells[c][i]:
nSynapsesThisSeg = seg.getNumSynapses()
nSynapses += nSynapsesThisSeg
if distSegSizes.has_key(nSynapsesThisSeg):
distSegSizes[nSynapsesThisSeg] += 1
else:
distSegSizes[nSynapsesThisSeg] = 1
# Accumulate permanence value histogram
for syn in seg.syns:
p = int(syn[2]*10)
if distPermValues.has_key(p):
distPermValues[p] += 1
else:
distPermValues[p] = 1
# Accumulate segment age histogram
age = self.lrnIterationIdx - seg.lastActiveIteration
ageBucket = int(age/ageBucketSize)
distAges[ageBucket][1] += 1
# Get active synapse statistics if requested
if collectActiveData:
if self.isSegmentActive(seg, self.infActiveState['t']):
nActiveSegs += 1
for syn in seg.syns:
if self.activeState['t'][syn[0]][syn[1]] == 1:
nActiveSynapses += 1
return (nSegments, nSynapses, nActiveSegs, nActiveSynapses,
distSegSizes, distNSegsPerCell, distPermValues, distAges) | python | def getSegmentInfo(self, collectActiveData = False):
"""Returns information about the distribution of segments, synapses and
permanence values in the current TP. If requested, also returns information
regarding the number of currently active segments and synapses.
The method returns the following tuple:
(
nSegments, # total number of segments
nSynapses, # total number of synapses
nActiveSegs, # total no. of active segments
nActiveSynapses, # total no. of active synapses
distSegSizes, # a dict where d[n] = number of segments with n synapses
distNSegsPerCell, # a dict where d[n] = number of cells with n segments
distPermValues, # a dict where d[p] = number of synapses with perm = p/10
distAges, # a list of tuples (ageRange, numSegments)
)
nActiveSegs and nActiveSynapses are 0 if collectActiveData is False
"""
nSegments, nSynapses = 0, 0
nActiveSegs, nActiveSynapses = 0, 0
distSegSizes, distNSegsPerCell = {}, {}
distPermValues = {} # Num synapses with given permanence values
numAgeBuckets = 20
distAges = []
ageBucketSize = int((self.lrnIterationIdx+20) / 20)
for i in range(numAgeBuckets):
distAges.append(['%d-%d' % (i*ageBucketSize, (i+1)*ageBucketSize-1), 0])
for c in xrange(self.numberOfCols):
for i in xrange(self.cellsPerColumn):
if len(self.cells[c][i]) > 0:
nSegmentsThisCell = len(self.cells[c][i])
nSegments += nSegmentsThisCell
if distNSegsPerCell.has_key(nSegmentsThisCell):
distNSegsPerCell[nSegmentsThisCell] += 1
else:
distNSegsPerCell[nSegmentsThisCell] = 1
for seg in self.cells[c][i]:
nSynapsesThisSeg = seg.getNumSynapses()
nSynapses += nSynapsesThisSeg
if distSegSizes.has_key(nSynapsesThisSeg):
distSegSizes[nSynapsesThisSeg] += 1
else:
distSegSizes[nSynapsesThisSeg] = 1
# Accumulate permanence value histogram
for syn in seg.syns:
p = int(syn[2]*10)
if distPermValues.has_key(p):
distPermValues[p] += 1
else:
distPermValues[p] = 1
# Accumulate segment age histogram
age = self.lrnIterationIdx - seg.lastActiveIteration
ageBucket = int(age/ageBucketSize)
distAges[ageBucket][1] += 1
# Get active synapse statistics if requested
if collectActiveData:
if self.isSegmentActive(seg, self.infActiveState['t']):
nActiveSegs += 1
for syn in seg.syns:
if self.activeState['t'][syn[0]][syn[1]] == 1:
nActiveSynapses += 1
return (nSegments, nSynapses, nActiveSegs, nActiveSynapses,
distSegSizes, distNSegsPerCell, distPermValues, distAges) | [
"def",
"getSegmentInfo",
"(",
"self",
",",
"collectActiveData",
"=",
"False",
")",
":",
"nSegments",
",",
"nSynapses",
"=",
"0",
",",
"0",
"nActiveSegs",
",",
"nActiveSynapses",
"=",
"0",
",",
"0",
"distSegSizes",
",",
"distNSegsPerCell",
"=",
"{",
"}",
",... | Returns information about the distribution of segments, synapses and
permanence values in the current TP. If requested, also returns information
regarding the number of currently active segments and synapses.
The method returns the following tuple:
(
nSegments, # total number of segments
nSynapses, # total number of synapses
nActiveSegs, # total no. of active segments
nActiveSynapses, # total no. of active synapses
distSegSizes, # a dict where d[n] = number of segments with n synapses
distNSegsPerCell, # a dict where d[n] = number of cells with n segments
distPermValues, # a dict where d[p] = number of synapses with perm = p/10
distAges, # a list of tuples (ageRange, numSegments)
)
nActiveSegs and nActiveSynapses are 0 if collectActiveData is False | [
"Returns",
"information",
"about",
"the",
"distribution",
"of",
"segments",
"synapses",
"and",
"permanence",
"values",
"in",
"the",
"current",
"TP",
".",
"If",
"requested",
"also",
"returns",
"information",
"regarding",
"the",
"number",
"of",
"currently",
"active"... | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/TM.py#L2103-L2175 | train | 198,975 |
numenta/htmresearch | htmresearch/algorithms/TM.py | Segment.updateSynapses | def updateSynapses(self, synapses, delta):
"""Update a set of synapses in the segment.
@param tp The owner TP
@param synapses List of synapse indices to update
@param delta How much to add to each permanence
@returns True if synapse reached 0
"""
reached0 = False
if delta > 0:
for synapse in synapses:
self.syns[synapse][2] = newValue = self.syns[synapse][2] + delta
# Cap synapse permanence at permanenceMax
if newValue > self.tp.permanenceMax:
self.syns[synapse][2] = self.tp.permanenceMax
else:
for synapse in synapses:
self.syns[synapse][2] = newValue = self.syns[synapse][2] + delta
# Cap min synapse permanence to 0 in case there is no global decay
if newValue <= 0:
self.syns[synapse][2] = 0
reached0 = True
return reached0 | python | def updateSynapses(self, synapses, delta):
"""Update a set of synapses in the segment.
@param tp The owner TP
@param synapses List of synapse indices to update
@param delta How much to add to each permanence
@returns True if synapse reached 0
"""
reached0 = False
if delta > 0:
for synapse in synapses:
self.syns[synapse][2] = newValue = self.syns[synapse][2] + delta
# Cap synapse permanence at permanenceMax
if newValue > self.tp.permanenceMax:
self.syns[synapse][2] = self.tp.permanenceMax
else:
for synapse in synapses:
self.syns[synapse][2] = newValue = self.syns[synapse][2] + delta
# Cap min synapse permanence to 0 in case there is no global decay
if newValue <= 0:
self.syns[synapse][2] = 0
reached0 = True
return reached0 | [
"def",
"updateSynapses",
"(",
"self",
",",
"synapses",
",",
"delta",
")",
":",
"reached0",
"=",
"False",
"if",
"delta",
">",
"0",
":",
"for",
"synapse",
"in",
"synapses",
":",
"self",
".",
"syns",
"[",
"synapse",
"]",
"[",
"2",
"]",
"=",
"newValue",
... | Update a set of synapses in the segment.
@param tp The owner TP
@param synapses List of synapse indices to update
@param delta How much to add to each permanence
@returns True if synapse reached 0 | [
"Update",
"a",
"set",
"of",
"synapses",
"in",
"the",
"segment",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/TM.py#L2426-L2454 | train | 198,976 |
numenta/htmresearch | htmresearch/frameworks/pytorch/duty_cycle_metrics.py | maxEntropy | def maxEntropy(n,k):
"""
The maximum enropy we could get with n units and k winners
"""
s = float(k)/n
if s > 0.0 and s < 1.0:
entropy = - s * math.log(s,2) - (1 - s) * math.log(1 - s,2)
else:
entropy = 0
return n*entropy | python | def maxEntropy(n,k):
"""
The maximum enropy we could get with n units and k winners
"""
s = float(k)/n
if s > 0.0 and s < 1.0:
entropy = - s * math.log(s,2) - (1 - s) * math.log(1 - s,2)
else:
entropy = 0
return n*entropy | [
"def",
"maxEntropy",
"(",
"n",
",",
"k",
")",
":",
"s",
"=",
"float",
"(",
"k",
")",
"/",
"n",
"if",
"s",
">",
"0.0",
"and",
"s",
"<",
"1.0",
":",
"entropy",
"=",
"-",
"s",
"*",
"math",
".",
"log",
"(",
"s",
",",
"2",
")",
"-",
"(",
"1"... | The maximum enropy we could get with n units and k winners | [
"The",
"maximum",
"enropy",
"we",
"could",
"get",
"with",
"n",
"units",
"and",
"k",
"winners"
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/pytorch/duty_cycle_metrics.py#L29-L40 | train | 198,977 |
numenta/htmresearch | htmresearch/frameworks/pytorch/duty_cycle_metrics.py | binaryEntropy | def binaryEntropy(x):
"""
Calculate entropy for a list of binary random variables
:param x: (torch tensor) the probability of the variable to be 1.
:return: entropy: (torch tensor) entropy, sum(entropy)
"""
entropy = - x*x.log2() - (1-x)*(1-x).log2()
entropy[x*(1 - x) == 0] = 0
return entropy, entropy.sum() | python | def binaryEntropy(x):
"""
Calculate entropy for a list of binary random variables
:param x: (torch tensor) the probability of the variable to be 1.
:return: entropy: (torch tensor) entropy, sum(entropy)
"""
entropy = - x*x.log2() - (1-x)*(1-x).log2()
entropy[x*(1 - x) == 0] = 0
return entropy, entropy.sum() | [
"def",
"binaryEntropy",
"(",
"x",
")",
":",
"entropy",
"=",
"-",
"x",
"*",
"x",
".",
"log2",
"(",
")",
"-",
"(",
"1",
"-",
"x",
")",
"*",
"(",
"1",
"-",
"x",
")",
".",
"log2",
"(",
")",
"entropy",
"[",
"x",
"*",
"(",
"1",
"-",
"x",
")",... | Calculate entropy for a list of binary random variables
:param x: (torch tensor) the probability of the variable to be 1.
:return: entropy: (torch tensor) entropy, sum(entropy) | [
"Calculate",
"entropy",
"for",
"a",
"list",
"of",
"binary",
"random",
"variables"
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/pytorch/duty_cycle_metrics.py#L43-L52 | train | 198,978 |
numenta/htmresearch | htmresearch/frameworks/pytorch/duty_cycle_metrics.py | plotDutyCycles | def plotDutyCycles(dutyCycle, filePath):
"""
Create plot showing histogram of duty cycles
:param dutyCycle: (torch tensor) the duty cycle of each unit
:param filePath: (str) Full filename of image file
"""
_,entropy = binaryEntropy(dutyCycle)
bins = np.linspace(0.0, 0.3, 200)
plt.hist(dutyCycle, bins, alpha=0.5, label='All cols')
plt.title("Histogram of duty cycles, entropy=" + str(float(entropy)))
plt.xlabel("Duty cycle")
plt.ylabel("Number of units")
plt.savefig(filePath)
plt.close() | python | def plotDutyCycles(dutyCycle, filePath):
"""
Create plot showing histogram of duty cycles
:param dutyCycle: (torch tensor) the duty cycle of each unit
:param filePath: (str) Full filename of image file
"""
_,entropy = binaryEntropy(dutyCycle)
bins = np.linspace(0.0, 0.3, 200)
plt.hist(dutyCycle, bins, alpha=0.5, label='All cols')
plt.title("Histogram of duty cycles, entropy=" + str(float(entropy)))
plt.xlabel("Duty cycle")
plt.ylabel("Number of units")
plt.savefig(filePath)
plt.close() | [
"def",
"plotDutyCycles",
"(",
"dutyCycle",
",",
"filePath",
")",
":",
"_",
",",
"entropy",
"=",
"binaryEntropy",
"(",
"dutyCycle",
")",
"bins",
"=",
"np",
".",
"linspace",
"(",
"0.0",
",",
"0.3",
",",
"200",
")",
"plt",
".",
"hist",
"(",
"dutyCycle",
... | Create plot showing histogram of duty cycles
:param dutyCycle: (torch tensor) the duty cycle of each unit
:param filePath: (str) Full filename of image file | [
"Create",
"plot",
"showing",
"histogram",
"of",
"duty",
"cycles"
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/pytorch/duty_cycle_metrics.py#L55-L69 | train | 198,979 |
numenta/htmresearch | projects/lateral_pooler/src/sp_wrapper.py | SpatialPoolerWrapper.compute | def compute(self, inputVector, learn, activeArray):
"""
This method resembles the primary public method of the SpatialPooler class.
"""
super(SpatialPoolerWrapper, self).compute(inputVector, learn, activeArray)
self._updateAvgActivityPairs(activeArray) | python | def compute(self, inputVector, learn, activeArray):
"""
This method resembles the primary public method of the SpatialPooler class.
"""
super(SpatialPoolerWrapper, self).compute(inputVector, learn, activeArray)
self._updateAvgActivityPairs(activeArray) | [
"def",
"compute",
"(",
"self",
",",
"inputVector",
",",
"learn",
",",
"activeArray",
")",
":",
"super",
"(",
"SpatialPoolerWrapper",
",",
"self",
")",
".",
"compute",
"(",
"inputVector",
",",
"learn",
",",
"activeArray",
")",
"self",
".",
"_updateAvgActivity... | This method resembles the primary public method of the SpatialPooler class. | [
"This",
"method",
"resembles",
"the",
"primary",
"public",
"method",
"of",
"the",
"SpatialPooler",
"class",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/lateral_pooler/src/sp_wrapper.py#L43-L49 | train | 198,980 |
numenta/htmresearch | projects/speech_commands/parameters_table.py | computeMaxPool | def computeMaxPool(input_width):
"""
Compute CNN max pool width. see 'cnn_sdr.py'
"""
wout = math.floor((input_width + 2 * PADDING - KERNEL_SIZE) / STRIDE + 1)
return int(math.floor(wout / 2.0)) | python | def computeMaxPool(input_width):
"""
Compute CNN max pool width. see 'cnn_sdr.py'
"""
wout = math.floor((input_width + 2 * PADDING - KERNEL_SIZE) / STRIDE + 1)
return int(math.floor(wout / 2.0)) | [
"def",
"computeMaxPool",
"(",
"input_width",
")",
":",
"wout",
"=",
"math",
".",
"floor",
"(",
"(",
"input_width",
"+",
"2",
"*",
"PADDING",
"-",
"KERNEL_SIZE",
")",
"/",
"STRIDE",
"+",
"1",
")",
"return",
"int",
"(",
"math",
".",
"floor",
"(",
"wout... | Compute CNN max pool width. see 'cnn_sdr.py' | [
"Compute",
"CNN",
"max",
"pool",
"width",
".",
"see",
"cnn_sdr",
".",
"py"
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/speech_commands/parameters_table.py#L40-L45 | train | 198,981 |
numenta/htmresearch | htmresearch/frameworks/layers/simple_object_machine.py | SimpleObjectMachine.createRandomObjects | def createRandomObjects(self,
numObjects,
numPoints,
numLocations=None,
numFeatures=None):
"""
Creates a set of random objects and adds them to the machine.
If numLocations and numFeatures and not specified, they will be set to the
desired number of points.
"""
if numObjects > 0:
if numLocations is None:
numLocations = numPoints
if numFeatures is None:
numFeatures = numPoints
assert(numPoints <= numLocations), ("Number of points in object cannot be "
"greater than number of locations")
locationArray = numpy.array(range(numLocations))
numpy.random.seed(self.seed)
for _ in xrange(numObjects):
# Permute the number of locations and select points from it
locationArray = numpy.random.permutation(locationArray)
self.addObject(
[(locationArray[p],
numpy.random.randint(0, numFeatures)) for p in xrange(numPoints)],
) | python | def createRandomObjects(self,
numObjects,
numPoints,
numLocations=None,
numFeatures=None):
"""
Creates a set of random objects and adds them to the machine.
If numLocations and numFeatures and not specified, they will be set to the
desired number of points.
"""
if numObjects > 0:
if numLocations is None:
numLocations = numPoints
if numFeatures is None:
numFeatures = numPoints
assert(numPoints <= numLocations), ("Number of points in object cannot be "
"greater than number of locations")
locationArray = numpy.array(range(numLocations))
numpy.random.seed(self.seed)
for _ in xrange(numObjects):
# Permute the number of locations and select points from it
locationArray = numpy.random.permutation(locationArray)
self.addObject(
[(locationArray[p],
numpy.random.randint(0, numFeatures)) for p in xrange(numPoints)],
) | [
"def",
"createRandomObjects",
"(",
"self",
",",
"numObjects",
",",
"numPoints",
",",
"numLocations",
"=",
"None",
",",
"numFeatures",
"=",
"None",
")",
":",
"if",
"numObjects",
">",
"0",
":",
"if",
"numLocations",
"is",
"None",
":",
"numLocations",
"=",
"n... | Creates a set of random objects and adds them to the machine.
If numLocations and numFeatures and not specified, they will be set to the
desired number of points. | [
"Creates",
"a",
"set",
"of",
"random",
"objects",
"and",
"adds",
"them",
"to",
"the",
"machine",
".",
"If",
"numLocations",
"and",
"numFeatures",
"and",
"not",
"specified",
"they",
"will",
"be",
"set",
"to",
"the",
"desired",
"number",
"of",
"points",
"."
... | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/simple_object_machine.py#L212-L239 | train | 198,982 |
numenta/htmresearch | htmresearch/frameworks/layers/simple_object_machine.py | SimpleObjectMachine.getUniqueFeaturesLocationsInObject | def getUniqueFeaturesLocationsInObject(self, name):
"""
Return two sets. The first set contains the unique locations Ids in the
object. The second set contains the unique feature Ids in the object.
"""
uniqueFeatures = set()
uniqueLocations = set()
for pair in self.objects[name]:
uniqueLocations = uniqueLocations.union({pair[0]})
uniqueFeatures = uniqueFeatures.union({pair[1]})
return uniqueLocations, uniqueFeatures | python | def getUniqueFeaturesLocationsInObject(self, name):
"""
Return two sets. The first set contains the unique locations Ids in the
object. The second set contains the unique feature Ids in the object.
"""
uniqueFeatures = set()
uniqueLocations = set()
for pair in self.objects[name]:
uniqueLocations = uniqueLocations.union({pair[0]})
uniqueFeatures = uniqueFeatures.union({pair[1]})
return uniqueLocations, uniqueFeatures | [
"def",
"getUniqueFeaturesLocationsInObject",
"(",
"self",
",",
"name",
")",
":",
"uniqueFeatures",
"=",
"set",
"(",
")",
"uniqueLocations",
"=",
"set",
"(",
")",
"for",
"pair",
"in",
"self",
".",
"objects",
"[",
"name",
"]",
":",
"uniqueLocations",
"=",
"u... | Return two sets. The first set contains the unique locations Ids in the
object. The second set contains the unique feature Ids in the object. | [
"Return",
"two",
"sets",
".",
"The",
"first",
"set",
"contains",
"the",
"unique",
"locations",
"Ids",
"in",
"the",
"object",
".",
"The",
"second",
"set",
"contains",
"the",
"unique",
"feature",
"Ids",
"in",
"the",
"object",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/simple_object_machine.py#L253-L264 | train | 198,983 |
numenta/htmresearch | htmresearch/frameworks/layers/simple_object_machine.py | SimpleObjectMachine._generateLocations | def _generateLocations(self):
"""
Generates a pool of locations to be used for the experiments.
For each index, numColumns SDR's are created, as locations for the same
feature should be different for each column.
"""
size = self.externalInputSize
bits = self.numInputBits
random.seed(self.seed)
self.locations = []
for _ in xrange(self.numColumns):
self.locations.append(
[self._generatePattern(bits, size) for _ in xrange(self.numLocations)]
) | python | def _generateLocations(self):
"""
Generates a pool of locations to be used for the experiments.
For each index, numColumns SDR's are created, as locations for the same
feature should be different for each column.
"""
size = self.externalInputSize
bits = self.numInputBits
random.seed(self.seed)
self.locations = []
for _ in xrange(self.numColumns):
self.locations.append(
[self._generatePattern(bits, size) for _ in xrange(self.numLocations)]
) | [
"def",
"_generateLocations",
"(",
"self",
")",
":",
"size",
"=",
"self",
".",
"externalInputSize",
"bits",
"=",
"self",
".",
"numInputBits",
"random",
".",
"seed",
"(",
"self",
".",
"seed",
")",
"self",
".",
"locations",
"=",
"[",
"]",
"for",
"_",
"in"... | Generates a pool of locations to be used for the experiments.
For each index, numColumns SDR's are created, as locations for the same
feature should be different for each column. | [
"Generates",
"a",
"pool",
"of",
"locations",
"to",
"be",
"used",
"for",
"the",
"experiments",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/simple_object_machine.py#L352-L366 | train | 198,984 |
numenta/htmresearch | projects/nab_experiments/run.py | getDetectorClassConstructors | def getDetectorClassConstructors(detectors):
"""
Takes in names of detectors. Collects class names that correspond to those
detectors and returns them in a dict. The dict maps detector name to class
names. Assumes the detectors have been imported.
"""
detectorConstructors = {
d : globals()[detectorNameToClass(d)] for d in detectors}
return detectorConstructors | python | def getDetectorClassConstructors(detectors):
"""
Takes in names of detectors. Collects class names that correspond to those
detectors and returns them in a dict. The dict maps detector name to class
names. Assumes the detectors have been imported.
"""
detectorConstructors = {
d : globals()[detectorNameToClass(d)] for d in detectors}
return detectorConstructors | [
"def",
"getDetectorClassConstructors",
"(",
"detectors",
")",
":",
"detectorConstructors",
"=",
"{",
"d",
":",
"globals",
"(",
")",
"[",
"detectorNameToClass",
"(",
"d",
")",
"]",
"for",
"d",
"in",
"detectors",
"}",
"return",
"detectorConstructors"
] | Takes in names of detectors. Collects class names that correspond to those
detectors and returns them in a dict. The dict maps detector name to class
names. Assumes the detectors have been imported. | [
"Takes",
"in",
"names",
"of",
"detectors",
".",
"Collects",
"class",
"names",
"that",
"correspond",
"to",
"those",
"detectors",
"and",
"returns",
"them",
"in",
"a",
"dict",
".",
"The",
"dict",
"maps",
"detector",
"name",
"to",
"class",
"names",
".",
"Assum... | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/nab_experiments/run.py#L34-L43 | train | 198,985 |
numenta/htmresearch | htmresearch/frameworks/rl/dqn.py | DQN.select_action | def select_action(self, state):
"""
Select the best action for the given state using e-greedy exploration to
minimize overfitting
:return: tuple(action, value)
"""
value = 0
if self.steps < self.min_steps:
action = np.random.randint(self.actions)
else:
self.eps = max(self.eps_end, self.eps * self.eps_decay)
if random.random() < self.eps:
action = np.random.randint(self.actions)
else:
self.local.eval()
with torch.no_grad():
state = torch.tensor(state, device=self.device, dtype=torch.float).unsqueeze(0)
Q = self.local(state)
value, action = torch.max(Q, 1)
return int(action), float(value) | python | def select_action(self, state):
"""
Select the best action for the given state using e-greedy exploration to
minimize overfitting
:return: tuple(action, value)
"""
value = 0
if self.steps < self.min_steps:
action = np.random.randint(self.actions)
else:
self.eps = max(self.eps_end, self.eps * self.eps_decay)
if random.random() < self.eps:
action = np.random.randint(self.actions)
else:
self.local.eval()
with torch.no_grad():
state = torch.tensor(state, device=self.device, dtype=torch.float).unsqueeze(0)
Q = self.local(state)
value, action = torch.max(Q, 1)
return int(action), float(value) | [
"def",
"select_action",
"(",
"self",
",",
"state",
")",
":",
"value",
"=",
"0",
"if",
"self",
".",
"steps",
"<",
"self",
".",
"min_steps",
":",
"action",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"self",
".",
"actions",
")",
"else",
":",
"self... | Select the best action for the given state using e-greedy exploration to
minimize overfitting
:return: tuple(action, value) | [
"Select",
"the",
"best",
"action",
"for",
"the",
"given",
"state",
"using",
"e",
"-",
"greedy",
"exploration",
"to",
"minimize",
"overfitting"
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/rl/dqn.py#L79-L100 | train | 198,986 |
numenta/htmresearch | projects/location_layer/multi_column_2d_experiment/grid_multi_column_experiment.py | MultiColumn2DExperiment.inferObjects | def inferObjects(self, bodyPlacement, maxTouches=2):
"""
Touch each object with multiple sensors twice.
:returns: dict mapping the number of touches required to the number of
objects that took that many touches to be uniquely inferred. The 'None'
key is reserved for objects not recognized after `maxTouches` touches
"""
for monitor in self.monitors.itervalues():
monitor.afterBodyWorldLocationChanged(bodyPlacement)
numTouchesRequired = collections.defaultdict(int)
for objectName, objectFeatures in self.objects.iteritems():
self.reset()
objectPlacement = self.objectPlacements[objectName]
featureIndexByColumnIterator = (
greedySensorPositions(self.numCorticalColumns, len(objectFeatures)))
for touch in xrange(maxTouches):
# Choose where to place each sensor.
featureIndexByColumn = featureIndexByColumnIterator.next()
sensedFeatures = [objectFeatures[i] for i in featureIndexByColumn]
featureSDRByColumn = [self.features[(iCol, feature["name"])]
for iCol, feature in enumerate(sensedFeatures)]
worldLocationByColumn = np.array([
[objectPlacement[0] + feature["top"] + feature["height"]/2,
objectPlacement[1] + feature["left"] + feature["width"]/2]
for feature in sensedFeatures])
for monitor in self.monitors.itervalues():
monitor.afterSensorWorldLocationChanged(worldLocationByColumn)
egocentricLocationByColumn = worldLocationByColumn - bodyPlacement
prevCellActivity = None
for t in xrange(self.maxSettlingTime):
for monitor in self.monitors.itervalues():
monitor.beforeCompute(egocentricLocationByColumn, featureSDRByColumn,
isRepeat=(t > 0))
self.compute(egocentricLocationByColumn, featureSDRByColumn, learn=False)
cellActivity = (
tuple(c.getAllCellActivity()
for c in self.corticalColumns),
tuple(set(module.activeCells)
for module in self.bodyToSpecificObjectModules))
if cellActivity == prevCellActivity:
# It settled. Cancel logging this timestep.
for monitor in self.monitors.itervalues():
monitor.clearUnflushedData()
break
else:
prevCellActivity = cellActivity
for monitor in self.monitors.itervalues():
monitor.flush()
# Check if the object is narrowed down
if self.isObjectClassified(objectName):
numTouchesRequired[touch + 1] += 1
break
else:
numTouchesRequired[None] += 1
return numTouchesRequired | python | def inferObjects(self, bodyPlacement, maxTouches=2):
"""
Touch each object with multiple sensors twice.
:returns: dict mapping the number of touches required to the number of
objects that took that many touches to be uniquely inferred. The 'None'
key is reserved for objects not recognized after `maxTouches` touches
"""
for monitor in self.monitors.itervalues():
monitor.afterBodyWorldLocationChanged(bodyPlacement)
numTouchesRequired = collections.defaultdict(int)
for objectName, objectFeatures in self.objects.iteritems():
self.reset()
objectPlacement = self.objectPlacements[objectName]
featureIndexByColumnIterator = (
greedySensorPositions(self.numCorticalColumns, len(objectFeatures)))
for touch in xrange(maxTouches):
# Choose where to place each sensor.
featureIndexByColumn = featureIndexByColumnIterator.next()
sensedFeatures = [objectFeatures[i] for i in featureIndexByColumn]
featureSDRByColumn = [self.features[(iCol, feature["name"])]
for iCol, feature in enumerate(sensedFeatures)]
worldLocationByColumn = np.array([
[objectPlacement[0] + feature["top"] + feature["height"]/2,
objectPlacement[1] + feature["left"] + feature["width"]/2]
for feature in sensedFeatures])
for monitor in self.monitors.itervalues():
monitor.afterSensorWorldLocationChanged(worldLocationByColumn)
egocentricLocationByColumn = worldLocationByColumn - bodyPlacement
prevCellActivity = None
for t in xrange(self.maxSettlingTime):
for monitor in self.monitors.itervalues():
monitor.beforeCompute(egocentricLocationByColumn, featureSDRByColumn,
isRepeat=(t > 0))
self.compute(egocentricLocationByColumn, featureSDRByColumn, learn=False)
cellActivity = (
tuple(c.getAllCellActivity()
for c in self.corticalColumns),
tuple(set(module.activeCells)
for module in self.bodyToSpecificObjectModules))
if cellActivity == prevCellActivity:
# It settled. Cancel logging this timestep.
for monitor in self.monitors.itervalues():
monitor.clearUnflushedData()
break
else:
prevCellActivity = cellActivity
for monitor in self.monitors.itervalues():
monitor.flush()
# Check if the object is narrowed down
if self.isObjectClassified(objectName):
numTouchesRequired[touch + 1] += 1
break
else:
numTouchesRequired[None] += 1
return numTouchesRequired | [
"def",
"inferObjects",
"(",
"self",
",",
"bodyPlacement",
",",
"maxTouches",
"=",
"2",
")",
":",
"for",
"monitor",
"in",
"self",
".",
"monitors",
".",
"itervalues",
"(",
")",
":",
"monitor",
".",
"afterBodyWorldLocationChanged",
"(",
"bodyPlacement",
")",
"n... | Touch each object with multiple sensors twice.
:returns: dict mapping the number of touches required to the number of
objects that took that many touches to be uniquely inferred. The 'None'
key is reserved for objects not recognized after `maxTouches` touches | [
"Touch",
"each",
"object",
"with",
"multiple",
"sensors",
"twice",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/location_layer/multi_column_2d_experiment/grid_multi_column_experiment.py#L360-L427 | train | 198,987 |
numenta/htmresearch | projects/thing_classification/l2l4l6_experiment.py | plotAccuracy | def plotAccuracy(suite, name):
"""
Plots classification accuracy
"""
path = suite.cfgparser.get(name, "path")
path = os.path.join(path, name)
accuracy = defaultdict(list)
sensations = defaultdict(list)
for exp in suite.get_exps(path=path):
params = suite.get_params(exp)
maxTouches = params["num_sensations"]
cells = params["cells_per_axis"]
res = suite.get_history(exp, 0, "Correct classification")
classified = [any(x) for x in res]
accuracy[cells] = float(sum(classified)) / float(len(classified))
touches = [np.argmax(x) or maxTouches for x in res]
sensations[cells] = [np.mean(touches), np.max(touches)]
plt.title("Classification Accuracy")
accuracy = OrderedDict(sorted(accuracy.items(), key=lambda t: t[0]))
fig, ax1 = plt.subplots()
ax1.plot(accuracy.keys(), accuracy.values(), "b")
ax1.set_xlabel("Cells per axis")
ax1.set_ylabel("Accuracy", color="b")
ax1.tick_params("y", colors="b")
sensations = OrderedDict(sorted(sensations.items(), key=lambda t: t[0]))
ax2 = ax1.twinx()
ax2.set_prop_cycle(linestyle=["-", "--"])
ax2.plot(sensations.keys(), sensations.values(), "r")
ax2.set_ylabel("Sensations", color="r")
ax2.tick_params("y", colors="r")
ax2.legend(("Mean", "Max"))
# save
path = suite.cfgparser.get(name, "path")
plotPath = os.path.join(path, "{}.pdf".format(name))
plt.savefig(plotPath)
plt.close() | python | def plotAccuracy(suite, name):
"""
Plots classification accuracy
"""
path = suite.cfgparser.get(name, "path")
path = os.path.join(path, name)
accuracy = defaultdict(list)
sensations = defaultdict(list)
for exp in suite.get_exps(path=path):
params = suite.get_params(exp)
maxTouches = params["num_sensations"]
cells = params["cells_per_axis"]
res = suite.get_history(exp, 0, "Correct classification")
classified = [any(x) for x in res]
accuracy[cells] = float(sum(classified)) / float(len(classified))
touches = [np.argmax(x) or maxTouches for x in res]
sensations[cells] = [np.mean(touches), np.max(touches)]
plt.title("Classification Accuracy")
accuracy = OrderedDict(sorted(accuracy.items(), key=lambda t: t[0]))
fig, ax1 = plt.subplots()
ax1.plot(accuracy.keys(), accuracy.values(), "b")
ax1.set_xlabel("Cells per axis")
ax1.set_ylabel("Accuracy", color="b")
ax1.tick_params("y", colors="b")
sensations = OrderedDict(sorted(sensations.items(), key=lambda t: t[0]))
ax2 = ax1.twinx()
ax2.set_prop_cycle(linestyle=["-", "--"])
ax2.plot(sensations.keys(), sensations.values(), "r")
ax2.set_ylabel("Sensations", color="r")
ax2.tick_params("y", colors="r")
ax2.legend(("Mean", "Max"))
# save
path = suite.cfgparser.get(name, "path")
plotPath = os.path.join(path, "{}.pdf".format(name))
plt.savefig(plotPath)
plt.close() | [
"def",
"plotAccuracy",
"(",
"suite",
",",
"name",
")",
":",
"path",
"=",
"suite",
".",
"cfgparser",
".",
"get",
"(",
"name",
",",
"\"path\"",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"name",
")",
"accuracy",
"=",
"default... | Plots classification accuracy | [
"Plots",
"classification",
"accuracy"
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/thing_classification/l2l4l6_experiment.py#L192-L234 | train | 198,988 |
numenta/htmresearch | projects/sdr_paper/poirazi_neuron_model/run_HTM_classification_experiment.py | get_error | def get_error(data, labels, pos_neurons, neg_neurons = [], add_noise = True):
"""
Calculates error, including number of false positives and false negatives.
Written to allow the use of multiple neurons, in case we attempt to use a
population in the future.
"""
num_correct = 0
num_false_positives = 0
num_false_negatives = 0
classifications = numpy.zeros(data.nRows())
for neuron in pos_neurons:
classifications += neuron.calculate_on_entire_dataset(data)
for neuron in neg_neurons:
classifications -= neuron.calculate_on_entire_dataset(data)
if add_noise:
classifications += (numpy.random.rand() - 0.5)/1000
classifications = numpy.sign(classifications)
for classification, label in zip(classifications, labels):
if classification > 0 and label > 0:
num_correct += 1.0
elif classification <= 0 and label <= 0:
num_correct += 1.0
elif classification > 0 and label <= 0:
num_false_positives += 1
else:
num_false_negatives += 1
return (1.*num_false_positives + num_false_negatives)/data.nRows(), num_false_positives, num_false_negatives | python | def get_error(data, labels, pos_neurons, neg_neurons = [], add_noise = True):
"""
Calculates error, including number of false positives and false negatives.
Written to allow the use of multiple neurons, in case we attempt to use a
population in the future.
"""
num_correct = 0
num_false_positives = 0
num_false_negatives = 0
classifications = numpy.zeros(data.nRows())
for neuron in pos_neurons:
classifications += neuron.calculate_on_entire_dataset(data)
for neuron in neg_neurons:
classifications -= neuron.calculate_on_entire_dataset(data)
if add_noise:
classifications += (numpy.random.rand() - 0.5)/1000
classifications = numpy.sign(classifications)
for classification, label in zip(classifications, labels):
if classification > 0 and label > 0:
num_correct += 1.0
elif classification <= 0 and label <= 0:
num_correct += 1.0
elif classification > 0 and label <= 0:
num_false_positives += 1
else:
num_false_negatives += 1
return (1.*num_false_positives + num_false_negatives)/data.nRows(), num_false_positives, num_false_negatives | [
"def",
"get_error",
"(",
"data",
",",
"labels",
",",
"pos_neurons",
",",
"neg_neurons",
"=",
"[",
"]",
",",
"add_noise",
"=",
"True",
")",
":",
"num_correct",
"=",
"0",
"num_false_positives",
"=",
"0",
"num_false_negatives",
"=",
"0",
"classifications",
"=",... | Calculates error, including number of false positives and false negatives.
Written to allow the use of multiple neurons, in case we attempt to use a
population in the future. | [
"Calculates",
"error",
"including",
"number",
"of",
"false",
"positives",
"and",
"false",
"negatives",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sdr_paper/poirazi_neuron_model/run_HTM_classification_experiment.py#L118-L146 | train | 198,989 |
numenta/htmresearch | htmresearch/algorithms/multiconnections.py | Multiconnections.computeActivity | def computeActivity(self, activeInputsBySource, permanenceThreshold=None):
"""
Calculate the number of active synapses per segment.
@param activeInputsBySource (dict)
The active cells in each source. Example:
{"customInputName1": np.array([42, 69])}
"""
overlaps = None
for source, connections in self.connectionsBySource.iteritems():
o = connections.computeActivity(activeInputsBySource[source],
permanenceThreshold)
if overlaps is None:
overlaps = o
else:
overlaps += o
return overlaps | python | def computeActivity(self, activeInputsBySource, permanenceThreshold=None):
"""
Calculate the number of active synapses per segment.
@param activeInputsBySource (dict)
The active cells in each source. Example:
{"customInputName1": np.array([42, 69])}
"""
overlaps = None
for source, connections in self.connectionsBySource.iteritems():
o = connections.computeActivity(activeInputsBySource[source],
permanenceThreshold)
if overlaps is None:
overlaps = o
else:
overlaps += o
return overlaps | [
"def",
"computeActivity",
"(",
"self",
",",
"activeInputsBySource",
",",
"permanenceThreshold",
"=",
"None",
")",
":",
"overlaps",
"=",
"None",
"for",
"source",
",",
"connections",
"in",
"self",
".",
"connectionsBySource",
".",
"iteritems",
"(",
")",
":",
"o",... | Calculate the number of active synapses per segment.
@param activeInputsBySource (dict)
The active cells in each source. Example:
{"customInputName1": np.array([42, 69])} | [
"Calculate",
"the",
"number",
"of",
"active",
"synapses",
"per",
"segment",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/multiconnections.py#L50-L68 | train | 198,990 |
numenta/htmresearch | htmresearch/algorithms/multiconnections.py | Multiconnections.createSegments | def createSegments(self, cells):
"""
Create a segment on each of the specified cells.
@param cells (numpy array)
"""
segments = None
for connections in self.connectionsBySource.itervalues():
created = connections.createSegments(cells)
if segments is None:
segments = created
else:
# Sanity-check that the segment numbers are the same.
np.testing.assert_equal(segments, created)
return segments | python | def createSegments(self, cells):
"""
Create a segment on each of the specified cells.
@param cells (numpy array)
"""
segments = None
for connections in self.connectionsBySource.itervalues():
created = connections.createSegments(cells)
if segments is None:
segments = created
else:
# Sanity-check that the segment numbers are the same.
np.testing.assert_equal(segments, created)
return segments | [
"def",
"createSegments",
"(",
"self",
",",
"cells",
")",
":",
"segments",
"=",
"None",
"for",
"connections",
"in",
"self",
".",
"connectionsBySource",
".",
"itervalues",
"(",
")",
":",
"created",
"=",
"connections",
".",
"createSegments",
"(",
"cells",
")",
... | Create a segment on each of the specified cells.
@param cells (numpy array) | [
"Create",
"a",
"segment",
"on",
"each",
"of",
"the",
"specified",
"cells",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/multiconnections.py#L71-L88 | train | 198,991 |
numenta/htmresearch | htmresearch/algorithms/multiconnections.py | Multiconnections.growSynapses | def growSynapses(self, segments, activeInputsBySource, initialPermanence):
"""
Grow synapses to each of the specified inputs on each specified segment.
@param segments (numpy array)
The segments that should add synapses
@param activeInputsBySource (dict)
The active cells in each source. Example:
{"customInputName1": np.array([42, 69])}
@param initialPermanence (float)
"""
for source, connections in self.connectionsBySource.iteritems():
connections.growSynapses(segments, activeInputsBySource[source],
initialPermanence) | python | def growSynapses(self, segments, activeInputsBySource, initialPermanence):
"""
Grow synapses to each of the specified inputs on each specified segment.
@param segments (numpy array)
The segments that should add synapses
@param activeInputsBySource (dict)
The active cells in each source. Example:
{"customInputName1": np.array([42, 69])}
@param initialPermanence (float)
"""
for source, connections in self.connectionsBySource.iteritems():
connections.growSynapses(segments, activeInputsBySource[source],
initialPermanence) | [
"def",
"growSynapses",
"(",
"self",
",",
"segments",
",",
"activeInputsBySource",
",",
"initialPermanence",
")",
":",
"for",
"source",
",",
"connections",
"in",
"self",
".",
"connectionsBySource",
".",
"iteritems",
"(",
")",
":",
"connections",
".",
"growSynapse... | Grow synapses to each of the specified inputs on each specified segment.
@param segments (numpy array)
The segments that should add synapses
@param activeInputsBySource (dict)
The active cells in each source. Example:
{"customInputName1": np.array([42, 69])}
@param initialPermanence (float) | [
"Grow",
"synapses",
"to",
"each",
"of",
"the",
"specified",
"inputs",
"on",
"each",
"specified",
"segment",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/multiconnections.py#L91-L106 | train | 198,992 |
numenta/htmresearch | htmresearch/algorithms/multiconnections.py | Multiconnections.setPermanences | def setPermanences(self, segments, presynapticCellsBySource, permanence):
"""
Set the permanence of a specific set of synapses. Any synapses that don't
exist will be initialized. Any existing synapses will be overwritten.
Conceptually, this method takes a list of [segment, presynapticCell] pairs
and initializes their permanence. For each segment, one synapse is added
(although one might be added for each "source"). To add multiple synapses to
a segment, include it in the list multiple times.
The total number of affected synapses is len(segments)*number_of_sources*1.
@param segments (numpy array)
One segment for each synapse that should be added
@param presynapticCellsBySource (dict of numpy arrays)
One presynaptic cell for each segment.
Example:
{"customInputName1": np.array([42, 69])}
@param permanence (float)
The permanence to assign the synapse
"""
permanences = np.repeat(np.float32(permanence), len(segments))
for source, connections in self.connectionsBySource.iteritems():
if source in presynapticCellsBySource:
connections.matrix.setElements(segments, presynapticCellsBySource[source],
permanences) | python | def setPermanences(self, segments, presynapticCellsBySource, permanence):
"""
Set the permanence of a specific set of synapses. Any synapses that don't
exist will be initialized. Any existing synapses will be overwritten.
Conceptually, this method takes a list of [segment, presynapticCell] pairs
and initializes their permanence. For each segment, one synapse is added
(although one might be added for each "source"). To add multiple synapses to
a segment, include it in the list multiple times.
The total number of affected synapses is len(segments)*number_of_sources*1.
@param segments (numpy array)
One segment for each synapse that should be added
@param presynapticCellsBySource (dict of numpy arrays)
One presynaptic cell for each segment.
Example:
{"customInputName1": np.array([42, 69])}
@param permanence (float)
The permanence to assign the synapse
"""
permanences = np.repeat(np.float32(permanence), len(segments))
for source, connections in self.connectionsBySource.iteritems():
if source in presynapticCellsBySource:
connections.matrix.setElements(segments, presynapticCellsBySource[source],
permanences) | [
"def",
"setPermanences",
"(",
"self",
",",
"segments",
",",
"presynapticCellsBySource",
",",
"permanence",
")",
":",
"permanences",
"=",
"np",
".",
"repeat",
"(",
"np",
".",
"float32",
"(",
"permanence",
")",
",",
"len",
"(",
"segments",
")",
")",
"for",
... | Set the permanence of a specific set of synapses. Any synapses that don't
exist will be initialized. Any existing synapses will be overwritten.
Conceptually, this method takes a list of [segment, presynapticCell] pairs
and initializes their permanence. For each segment, one synapse is added
(although one might be added for each "source"). To add multiple synapses to
a segment, include it in the list multiple times.
The total number of affected synapses is len(segments)*number_of_sources*1.
@param segments (numpy array)
One segment for each synapse that should be added
@param presynapticCellsBySource (dict of numpy arrays)
One presynaptic cell for each segment.
Example:
{"customInputName1": np.array([42, 69])}
@param permanence (float)
The permanence to assign the synapse | [
"Set",
"the",
"permanence",
"of",
"a",
"specific",
"set",
"of",
"synapses",
".",
"Any",
"synapses",
"that",
"don",
"t",
"exist",
"will",
"be",
"initialized",
".",
"Any",
"existing",
"synapses",
"will",
"be",
"overwritten",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/multiconnections.py#L109-L137 | train | 198,993 |
numenta/htmresearch | projects/thalamus/run_experiment.py | loadImage | def loadImage(t, filename="cajal.jpg"):
"""
Load the given gray scale image. Threshold it to black and white and crop it
to be the dimensions of the FF input for the thalamus. Return a binary numpy
matrix where 1 corresponds to black, and 0 corresponds to white.
"""
image = Image.open("cajal.jpg").convert("1")
image.load()
box = (0, 0, t.inputWidth, t.inputHeight)
image = image.crop(box)
# Here a will be a binary numpy array where True is white. Convert to floating
# point numpy array where white is 0.0
a = np.asarray(image)
im = np.ones((t.inputWidth, t.inputHeight))
im[a] = 0
return im | python | def loadImage(t, filename="cajal.jpg"):
"""
Load the given gray scale image. Threshold it to black and white and crop it
to be the dimensions of the FF input for the thalamus. Return a binary numpy
matrix where 1 corresponds to black, and 0 corresponds to white.
"""
image = Image.open("cajal.jpg").convert("1")
image.load()
box = (0, 0, t.inputWidth, t.inputHeight)
image = image.crop(box)
# Here a will be a binary numpy array where True is white. Convert to floating
# point numpy array where white is 0.0
a = np.asarray(image)
im = np.ones((t.inputWidth, t.inputHeight))
im[a] = 0
return im | [
"def",
"loadImage",
"(",
"t",
",",
"filename",
"=",
"\"cajal.jpg\"",
")",
":",
"image",
"=",
"Image",
".",
"open",
"(",
"\"cajal.jpg\"",
")",
".",
"convert",
"(",
"\"1\"",
")",
"image",
".",
"load",
"(",
")",
"box",
"=",
"(",
"0",
",",
"0",
",",
... | Load the given gray scale image. Threshold it to black and white and crop it
to be the dimensions of the FF input for the thalamus. Return a binary numpy
matrix where 1 corresponds to black, and 0 corresponds to white. | [
"Load",
"the",
"given",
"gray",
"scale",
"image",
".",
"Threshold",
"it",
"to",
"black",
"and",
"white",
"and",
"crop",
"it",
"to",
"be",
"the",
"dimensions",
"of",
"the",
"FF",
"input",
"for",
"the",
"thalamus",
".",
"Return",
"a",
"binary",
"numpy",
... | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/thalamus/run_experiment.py#L54-L71 | train | 198,994 |
numenta/htmresearch | projects/thalamus/run_experiment.py | inferThalamus | def inferThalamus(t, l6Input, ffInput):
"""
Compute the effect of this feed forward input given the specific L6 input.
:param t: instance of Thalamus
:param l6Input:
:param ffInput: a numpy array of 0's and 1's
:return:
"""
print("\n-----------")
t.reset()
t.deInactivateCells(l6Input)
ffOutput = t.computeFeedForwardActivity(ffInput)
# print("L6 input:", l6Input)
# print("Active TRN cells: ", t.activeTRNCellIndices)
# print("Burst ready relay cells: ", t.burstReadyCellIndices)
return ffOutput | python | def inferThalamus(t, l6Input, ffInput):
"""
Compute the effect of this feed forward input given the specific L6 input.
:param t: instance of Thalamus
:param l6Input:
:param ffInput: a numpy array of 0's and 1's
:return:
"""
print("\n-----------")
t.reset()
t.deInactivateCells(l6Input)
ffOutput = t.computeFeedForwardActivity(ffInput)
# print("L6 input:", l6Input)
# print("Active TRN cells: ", t.activeTRNCellIndices)
# print("Burst ready relay cells: ", t.burstReadyCellIndices)
return ffOutput | [
"def",
"inferThalamus",
"(",
"t",
",",
"l6Input",
",",
"ffInput",
")",
":",
"print",
"(",
"\"\\n-----------\"",
")",
"t",
".",
"reset",
"(",
")",
"t",
".",
"deInactivateCells",
"(",
"l6Input",
")",
"ffOutput",
"=",
"t",
".",
"computeFeedForwardActivity",
"... | Compute the effect of this feed forward input given the specific L6 input.
:param t: instance of Thalamus
:param l6Input:
:param ffInput: a numpy array of 0's and 1's
:return: | [
"Compute",
"the",
"effect",
"of",
"this",
"feed",
"forward",
"input",
"given",
"the",
"specific",
"L6",
"input",
"."
] | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/thalamus/run_experiment.py#L84-L100 | train | 198,995 |
numenta/htmresearch | projects/thalamus/run_experiment.py | filtered | def filtered(w=250):
"""
In this example we filter the image into several channels using gabor filters. L6 activity is used to select
one of those channels. Only activity selected by those channels burst.
"""
# prepare filter bank kernels
kernels = []
for theta in range(4):
theta = theta / 4. * np.pi
for sigma in (1, 3):
for frequency in (0.05, 0.25):
kernel = np.real(gabor_kernel(frequency, theta=theta,
sigma_x=sigma, sigma_y=sigma))
kernels.append(kernel)
print("Initializing thalamus")
t = Thalamus(
trnCellShape=(w, w),
relayCellShape=(w, w),
inputShape=(w, w),
l6CellCount=128*128,
trnThreshold=15,
)
ff = loadImage(t)
for i,k in enumerate(kernels):
plotActivity(k, "kernel"+str(i)+".jpg", "Filter kernel", vmax=k.max(),
vmin=k.min())
filtered0 = power(ff, k)
ft = np.zeros((w, w))
ft[filtered0 > filtered0.mean() + filtered0.std()] = 1.0
plotActivity(ft, "filtered"+str(i)+".jpg", "Filtered image", vmax=1.0)
encoder = createLocationEncoder(t, w=17)
trainThalamusLocations(t, encoder)
filtered0 = power(ff, kernels[3])
ft = np.zeros((w, w))
ft[filtered0 > filtered0.mean() + filtered0.std()] = 1.0
# Get a salt and pepper burst ready image
print("Getting unions")
l6Code = list(getUnionLocations(encoder, 125, 125, 150, step=10))
print("Num active cells in L6 union:", len(l6Code),"out of", t.l6CellCount)
ffOutput = inferThalamus(t, l6Code, ft)
plotActivity(t.burstReadyCells, "relay_burstReady_filtered.jpg",
title="Burst-ready cells",
)
plotActivity(ffOutput, "cajal_relay_output_filtered.jpg",
title="Filtered activity",
cmap="Greys")
# Get a more detailed filtered image
print("Getting unions")
l6Code = list(getUnionLocations(encoder, 125, 125, 150, step=3))
print("Num active cells in L6 union:", len(l6Code),"out of", t.l6CellCount)
ffOutput_all = inferThalamus(t, l6Code, ff)
ffOutput_filtered = inferThalamus(t, l6Code, ft)
ffOutput3 = ffOutput_all*0.4 + ffOutput_filtered
plotActivity(t.burstReadyCells, "relay_burstReady_all.jpg",
title="Burst-ready cells",
)
plotActivity(ffOutput3, "cajal_relay_output_filtered2.jpg",
title="Filtered activity",
cmap="Greys") | python | def filtered(w=250):
"""
In this example we filter the image into several channels using gabor filters. L6 activity is used to select
one of those channels. Only activity selected by those channels burst.
"""
# prepare filter bank kernels
kernels = []
for theta in range(4):
theta = theta / 4. * np.pi
for sigma in (1, 3):
for frequency in (0.05, 0.25):
kernel = np.real(gabor_kernel(frequency, theta=theta,
sigma_x=sigma, sigma_y=sigma))
kernels.append(kernel)
print("Initializing thalamus")
t = Thalamus(
trnCellShape=(w, w),
relayCellShape=(w, w),
inputShape=(w, w),
l6CellCount=128*128,
trnThreshold=15,
)
ff = loadImage(t)
for i,k in enumerate(kernels):
plotActivity(k, "kernel"+str(i)+".jpg", "Filter kernel", vmax=k.max(),
vmin=k.min())
filtered0 = power(ff, k)
ft = np.zeros((w, w))
ft[filtered0 > filtered0.mean() + filtered0.std()] = 1.0
plotActivity(ft, "filtered"+str(i)+".jpg", "Filtered image", vmax=1.0)
encoder = createLocationEncoder(t, w=17)
trainThalamusLocations(t, encoder)
filtered0 = power(ff, kernels[3])
ft = np.zeros((w, w))
ft[filtered0 > filtered0.mean() + filtered0.std()] = 1.0
# Get a salt and pepper burst ready image
print("Getting unions")
l6Code = list(getUnionLocations(encoder, 125, 125, 150, step=10))
print("Num active cells in L6 union:", len(l6Code),"out of", t.l6CellCount)
ffOutput = inferThalamus(t, l6Code, ft)
plotActivity(t.burstReadyCells, "relay_burstReady_filtered.jpg",
title="Burst-ready cells",
)
plotActivity(ffOutput, "cajal_relay_output_filtered.jpg",
title="Filtered activity",
cmap="Greys")
# Get a more detailed filtered image
print("Getting unions")
l6Code = list(getUnionLocations(encoder, 125, 125, 150, step=3))
print("Num active cells in L6 union:", len(l6Code),"out of", t.l6CellCount)
ffOutput_all = inferThalamus(t, l6Code, ff)
ffOutput_filtered = inferThalamus(t, l6Code, ft)
ffOutput3 = ffOutput_all*0.4 + ffOutput_filtered
plotActivity(t.burstReadyCells, "relay_burstReady_all.jpg",
title="Burst-ready cells",
)
plotActivity(ffOutput3, "cajal_relay_output_filtered2.jpg",
title="Filtered activity",
cmap="Greys") | [
"def",
"filtered",
"(",
"w",
"=",
"250",
")",
":",
"# prepare filter bank kernels",
"kernels",
"=",
"[",
"]",
"for",
"theta",
"in",
"range",
"(",
"4",
")",
":",
"theta",
"=",
"theta",
"/",
"4.",
"*",
"np",
".",
"pi",
"for",
"sigma",
"in",
"(",
"1",... | In this example we filter the image into several channels using gabor filters. L6 activity is used to select
one of those channels. Only activity selected by those channels burst. | [
"In",
"this",
"example",
"we",
"filter",
"the",
"image",
"into",
"several",
"channels",
"using",
"gabor",
"filters",
".",
"L6",
"activity",
"is",
"used",
"to",
"select",
"one",
"of",
"those",
"channels",
".",
"Only",
"activity",
"selected",
"by",
"those",
... | 70c096b09a577ea0432c3f3bfff4442d4871b7aa | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/thalamus/run_experiment.py#L210-L277 | train | 198,996 |
spotify/snakebite | snakebite/channel.py | get_delimited_message_bytes | def get_delimited_message_bytes(byte_stream, nr=4):
''' Parse a delimited protobuf message. This is done by first getting a protobuf varint from
the stream that represents the length of the message, then reading that amount of
from the message and then parse it.
Since the int can be represented as max 4 bytes, first get 4 bytes and try to decode.
The decoder returns the value and the position where the value was found, so we need
to rewind the buffer to the position, because the remaining bytes belong to the message
after.
'''
(length, pos) = decoder._DecodeVarint32(byte_stream.read(nr), 0)
if log.getEffectiveLevel() == logging.DEBUG:
log.debug("Delimited message length (pos %d): %d" % (pos, length))
delimiter_bytes = nr - pos
byte_stream.rewind(delimiter_bytes)
message_bytes = byte_stream.read(length)
if log.getEffectiveLevel() == logging.DEBUG:
log.debug("Delimited message bytes (%d): %s" % (len(message_bytes), format_bytes(message_bytes)))
total_len = length + pos
return (total_len, message_bytes) | python | def get_delimited_message_bytes(byte_stream, nr=4):
''' Parse a delimited protobuf message. This is done by first getting a protobuf varint from
the stream that represents the length of the message, then reading that amount of
from the message and then parse it.
Since the int can be represented as max 4 bytes, first get 4 bytes and try to decode.
The decoder returns the value and the position where the value was found, so we need
to rewind the buffer to the position, because the remaining bytes belong to the message
after.
'''
(length, pos) = decoder._DecodeVarint32(byte_stream.read(nr), 0)
if log.getEffectiveLevel() == logging.DEBUG:
log.debug("Delimited message length (pos %d): %d" % (pos, length))
delimiter_bytes = nr - pos
byte_stream.rewind(delimiter_bytes)
message_bytes = byte_stream.read(length)
if log.getEffectiveLevel() == logging.DEBUG:
log.debug("Delimited message bytes (%d): %s" % (len(message_bytes), format_bytes(message_bytes)))
total_len = length + pos
return (total_len, message_bytes) | [
"def",
"get_delimited_message_bytes",
"(",
"byte_stream",
",",
"nr",
"=",
"4",
")",
":",
"(",
"length",
",",
"pos",
")",
"=",
"decoder",
".",
"_DecodeVarint32",
"(",
"byte_stream",
".",
"read",
"(",
"nr",
")",
",",
"0",
")",
"if",
"log",
".",
"getEffec... | Parse a delimited protobuf message. This is done by first getting a protobuf varint from
the stream that represents the length of the message, then reading that amount of
from the message and then parse it.
Since the int can be represented as max 4 bytes, first get 4 bytes and try to decode.
The decoder returns the value and the position where the value was found, so we need
to rewind the buffer to the position, because the remaining bytes belong to the message
after. | [
"Parse",
"a",
"delimited",
"protobuf",
"message",
".",
"This",
"is",
"done",
"by",
"first",
"getting",
"a",
"protobuf",
"varint",
"from",
"the",
"stream",
"that",
"represents",
"the",
"length",
"of",
"the",
"message",
"then",
"reading",
"that",
"amount",
"of... | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/channel.py#L86-L108 | train | 198,997 |
spotify/snakebite | snakebite/channel.py | RpcBufferedReader.read | def read(self, n):
'''Reads n bytes into the internal buffer'''
bytes_wanted = n - self.buffer_length + self.pos + 1
if bytes_wanted > 0:
self._buffer_bytes(bytes_wanted)
end_pos = self.pos + n
ret = self.buffer[self.pos + 1:end_pos + 1]
self.pos = end_pos
return ret | python | def read(self, n):
'''Reads n bytes into the internal buffer'''
bytes_wanted = n - self.buffer_length + self.pos + 1
if bytes_wanted > 0:
self._buffer_bytes(bytes_wanted)
end_pos = self.pos + n
ret = self.buffer[self.pos + 1:end_pos + 1]
self.pos = end_pos
return ret | [
"def",
"read",
"(",
"self",
",",
"n",
")",
":",
"bytes_wanted",
"=",
"n",
"-",
"self",
".",
"buffer_length",
"+",
"self",
".",
"pos",
"+",
"1",
"if",
"bytes_wanted",
">",
"0",
":",
"self",
".",
"_buffer_bytes",
"(",
"bytes_wanted",
")",
"end_pos",
"=... | Reads n bytes into the internal buffer | [
"Reads",
"n",
"bytes",
"into",
"the",
"internal",
"buffer"
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/channel.py#L121-L130 | train | 198,998 |
spotify/snakebite | snakebite/channel.py | RpcBufferedReader.rewind | def rewind(self, places):
'''Rewinds the current buffer to a position. Needed for reading varints,
because we might read bytes that belong to the stream after the varint.
'''
log.debug("Rewinding pos %d with %d places" % (self.pos, places))
self.pos -= places
log.debug("Reset buffer to pos %d" % self.pos) | python | def rewind(self, places):
'''Rewinds the current buffer to a position. Needed for reading varints,
because we might read bytes that belong to the stream after the varint.
'''
log.debug("Rewinding pos %d with %d places" % (self.pos, places))
self.pos -= places
log.debug("Reset buffer to pos %d" % self.pos) | [
"def",
"rewind",
"(",
"self",
",",
"places",
")",
":",
"log",
".",
"debug",
"(",
"\"Rewinding pos %d with %d places\"",
"%",
"(",
"self",
".",
"pos",
",",
"places",
")",
")",
"self",
".",
"pos",
"-=",
"places",
"log",
".",
"debug",
"(",
"\"Reset buffer t... | Rewinds the current buffer to a position. Needed for reading varints,
because we might read bytes that belong to the stream after the varint. | [
"Rewinds",
"the",
"current",
"buffer",
"to",
"a",
"position",
".",
"Needed",
"for",
"reading",
"varints",
"because",
"we",
"might",
"read",
"bytes",
"that",
"belong",
"to",
"the",
"stream",
"after",
"the",
"varint",
"."
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/channel.py#L146-L152 | train | 198,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.