code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
print("\n================",expName,"=====================")
try:
# Retrieve the last totalCorrect from each experiment
# Print them sorted from best to worst
values, params = suite.get_values_fix_params(
expName, 0, "totalCorrect", "last")
v = np.array(values)
sortedIndices = v.argsort... | def summarizeResults(expName, suite) | Summarize the totalCorrect value from the last iteration for each experiment
in the directory tree. | 3.271473 | 3.095593 | 1.056816 |
print("\nLEARNING CURVE ================",expPath,"=====================")
try:
headers=["testerror","totalCorrect","elapsedTime","entropy"]
result = suite.get_value(expPath, 0, headers, "all")
info = []
for i,v in enumerate(zip(result["testerror"],result["totalCorrect"],
... | def learningCurve(expPath, suite) | Print the test and overall noise errors from each iteration of this experiment | 5.13275 | 5.02278 | 1.021894 |
spec = {
"description": CoordinateSensorRegion.__doc__,
"singleNodeOnly": True,
"inputs": {}, # input data is added to queue via "addDataToQueue" command
"outputs": {
"dataOut": {
"description": "Encoded coordinate SDR.",
"dataType": "Real32",
"cou... | def getSpec(cls) | Return base spec for this region. See base class method for more info. | 3.33766 | 3.248104 | 1.027572 |
if len(self.queue) > 0:
data = self.queue.pop()
else:
raise Exception("CoordinateSensor: No data to encode: queue is empty")
outputs["resetOut"][0] = data["reset"]
outputs["sequenceIdOut"][0] = data["sequenceId"]
sdr = self.encoder.encode((numpy.array(data["coordinate"]), self.rad... | def compute(self, inputs, outputs) | Get the next record from the queue and encode it.
@param inputs This parameter is ignored. The data comes from the queue
@param outputs See definition in the spec above. | 5.432949 | 5.1651 | 1.051857 |
if type(coordinate) == type(""):
coordinateList = eval(coordinate)
elif type(coordinate) == type([]):
coordinateList = coordinate
else:
raise Exception("CoordinateSensor.addDataToQueue: unknown type for "
"coordinate")
self.queue.appendleft({
"sequence... | def addDataToQueue(self, coordinate, reset, sequenceId) | Add the given data item to the sensor's internal queue. Calls to compute
will cause items in the queue to be dequeued in FIFO order.
@param coordinate A list containing the N-dimensional integer coordinate
space to be encoded. This list can be specified in two
ways, ... | 3.998008 | 3.718592 | 1.07514 |
print "Experiment start time:", time.ctime()
print "\nExperiment arguments:"
pprint.pprint(args)
r = sequences.objectConfusion()
print "Average common pairs in sequences=", r[0],
print ", features=",r[2]
r = objects.objectConfusion()
print "Average common pairs in objects=", r[0],
print ", locati... | def printDiagnostics(exp, sequences, objects, args, verbosity=0) | Useful diagnostics for debugging. | 4.967494 | 4.852389 | 1.023721 |
if len(kwargs) == 0: return [{}]
kargs = deepcopy(kwargs)
k1 = kargs.keys()[0]
values = kargs.pop(k1)
args = []
# Get all other combinations
otherArgs = createArgs(**kargs)
# Create combinations for values associated with k1
for v in values:
newArgs = deepcopy(otherArgs)
arg = {k1: v}
... | def createArgs(**kwargs) | Each kwarg is a list. Return a list of dicts representing all possible
combinations of the kwargs. | 3.674079 | 3.093208 | 1.187789 |
randomizedSequence = []
sparseCols = int(numColumns * sparsity)
numSymbolsToChange = int(symbolsPerSequence * p)
symIndices = np.random.permutation(np.arange(symbolsPerSequence))
for symbol in range(symbolsPerSequence):
randomizedSequence.append(sequence[symbol])
i = 0
while numSymbolsToChange > ... | def randomizeSequence(sequence, symbolsPerSequence, numColumns, sparsity, p = 0.25) | Takes a sequence as input and randomizes a percentage p of it by choosing
SDRs at random while preserving the remaining invariant.
@param sequence (array) sequence to be randomized
@param symbolsPerSequence (int) number of symbols per sequence
@param numColumns (int) number of columns in the TM
@param spar... | 2.743187 | 3.058787 | 0.896822 |
sequenceHO = []
sparseCols = int(numColumns * sparsity)
for symbol in range(symbolsPerSequence):
if symbol == 0 or symbol == (symbolsPerSequence - 1):
sequenceHO.append(generateRandomSymbol(numColumns, sparseCols))
else:
sequenceHO.append(sequence[symbol])
return sequenceHO | def generateHOSequence(sequence, symbolsPerSequence, numColumns, sparsity) | Generates a high-order sequence by taking an initial sequence and the changing
its first and last SDRs by random SDRs
@param sequence (array) sequence to be randomized
@param symbolsPerSequence (int) number of symbols per sequence
@param numColumns (int) number of columns in the TM
@param sparsity (float) ... | 2.955513 | 3.485326 | 0.847988 |
nonZeroX1 = np.count_nonzero(x1)
nonZeroX2 = np.count_nonzero(x2)
sparseCols = min(nonZeroX1, nonZeroX2)
# transform input vector specifying columns into binary vector
binX1 = np.zeros(numColumns, dtype="uint32")
binX2 = np.zeros(numColumns, dtype="uint32")
for i in range(sparseCols):
binX1[x1[... | def percentOverlap(x1, x2, numColumns) | Calculates the percentage of overlap between two SDRs
@param x1 (array) SDR
@param x2 (array) SDR
@return percentageOverlap (float) percentage overlap between x1 and x2 | 2.696817 | 2.834366 | 0.951471 |
symbol = list()
remainingCols = sparseCols
while remainingCols > 0:
col = random.randrange(numColumns)
if col not in symbol:
symbol.append(col)
remainingCols -= 1
return symbol | def generateRandomSymbol(numColumns, sparseCols) | Generates a random SDR with sparseCols number of active columns
@param numColumns (int) number of columns in the temporal memory
@param sparseCols (int) number of sparse columns for desired SDR
@return symbol (list) SDR | 2.848342 | 2.989523 | 0.952775 |
sequence = []
sparseCols = int(numColumns * sparsity)
for _ in range(numSymbols):
sequence.append(generateRandomSymbol(numColumns, sparseCols))
return sequence | def generateRandomSequence(numSymbols, numColumns, sparsity) | Generate a random sequence comprising numSymbols SDRs
@param numSymbols (int) number of SDRs in random sequence
@param numColumns (int) number of columns in the temporal memory
@param sparsity (float) percentage of sparsity (real number between 0 and 1)
@return sequence (array) random sequence generated | 3.477093 | 4.357537 | 0.797949 |
numCells = np.shape(spikeTrains)[0]
corrMatrix = np.zeros((numCells, numCells))
numNegPCC = 0
for i in range(numCells):
for j in range(numCells):
if i == j and removeAutoCorr == True:
continue
if not all(spikeTrains[i,:] == 0) and not all(spikeTrains[j,:] == 0):
corrMatrix[i,j... | def computePWCorrelations(spikeTrains, removeAutoCorr) | Computes pairwise correlations from spikeTrains
@param spikeTrains (array) spike trains obtained from the activation of cells in the TM
the array dimensions are: numCells x timeSteps
@param removeAutoCorr (boolean) if true, auto-correlations are removed by substracting
the diagonal of the corre... | 1.989895 | 1.723448 | 1.154601 |
acc = 0
if np.count_nonzero(predicted) > 0:
acc = float(np.dot(current, predicted))/float(np.count_nonzero(predicted))
return acc | def accuracy(current, predicted) | Computes the accuracy of the TM at time-step t based on the prediction
at time-step t-1 and the current active columns at time-step t.
@param current (array) binary vector containing current active columns
@param predicted (array) binary vector containing predicted active columns
@return acc (float) predic... | 3.024462 | 3.13628 | 0.964347 |
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) | Generate indices of cell pairs, each pair of cells are from the same column
@return cellPairs (list) list of cell pairs | 2.46819 | 2.467911 | 1.000113 |
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[... | 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 | 1.967697 | 1.978942 | 0.994318 |
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:
subS... | 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
... | 2.07812 | 2.083643 | 0.997349 |
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
... | 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 ... | 1.731835 | 1.728589 | 1.001878 |
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) | Estimates entropy in spike trains.
@param spikeTrains (array) matrix of spike trains
@return entropy (float) entropy | 2.367945 | 2.685709 | 0.881683 |
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(zero... | 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 algo... | 2.732227 | 2.755779 | 0.991453 |
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) | 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) | 4.292214 | 4.505089 | 0.952748 |
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') | 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 | 2.94169 | 2.974257 | 0.989051 |
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) | 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) | 3.090091 | 3.408867 | 0.906486 |
count = 0
timeSteps = np.shape(spikeTrain)[1]
for i in range(timeSteps):
if np.dot(binaryWord, spikeTrain[:,i]) == np.count_nonzero(binaryWord):
count += 1
#print i
return count | def countInSample(binaryWord, spikeTrain) | Counts the times in which a binary pattern (e.g. [1 0 0 1 1 0 1]) occurs in a spike train
@param binaryWord (array) binary vector to be search within the spike train matrix.
@param spikeTrain (array) matrix of spike trains. Dimensions of binary word are 1xN, whereas
dimensions of spikeTrain must be Nxti... | 3.137238 | 2.955459 | 1.061506 |
# 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) | Saves the temporal memory and the sequences generated for its training.
@param tm (TemporalMemory) temporal memory used during the experiment | 6.742051 | 6.980162 | 0.965887 |
records = np.shape(allSequences)[0]
symbols = np.shape(allSequences)[1]
totalItems = records * symbols
overlapMatrix = np.zeros((totalItems, totalItems))
for i in range(totalItems):
if i % 500 == 0:
print str(i) + " rows processed"
for j in range(totalItems):
if model == "random":... | def inputAnalysis(allSequences, model, numColumns) | Calculates the overlap score of each SDR used as input to the temporal memory. Generates
an overlap matrix with entries (i,j) = overlapScore(i, j)
@param allSequences (array) sequences using during the experiment
@param model (string) string specifying whether the experiment used random or
periodic dat... | 3.037686 | 2.834928 | 1.071521 |
numCells = np.shape(spikeTrains)[0]
numCols = numCells / cellsPerColumn
corrMatrix = np.zeros((numCells, numCells))
numNegPCC = 0
indices = np.zeros(cellsPerColumn, dtype="uint32")
for col in range(numCols):
for k in range(cellsPerColumn):
indices[k] = (cellsPerColumn * col) + k
for i in... | def computePWCorrelationsWithinCol(spikeTrains, removeAutoCorr, cellsPerColumn) | Computes pairwise correlations from spikeTrains
@param spikeTrains (array) spike trains obtained from the activation of cells in the TM
the array dimensions are: numCells x timeSteps
@param removeAutoCorr (boolean) if true, auto-correlations are removed by substracting
the diagonal of the correlation m... | 2.357869 | 2.082269 | 1.132356 |
try:
with open(csvFile, "rU") as f:
reader = csv.reader(f)
headers = next(reader, None)
try:
sampleIdx = headers.index("Sample")
idIdx = headers.index("ID")
except ValueError as e:
print ("Could not find 'ID' and/or 'Sample' columns, so assuming "
... | def readCSV(csvFile, numLabels=0) | Read in a CSV file w/ the following formatting:
- one header row
- one page
- one column of samples, followed by column(s) of labels
@param csvFile (str) File name for the input CSV.
@param numLabels (int) Number of columns of category labels.
@return (d... | 2.490562 | 2.437698 | 1.021686 |
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) | 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) | 3.292845 | 3.535827 | 0.93128 |
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
... | def bucketCSVs(csvFile, bucketIdx=2) | Write the individual buckets in csvFile to their own CSV files. | 2.604764 | 2.565182 | 1.01543 |
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", "/"... | 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 name... | 3.100689 | 2.465651 | 1.257554 |
with open(csvFile, "wb") as f:
writer = csv.writer(f, delimiter=",")
writer.writerow(headers)
writer.writerows(data) | def writeCSV(data, headers, csvFile) | Write data with column headers to a CSV. | 2.036836 | 2.015669 | 1.010501 |
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) | Write dictionary to a CSV, where keys are row numbers and values are a list. | 2.157141 | 2.013974 | 1.071087 |
# 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:
categories... | 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
... | 3.121471 | 2.770821 | 1.126551 |
if modelName not in TemporalMemoryTypes.getTypes():
raise RuntimeError("Unknown model type: " + modelName)
return getattr(TemporalMemoryTypes, modelName)(**kwargs) | 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. Keyw... | 6.36781 | 4.650063 | 1.369403 |
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) | 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
... | 5.594385 | 4.071192 | 1.374139 |
for attrName in dir(cls):
attrValue = getattr(cls, attrName)
if (isinstance(attrValue, type)):
yield attrName | 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. | 3.864788 | 3.517528 | 1.098723 |
# 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 synap... | def initialize_dendrites(self) | Initialize all the dendrites of the neuron to a set of random connections | 4.616621 | 4.596806 | 1.004311 |
activations = datapoint * self.dendrites
activations = self.nonlinearity(activations)
return activations.sum() | def calculate_activation(self, datapoint) | Only for a single datapoint | 7.824142 | 6.558383 | 1.192999 |
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:
pr... | 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... | 3.121948 | 2.95628 | 1.056039 |
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 = activat... | 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. | 2.58979 | 2.505064 | 1.033822 |
baseClassList = list(_getPoolerClass(name).__bases__)
spatialPoolerParent = None
while len(baseClassList) > 0 and spatialPoolerParent is None:
v = baseClassList.pop()
if v.__name__ is "SpatialPooler":
spatialPoolerParent = v
if v.__name__ is not 'object':
baseClassList... | def _getParentSpatialPoolerClass(name) | Find the spatial pooler in the parent classes
:param name: pooler class name as in _getPoolerClass
:return: the parent spatial pooler class | 3.342886 | 3.112011 | 1.074189 |
typeNames = {int: "UInt32", float: "Real32", str: "Byte", bool: "bool",
tuple: "tuple"}
def getArgType(arg):
t = typeNames.get(type(arg), "Byte")
count = 0 if t == "Byte" else 1
if t == "tuple":
t = typeNames.get(type(arg[0]), "Byte")
count = len(arg)
if t == "bool":
... | def _getAdditionalSpecs(poolerClass=_getDefaultPoolerClass(), poolerType="union") | Build the additional specs in three groups (for the inspector)
Use the type of the default argument to set the Spec type, defaulting
to "Byte" for None and complex types
Determines the pooler parameters based on the selected implementation. | 3.245202 | 3.229183 | 1.004961 |
# 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
... | def initialize(self) | Initialize the self._poolerClass | 7.148076 | 5.800511 | 1.232318 |
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,... | 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... | 6.337267 | 6.050133 | 1.047459 |
spec = dict(
description=TemporalPoolerRegion.__doc__,
singleNodeOnly=True,
inputs=dict(
activeCells=dict(
description="Active cells",
dataType="Real32",
count=0,
required=True,
regionLevel=False,
isDefaultInput=True,
... | def getBaseSpec(cls) | Return the base Spec for TemporalPoolerRegion.
Doesn't include the pooler parameters | 4.266891 | 4.006312 | 1.065042 |
spec = cls.getBaseSpec()
p, o = _getAdditionalSpecs()
spec["parameters"].update(p)
spec["parameters"].update(o)
return spec | 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) | 8.920658 | 8.728035 | 1.022069 |
if parameterName in self._poolerArgNames:
setattr(self._pooler, parameterName, parameterValue)
elif hasattr(self, parameterName):
setattr(self, parameterName, parameterValue)
else:
raise Exception("Unknown parameter: " + parameterName) | def setParameter(self, parameterName, index, parameterValue) | Set the value of a Spec parameter. Most parameters are handled
automatically by PyRegion's parameter set mechanism. The ones that need
special treatment are explicitly handled here. | 3.585198 | 3.480307 | 1.030139 |
trainSeqN = [5, 10, 20, 50, 100, 200]
rptPerCondition = 20
correctRateAll = np.zeros((len(trainSeqN), rptPerCondition))
missRateAll = np.zeros((len(trainSeqN), rptPerCondition))
fpRateAll = np.zeros((len(trainSeqN), rptPerCondition))
for i in xrange(len(trainSeqN)):
for rpt in xrange(rptPerCondition)... | def runExperiment() | Experiment 1: Calculate error rate as a function of training sequence numbers
:return: | 2.203368 | 2.175409 | 1.012852 |
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:
closestBel... | def computeCapacity(results, threshold) | Returns largest number of objects with accuracy above threshold. | 4.195881 | 3.751403 | 1.118483 |
exp = rerunExperimentFromLogfile(logFile)
exp.logCalls = False
L2Representations = exp.objectL2Representations
print "Learned object representations:"
pprint.pprint(L2Representations, width=400)
print "=========================="
print "\nRun inference with a point on the capsule"
sensationList = ... | def debugExperiment(logFile) | Debug a thing experiment given a logFile | 1.887737 | 1.88338 | 1.002313 |
self.activeCells = np.empty(0, dtype="uint32")
self.activeDeltaSegments = np.empty(0, dtype="uint32")
self.activeFeatureLocationSegments = np.empty(0, dtype="uint32") | def reset(self) | Deactivate all cells. | 5.759785 | 4.600377 | 1.252025 |
prevActiveCells = self.activeCells
self.activeDeltaSegments = np.where(
(self.internalConnections.computeActivity(
prevActiveCells, self.connectedPermanence
) >= self.activationThreshold)
&
(self.deltaConnections.computeActivity(
deltaLocation, self.connectedPermane... | 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) | 3.557508 | 3.61012 | 0.985427 |
prevLocationPotentialOverlaps = self.internalConnections.computeActivity(
prevActiveCells)
deltaPotentialOverlaps = self.deltaConnections.computeActivity(
deltaLocation)
matchingDeltaSegments = np.where(
(prevLocationPotentialOverlaps >= self.learningThreshold) &
(deltaPotenti... | def _learnTransition(self, prevActiveCells, deltaLocation, newLocation) | For each cell in the newLocation SDR, learn the transition of prevLocation
(i.e. prevActiveCells) + deltaLocation.
The transition might be already known. In that case, just reinforce the
existing segments. | 2.970922 | 2.867428 | 1.036093 |
potentialOverlaps = self.featureLocationConnections.computeActivity(
featureLocationInput)
matchingSegments = np.where(potentialOverlaps > self.learningThreshold)[0]
# Cells with a active segment pair: reinforce the segment
cellsForActiveSegments = self.featureLocationConnections.mapSegment... | def _learnFeatureLocationPair(self, newLocation, featureLocationInput,
featureLocationGrowthCandidates) | Grow / reinforce synapses between the location layer's dendrites and the
input layer's active cells. | 4.038224 | 3.862497 | 1.045496 |
# self.net = buildNetwork(params['encoding_num'] * params['num_lags'],
# params['num_cells'],
# params['encoding_num'],
# bias=True,
# outputbias=True)
ds = SupervisedDataSet(params['encoding_nu... | def train(self, params) | Train TDNN network on buffered dataset history
:param params:
:return: | 3.168297 | 3.115073 | 1.017086 |
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.ancho... | def initialize(self) | Initialize grid cell modules | 4.574269 | 4.375653 | 1.045391 |
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["sensoryAs... | 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 :met... | 3.52528 | 3.001014 | 1.174696 |
spec = self.getSpec()
if parameterName not in spec['parameters']:
raise Exception("Unknown parameter: " + parameterName)
setattr(self, parameterName, parameterValue) | def setParameter(self, parameterName, index, parameterValue) | Set the value of a Spec parameter. | 4.959818 | 3.987613 | 1.243806 |
if name in ["activeCells", "learnableCells", "sensoryAssociatedCells"]:
return self.cellCount * self.moduleCount
else:
raise Exception("Invalid output name specified: " + name) | def getOutputElementCount(self, name) | Returns the size of the output array | 13.496937 | 13.495988 | 1.00007 |
if dimensions < 3:
raise ValueError("dimensions value must be 3 or higher")
b1 = np.random.multivariate_normal(mean=np.zeros(dimensions),
cov=np.eye(dimensions))
b1 /= np.linalg.norm(b1)
# Choose a random vector orthogonal to b1
while True:
r... | def createProjectionMatrix(self, dimensions=3) | Compute projection matrix used to convert n-dimensional displacement into
2D displacement compatible with :class:`ThresholdedGaussian2DLocationModule`
algorithm. To compute the 2D displacement each module must multiply the
n-dimensional displacement with the projection matrix for that module.
:param d... | 3.415979 | 3.23186 | 1.05697 |
oldPotentialRadius = sp._potentialRadius
sp._potentialRadius = newPotentialRadius
numColumns = np.prod(sp.getColumnDimensions())
for columnIndex in xrange(numColumns):
potential = sp._mapPotential(columnIndex)
sp._potentialPools.replace(columnIndex, potential.nonzero()[0])
sp._updateInhibitionRadi... | def updatePotentialRadius(sp, newPotentialRadius) | Change the potential radius for all columns
:return: | 8.041127 | 7.651899 | 1.050867 |
bumpSigma = RAT_BUMP_SIGMA * (baselineCellsPerAxis / float(cellsPerAxis))
activeFiringRate = ThresholdedGaussian2DLocationModule.chooseReliableActiveFiringRate(
cellsPerAxis, bumpSigma)
return {
"cellsPerAxis": cellsPerAxis,
"bumpSigma": bumpSigma,
"activeFiringRate": activeFiringRate
} | def computeRatModuleParametersFromCellCount(cellsPerAxis,
baselineCellsPerAxis=6) | Compute 'cellsPerAxis', 'bumpSigma', and 'activeFiringRate' parameters for
:class:`ThresholdedGaussian2DLocationModule` given the number of cells per
axis. See :func:`createRatModuleFromCellCount` | 6.806311 | 3.698681 | 1.840199 |
# Give the module enough precision in its learning so that the bump is the
# specified diameter when properly accounting for uncertainty.
cellsPerAxis = int(math.ceil(2*inverseReadoutResolution*enlargeModuleFactor))
bumpSigma = RAT_BUMP_SIGMA / enlargeModuleFactor
readoutResolution = 1. / (enlargeModuleF... | def computeRatModuleParametersFromReadoutResolution(inverseReadoutResolution,
enlargeModuleFactor=1.) | Compute 'cellsPerAxis', 'bumpSigma', and 'activeFiringRate' parameters for
:class:`ThresholdedGaussian2DLocationModule` given the
inverseReadoutResolution. See :func:`createRatModuleFromReadoutResolution` | 8.460401 | 5.142285 | 1.645261 |
params = computeRatModuleParametersFromReadoutResolution(inverseReadoutResolution,
enlargeModuleFactor)
params.update(kwargs)
params["scale"] = (scale if fixedScale else scale * enlargeModuleFactor)
return ThresholdedGaussian2DLocationModule(**param... | def createRatModuleFromReadoutResolution(inverseReadoutResolution, scale,
enlargeModuleFactor=1.,
fixedScale=False, **kwargs) | @param inverseReadoutResolution (int or float)
Equivalent to 1/readoutResolution, but specified this way as a convenience
(because it's easier and less ambiguous to type 3 than to type 0.3333333). The
readout resolution specifies the diameter of the circle of phases in the
rhombus encoded by a bump. So when a b... | 6.535053 | 7.215208 | 0.905733 |
if noiseFactor != 0:
xdisp = np.random.normal(0, noiseFactor)
ydisp = np.random.normal(0, noiseFactor)
else:
xdisp = 0
ydisp = 0
locationParams = {
"displacement": [displacement["top"] + ydisp,
displacement["left"] + xdisp],
"noiseFactor": mo... | def movementCompute(self, displacement, noiseFactor = 0, moduleNoiseFactor = 0) | @param displacement (dict)
The change in location. Example: {"top": 10, "left", 10}
@return (dict)
Data for logging/tracing. | 3.715934 | 3.44941 | 1.077267 |
inputParams = {
"activeColumns": activeMinicolumns,
"basalInput": self.getLocationRepresentation(),
"basalGrowthCandidates": self.getLearnableLocationRepresentation(),
"learn": learn
}
self.L4.compute(**inputParams)
locationParams = {
"anchorInput": self.L4.getActiveC... | def sensoryCompute(self, activeMinicolumns, learn) | @param activeMinicolumns (numpy array)
List of indices of minicolumns to activate.
@param learn (bool)
If True, the two layers should learn this association.
@return (tuple of dicts)
Data for logging/tracing. | 8.058978 | 8.104897 | 0.994334 |
self.L4.reset()
for module in self.L6aModules:
module.reset() | def reset(self) | Clear all cell activity. | 16.970964 | 16.77667 | 1.011581 |
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) | Get the full population representation of the location layer. | 7.948129 | 7.625209 | 1.042349 |
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) | 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. | 6.427674 | 5.856338 | 1.097559 |
cells = np.array([], dtype="uint32")
totalPrevCells = 0
for module in self.L6aModules:
cells = np.append(cells,
module.sensoryAssociatedCells + totalPrevCells)
totalPrevCells += module.numberOfCells()
return cells | def getSensoryAssociatedLocationRepresentation(self) | Get the location cells in the location layer that were driven by the input
layer (or, during learning, were associated with this input.) | 9.186828 | 8.398054 | 1.093923 |
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(fea... | 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
co... | 5.850544 | 5.466281 | 1.070297 |
self.reset()
for monitor in self.monitors.values():
monitor.beforeInferObject(objectDescription)
currentStep = 0
finished = False
inferred = False
inferredStep = None
prevTouchSequence = None
for _ in xrange(self.maxTraversals):
# Choose touch sequence.
while Tr... | def inferObjectWithRandomMovements(self,
objectDescription,
numSensations=None,
randomLocation=False,
checkFalseConvergence=True) | Attempt to recognize the specified object with the network. Randomly move
the sensor over the object until the object is recognized.
@param objectDescription (dict)
For example:
{"name": "Object 1",
"features": [{"top": 0, "left": 0, "width": 10, "height": 10, "name": "A"},
{"top... | 6.172162 | 6.151537 | 1.003353 |
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["lef... | 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. | 2.987011 | 2.844186 | 1.050217 |
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.getSensoryRepr... | def _sense(self, featureSDR, learn, waitForSettle) | Send the sensory input into the network. Optionally, send it multiple times
until the network settles. | 6.375832 | 6.150877 | 1.036573 |
path, params, minWeight, minDutycycle, position = args
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Dataset transformations used during training. See mnist_sparse_experiment.py
transform = transforms.Compose([transforms.ToTensor(),
transforms.Nor... | def analyzeWeightPruning(args) | Multiprocess function used to analyze the impact of nonzeros and accuracy
after pruning low weights and units with low dutycycle of a pre-trained model.
:param args: tuple with the following arguments:
- experiment path: The experiment results path
- configuration parameters: The p... | 3.812437 | 3.603385 | 1.058015 |
k = tf.convert_to_tensor(k, dtype=tf.int32)
boostStrength = tf.math.maximum(boostStrength, 0.0, name="boostStrength")
targetDensity = tf.cast(k / x.shape[1], tf.float32, name="targetDensity")
boostFactors = tf.exp((targetDensity - dutyCycles) * boostStrength,
name="boostFactors")
b... | def compute_kwinners(x, k, dutyCycles, boostStrength) | Use the boost strength to compute a boost factor for each unit represented
in x. These factors are used to increase the impact of each unit to improve
their chances of being chosen. This encourages participation of more columns
in the learning process.
The boosting function is a curve defined as: boostFactors ... | 3.356236 | 2.977614 | 1.127156 |
activeColumns = self.mmGetTraceActiveColumns()
activeInputs = self.mmGetTraceActiveInputs()
learnTrace = self.mmGetTraceLearn()
initialPermanence = self.mmGetDataInitialPermanence()
(columnNumber, inputSize) = initialPermanence.shape
# potential mask for the column of interest
potenti... | def recoverPermanence(self, columnIndex, verbose=0, getPermTrace=0) | Recover permamnece for a single column
:param columnIndex: index of the column of interest
:return: permInfo (dict) with the following traces over time
avgPermConnectedSyn: mean permanence for connected synapses
avgPermNonConnectedSyn: mean permanence for non-connected synapses
... | 3.901991 | 3.553189 | 1.098166 |
if machineType not in ObjectMachineTypes.getTypes():
raise RuntimeError("Unknown model type: " + machineType)
return getattr(ObjectMachineTypes, machineType)(**kwargs) | 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... | 5.10899 | 4.21262 | 1.212782 |
env = gym.make(name)
env = NoopResetEnv(env, noop_max=30)
env = EpisodicLifeEnv(env)
env = ClipRewardEnv(env)
action_names = env.unwrapped.get_action_meanings()
if 'FIRE' in action_names:
env = FireResetEnv(env)
env = WarpFrame(env)
env = FrameStack(env, k=4)
return env | def create_atari_environment(name) | Create OpenAI Gym atari environment
:param name: name of the atari game
:return: Preconfigured environment suitable for atari games | 1.963888 | 2.064682 | 0.951182 |
self.env.reset(**kwargs)
if self.override_num_noops is not None:
noops = self.override_num_noops
else:
noops = self.unwrapped.np_random.randint(1, self.noop_max + 1) # pylint: disable=E1101
assert noops > 0
obs = None
for _ in range(noops):
obs, _, done, _ = self.env.step... | def reset(self, **kwargs) | Do no-op action for a number of steps in [1, noop_max]. | 1.841013 | 1.580465 | 1.164855 |
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) | Recursively get the current and max entropies from every child module
:param m: any module
:return: (currentEntropy, maxEntropy) | 2.946035 | 2.599423 | 1.133342 |
if isinstance(m, KWinnersBase):
if m.training:
m.boostStrength = m.boostStrength * m.boostStrengthFactor | 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 | 11.826583 | 6.699654 | 1.765253 |
if self.training:
self.boostStrength = self.boostStrength * self.boostStrengthFactor | def updateBoostStrength(self) | Update boost strength using given strength factor during training | 7.177135 | 3.900158 | 1.840217 |
if self.k < self.n:
_, entropy = binaryEntropy(self.dutyCycle)
return entropy
else:
return 0 | def entropy(self) | Returns the current total entropy of this layer | 13.294918 | 13.322733 | 0.997912 |
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 enu... | 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 ... | 2.973324 | 3.021216 | 0.984148 |
if self._tm is None:
params = {
"columnCount": self.columnCount,
"basalInputSize": self.basalInputWidth,
"apicalInputSize": self.apicalInputWidth,
"cellsPerColumn": self.cellsPerColumn,
"activationThreshold": self.activationThreshold,
"initialPermanence": ... | def initialize(self) | Initialize the self._tm if not already initialized. | 3.325527 | 3.184091 | 1.04442 |
# If there's a reset, don't call compute. In some implementations, an empty
# input might cause unwanted effects.
if "resetIn" in inputs:
assert len(inputs["resetIn"]) == 1
if inputs["resetIn"][0] != 0:
# send empty output
self._tm.reset()
outputs["activeCells"][:] ... | def compute(self, inputs, outputs) | Run one iteration of TM's compute. | 2.767468 | 2.645483 | 1.046111 |
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) | Return the number of elements for the given output. | 8.664966 | 8.045087 | 1.077051 |
testDataDir = os.path.join(dataDir, "speech_commands", "test")
outDir = os.path.join(dataDir, "noise_examples")
if not os.path.exists(outDir):
os.mkdir(outDir)
# Create noise dataset with noise transform
noiseTransform = transforms.Compose([
LoadAudio(),
FixAudioLength(),
AddNoise(noise, m... | def save_examples(noise = 0.0, maxVal = 1.0, dataDir="data") | Generate sample noise files for listening and debugging.
:param noise: noise value for the addNoise transform
:param maxVal: maxVal for the addNoise transform
:param dataDir: root dir containing speech_commands directory | 3.299725 | 3.102439 | 1.06359 |
# 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 L... | 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, posi... | 3.140561 | 3.15462 | 0.995543 |
if enableFeedback is False:
self._disableL2()
self.network.regions["L4Column_0"].getSelf()._tm.disableApicalDependence = True
else:
self._enableL2()
self._setLearningMode(l4Learning=False, l2Learning=False)
if sequenceNumber is not None:
if sequenceNumber not in self.objec... | def infer(self, sequence, reset=True, sequenceNumber=None, burnIn=2,
enableFeedback=True, apicalTiebreak=True,
apicalModulationBasalThreshold=True, inertia=True) | Infer on a single given sequence. Sequence format:
sequence = [
set([16, 22, 32]), # Position 0
set([13, 15, 33]) # Position 1
]
Parameters:
----------------------------
@param sequence (list)
Sequence to infer, in the canonical format specified above
@param re... | 3.581328 | 3.557814 | 1.006609 |
for col in xrange(self.numColumns):
self.sensorInputs[col].addResetToQueue(sequenceId)
self.network.run(1) | def sendReset(self, sequenceId=0) | Sends a reset signal to the network. | 13.380331 | 12.311219 | 1.08684 |
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) | Returns the predicted active cells in each column in L4. | 8.269824 | 6.921865 | 1.194739 |
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) | Sets the learning mode for L4 and L2. | 4.74014 | 4.118223 | 1.151016 |
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 "... | def printDiagnosticsAfterTraining(exp, verbosity=0) | Useful diagnostics a trained system for debugging. | 5.060794 | 4.971285 | 1.018005 |
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.provideObje... | def trainSequences(sequences, exp, idOffset=0) | Train the network on all the sequences | 19.272413 | 20.340908 | 0.947471 |
# 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] = o... | 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. | 6.232413 | 5.500597 | 1.133043 |
# Create the (loc, feat) pairs for this sequence for column 0.
objectSensations = {
0: [pair for pair in sequences[sequenceId]]
}
inferConfig = {
"object": sequenceId,
"numSteps": len(objectSensations[0]),
"pairs": objectSensations,
}
inferenceSDRs = sequences.provideObjectToInfer(infer... | def inferSequence(exp, sequenceId, sequences, objectName=0) | Run inference on the given sequence. | 12.062743 | 11.918493 | 1.012103 |
# 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... | def inferObject(exp, objectId, objects, objectName) | Run inference on the given object.
objectName is the name of this object in the experiment. | 7.293925 | 7.092361 | 1.02842 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.