code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
self.ax1.clear() y = self.activations["n"] + self.activations["s"] + self.activations["e"] + \ self.activations["w"] self.ax1.matshow(y.reshape(self.dimensions)) self.ax2.clear() self.ax2.matshow(self.activationsI.reshape(self.dimensions)) self.ax3.clear() self.ax3.matshow(sel...
def plotActivation(self, position=None, time=None, velocity=None)
Plot the activation of the current cell populations. Assumes that two axes have already been created, ax1 and ax2. If done in a Jupyter notebook, this plotting will overwrite the old plot. :param position: The current location of the animal :param time: The current time in the simulation :param ve...
2.406668
2.449236
0.98262
if clearBuffer: while len(self.activationBuffer) > 1: baseI, baseE, baseP, t = self.activationBuffer.popleft() for (I, E, P, i) in self.activationBuffer: t = (i - t) * self.dt self.sdtpKernels(t, I, E, baseI, baseE, baseP, onlyPlace=onlyPlace) else: for I, E...
def stdpUpdate(self, time, clearBuffer=False, onlyPlace=False)
Adds the current activations to the tracking queue, and then performs an STDP update if possible. :param time: The current time. Must be provided. :param clearBuffer: Set as True to clear the activation buffer. This should be done at the end of training. :param onlyPlace: Only learn place c...
2.813229
2.786713
1.009515
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) mnist1 = datasets.MNIST('data', train=False, download=True, transform=transform) data1 = zip(mnist1.test_data, mnist1.test_labels) # Randomize second dataset mnist2 = data...
def create_union_mnist_dataset()
Create a UnionDataset composed of two versions of the MNIST datasets where each item in the dataset contains 2 distinct images superimposed
2.591583
2.531492
1.023737
res = torch.eq(target.sort(dim=1)[0], pred.sort(dim=1)[0]) return res.prod(dim=1)
def exact_match(pred, target)
Compute "Exact match" metric, also called "Subset accuracy" indicating the number of samples that have all their labels classified correctly. See https://en.wikipedia.org/wiki/Multi-label_classification :param pred: Predicted labels :param target: Correct labels :return: containing a 1 at the prediction wher...
5.08436
5.343227
0.951552
n = int(noiseLevel * len(pattern)) noised = set(pattern) noised.difference_update(random.sample(noised, n)) for _ in xrange(n): while True: v = random.randint(0, totalNumCells - 1) if v not in pattern and v not in noised: noised.add(v) break return noised
def noisy(pattern, noiseLevel, totalNumCells)
Generate a noisy copy of a pattern. Given number of active bits w = len(pattern), deactivate noiseLevel*w cells, and activate noiseLevel*w other cells. @param pattern (set) A set of active indices @param noiseLevel (float) The percentage of the bits to shuffle @param totalNumCells (int) The number o...
2.906666
3.134804
0.927224
allFeatures = range(featurePoolSize) allLocations = range(locationsPerObject) objects = dict((name, [random.choice(allFeatures) for _ in xrange(locationsPerObject)]) for name in xrange(numObjects)) return objects
def createRandomObjects(numObjects, locationsPerObject, featurePoolSize)
Generate random objects. @param numObjects (int) The number of objects to generate @param locationsPerObject (int) The number of points on each object @param featurePoolSize (int) The number of possible features @return For example, { 0: [0, 1, 2], 1: [0, 2, 1], 2: ...
4.06059
3.699039
1.097742
featureSDR = lambda : set(random.sample(xrange(NUM_L4_COLUMNS), 40)) locationSDR = lambda : set(random.sample(xrange(1024), 40)) featureSDRsByColumn = [defaultdict(featureSDR) for _ in xrange(numColumns)] locationSDRsByColumn = [defaultdict(locationSDR) for _ in xrange(numColumns)] exp = L4L2Experiment(...
def doExperiment(numColumns, objects, l2Overrides, noiseLevels, numInitialTraversals, noisyFeature, noisyLocation)
Touch every point on an object 'numInitialTraversals' times, then evaluate whether it has inferred the object by touching every point once more and checking the number of correctly active and incorrectly active cells. @param numColumns (int) The number of sensors to use @param l2Overrides (dict) Parameter...
4.405107
4.092933
1.076272
noiseLevels = [0.0, 0.30, 0.40, 0.45, 0.50, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90] l2Overrides = {"sampleSizeDistal": 20} columnCounts = [1, 2, 3, 4] results = defaultdict(list) for trial in xrange(1): print "trial", trial objects = createRandomObjects(10, 10, 10) ...
def logCellActivity_noisyFeature_varyNumColumns(name="cellActivity")
Run the experiment, varying the column counts, and save each [# correctly active cells, # incorrectly active cells] pair to a JSON file that can be visualized.
3.698234
3.724731
0.992886
trainSeqN = [5, 10, 20, 50, 100, 200] rptPerCondition = 5 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.457158
2.448406
1.003575
# Create each column numCorticalColumns = networkConfig["numCorticalColumns"] for i in xrange(numCorticalColumns): networkConfigCopy = copy.deepcopy(networkConfig) layerConfig = networkConfigCopy["L2Params"] layerConfig["seed"] = layerConfig.get("seed", 42) + i layerConfig["numOtherCorticalCo...
def createMultipleL4L2Columns(network, networkConfig)
Create a network consisting of multiple columns. Each column contains one L4 and one L2, is identical in structure to the network created by createL4L2Column. In addition all the L2 columns are fully connected to each other through their lateral inputs. Region names have a column number appended as in externa...
4.341575
3.658102
1.186838
numCorticalColumns = networkConfig["numCorticalColumns"] output_lateral_connections = [[] for i in xrange(numCorticalColumns)] input_lateral_connections = [[] for i in xrange(numCorticalColumns)] # If no column positions are provided, create a grid by default. # This is typically what the use...
def createMultipleL4L2ColumnsWithTopology(network, networkConfig)
Create a network consisting of multiple columns. Each column contains one L4 and one L2, is identical in structure to the network created by createL4L2Column. In addition the L2 columns are connected to each other through their lateral inputs, based on the topological information provided. Region names have...
3.710881
3.305936
1.12249
filename = os.path.join(folder, "Combo3_{}.mat".format(area)) contents = sio.loadmat(filename, variable_names=['data'], struct_as_record=False, squeeze_me=True) return contents['data']
def loadExperimentData(folder, area)
Loads the experiment's data from a MATLAB file into a python friendly structure. :param folder: Experiment data folder :param area: Experiament area to load. It should be 'V1' or 'AL' :return: The data as scipy matlab structure with the following fields: :Spiketrain.st: spike timing during stimulus (grati...
4.005826
4.440042
0.902204
contents = sio.loadmat("./data/DataFolderList.mat", variable_names=['DataFolderList'], struct_as_record=False, squeeze_me=True) return contents['DataFolderList']
def getExperimentList()
Get list of folders containing the data of each experiment :return: list of folders
5.556582
5.784918
0.960529
numClasses = storedVectors.shape[0] output = np.zeros((numClasses,)) for i in range(numClasses): output[i] = np.sum(np.minimum(testVector, storedVectors[i, :])) return output
def classifierPredict(testVector, storedVectors)
Return overlap of the testVector with stored representations for each object.
2.736925
2.480496
1.103378
if nCols == 1: return min(s, nPoints) elif nCols < nPoints: q = float(nCols) / nPoints unique = min(int(round(( 1.0 - math.pow(1.0 - q, s)) * nPoints)), nPoints) return unique else: return nPoints
def computeUniquePointsSensed(nCols, nPoints, s)
If a network with nCols columns senses an object s times, how many unique points are actually sensed? The number is generally <= nCols * s because features may be repeated across sensations.
3.848467
3.58784
1.072642
n = len(stats) for i in range(n): if stats[n-i-1] < 1: return n-i # Never differs - converged in one iteration return 1
def locateConvergencePoint(stats)
Walk backwards through stats until you locate the first point that diverges from target overlap values. We need this to handle cases where it might get to target values, diverge, and then get back again. We want the last convergence point.
6.88805
7.099775
0.970179
######################################################################## # # Accumulate all the results per column in a convergence array. # # Convergence[f,o] = how long it took it to converge with f unique features # and o objects. convergence = numpy.zeros((max(featureRange), max(objectRange) + 1))...
def plotConvergenceByObject(results, objectRange, featureRange, numTrials, linestyle='-')
Plots the convergence graph: iterations vs number of objects. Each curve shows the convergence for a given number of unique features.
4.067321
3.852447
1.055776
######################################################################## # # Accumulate all the results per column in a convergence array. # # Convergence[f,c] = how long it took it to converge with f unique features # and c columns. convergence = numpy.zeros((max(featureRange), max(columnRange) + 1))...
def plotConvergenceByColumn(results, columnRange, featureRange, numTrials, lineStype='-')
Plots the convergence graph: iterations vs number of columns. Each curve shows the convergence for a given number of unique features.
4.749694
4.495643
1.056511
# Create the objects featureRange = [5, 10, 20, 30] pointRange = 1 objectRange = [100] numLocations = [10] numPoints = 10 numTrials = 10 columnRange = [1, 2, 3, 4, 5, 6, 7, 8] useLocation = 1 resultsDir = os.path.dirname(os.path.realpath(__file__)) args = [] for c in reversed(columnRange): ...
def run_multiple_column_experiment()
Compare the ideal observer against a multi-column sensorimotor network.
3.30999
3.244156
1.020293
pointRange = 1 numTrials = 10 args = [] resultsDir = os.path.dirname(os.path.realpath(__file__)) for t in range(numTrials): for useLocation in [0, 1]: args.append( {"numObjects": 100, "numLocations": 10, "numFeatures": 10, "numColumns": 1, "trialNum":...
def single_column_accuracy_comparison()
Plot accuracy of the ideal observer (with and without locations) as the number of sensations increases.
3.391981
3.18315
1.065605
with open(logFilename, "wb") as outp: cPickle.dump(callLog, outp)
def save(callLog, logFilename)
Save the call log history into this file. @param logFilename (path) Filename in which to save a pickled version of the call logs.
3.755641
4.493864
0.835726
if minWeight == 0.0: return # Collect all weights weights = [v for k, v in self.named_parameters() if 'weight' in k] for w in weights: # Filter weights above threshold mask = torch.ge(torch.abs(w.data), minWeight) # Zero other weights w.data.mul_(mask.type(torch.float...
def pruneWeights(self, minWeight)
Prune all the weights whose absolute magnitude is less than minWeight :param minWeight: min weight to prune. If zero then no pruning :type minWeight: float
4.14384
4.123974
1.004817
if threshold < 0.0: return # Collect all layers with 'dutyCycle' for m in self.modules(): if m == self: continue if hasattr(m, 'pruneDutycycles'): m.pruneDutycycles(threshold)
def pruneDutycycles(self, threshold=0.0)
Prune all the units with dutycycles whose absolute magnitude is less than the given threshold :param threshold: min threshold to prune. If less than zero then no pruning :type threshold: float
5.446755
5.983229
0.910337
sampleSize = numExternalInputBits + numInputBits activationThreshold = int(max(numExternalInputBits, numInputBits) * .6) minThreshold = activationThreshold return { "columnCount": inputSize, "cellsPerColumn": 16, "learn": True, "learnOnOneCell": False, "initialPermane...
def _getDefaultCombinedL4Params(self, numInputBits, inputSize, numExternalInputBits, externalInputSize, L2CellCount)
Returns a good default set of parameters to use in a combined L4 region.
5.467699
5.364019
1.019329
numCorrect = 0.0 numStats = 0.0 prefix = "L4 PredictedActive" # For each object for stats in self.statistics: # Keep running total of how often the number of predictedActive cells are # in the range. for key in stats.iterkeys(): if prefix in key: for numCel...
def averageSequenceAccuracy(self, minOverlap, maxOverlap)
For each object, decide whether the TM uniquely classified it by checking that the number of predictedActive cells are in an acceptable range.
6.686469
4.943865
1.352478
L4Representations = self.getL4Representations() L4PredictedCells = self.getL4PredictedCells() L4PredictedActiveCells = self.getL4PredictedActiveCells() L2Representation = self.getL2Representations() for i in xrange(self.numColumns): statistics["L4 Representation C" + str(i)].append( ...
def _updateInferenceStats(self, statistics, objectName=None)
Updates the inference statistics. Parameters: ---------------------------- @param statistics (dict) Dictionary in which to write the statistics @param objectName (str) Name of the inferred object, if known. Otherwise, set to None.
2.811539
2.819626
0.997132
if isinstance(k, numbers.Number): return _choose(n, k) else: return np.array([_choose(n, k2) for k2 in k])
def choose(n, k)
Computes "n choose k". This can handle higher values than scipy.special.binom().
3.39155
3.199439
1.060045
k = np.array(distribution.possibleValues) return np.sum(k * distribution.pmf(k))
def getExpectedValue(distribution)
Calculates E[X] where X is a distribution.
9.189995
9.089834
1.011019
# mapping from n -> expected value actualValues = [ getExpectedValue( SampleMinimumDistribution(numSamples, BinomialDistribution(n, p, cache=True))) for n in xrange(nMax + 1)] results = [] n = 0 for desiredValue in desiredValuesSorted: while n + 1 <= nM...
def findBinomialNsWithExpectedSampleMinimum(desiredValuesSorted, p, numSamples, nMax)
For each desired value, find an approximate n for which the sample minimum has a expected value equal to this value. For each value, find an adjacent pair of n values whose expected sample minima are below and above the desired value, respectively, and return a linearly-interpolated n between these two values....
3.462915
3.554909
0.974122
def P(n, numOccurrences): return 1 - SampleMinimumDistribution(numSamples, BinomialDistribution(n, p)).cdf( numOccurrences - 1) results = [] n = 0 for desiredValue in desiredValuesSorted: while n + 1 <= nMax and P(n + 1, desiredValue) < confidence: n += 1 if n + 1 > nMax: ...
def findBinomialNsWithLowerBoundSampleMinimum(confidence, desiredValuesSorted, p, numSamples, nMax)
For each desired value, find an approximate n for which the sample minimum has a probabilistic lower bound equal to this value. For each value, find an adjacent pair of n values whose lower bound sample minima are below and above the desired value, respectively, and return a linearly-interpolated n between the...
3.769078
3.64638
1.033649
# We're choosing a location, checking its feature, and checking how many # *other* occurrences there are of this feature. So we check n - 1 locations. maxNumOtherLocations = maxNumObjects*10 - 1 results = zip(itertools.count(1), findBinomialNsWithExpectedSampleMinimum( iter...
def generateExpectedList(numUniqueFeatures, numLocationsPerObject, maxNumObjects)
Metric: How unique is each object's most unique feature? Calculate the expected number of occurrences of an object's most unique feature.
11.730428
11.028383
1.063658
# We're choosing a location, checking its feature, and checking how many # *other* occurrences there are of this feature. So we check n - 1 locations. maxNumOtherLocations = maxNumObjects*10 - 1 results = zip(itertools.count(1), findBinomialNsWithLowerBoundSampleMinimum( co...
def generateLowerBoundList(confidence, numUniqueFeatures, numLocationsPerObject, maxNumObjects)
Metric: How unique is each object's most unique feature? Calculate the probabilistic lower bound for the number of occurrences of an object's most unique feature. For example, if confidence is 0.8, the tick "3" will be placed at the point where 80% of objects are completely composed of features with 3 or more t...
11.677833
11.156434
1.046735
locs = [loc for label, loc in ticks] labels = [(str(label + 1) if (label + 1 == 2 or (label+1) % 5 == 0) else "") for label, loc in ticks] return locs, labels
def getTotalExpectedOccurrencesTicks_2_5(ticks)
Extract a set of tick locations and labels. The input ticks are assumed to mean "How many *other* occurrences are there of the sensed feature?" but we want to show how many *total* occurrences there are. So we add 1. We label tick 2, and then 5, 10, 15, 20, ... @param ticks A list of ticks, typically calcul...
6.558576
5.758093
1.139019
if self.apicalIntersect.any(): tempoFactor = tempoFactor * 0.5 else: tempoFactor = tempoFactor * 2 return tempoFactor
def tempoAdjust1(self, tempoFactor)
Adjust tempo based on recent active apical input only :param tempoFactor: scaling signal to MC clock from last sequence item :return: adjusted scaling signal
10.085156
7.710585
1.307963
late_votes = (len(self.adtm.getNextBasalPredictedCells()) - len(self.apicalIntersect)) * -1 early_votes = len(self.apicalIntersect) votes = late_votes + early_votes print('vote tally', votes) if votes > 0: tempoFactor = tempoFactor * 0.5 print 'speed up' elif votes < 0: ...
def tempoAdjust2(self, tempoFactor)
Adjust tempo by aggregating active basal cell votes for pre vs. post :param tempoFactor: scaling signal to MC clock from last sequence item :return: adjusted scaling signal
4.793634
4.35636
1.100376
late_votes = (len(self.adtm.getNextBasalPredictedCells()) - len(self.apicalIntersect)) * -1 early_votes = len(self.apicalIntersect) votes = late_votes + early_votes print('vote tally', votes) if votes > 0: tempoFactor = tempoFactor * 0.5 self.prevVote = 0.5 print 'speed up' ...
def tempoAdjust3(self, tempoFactor)
Adjust tempo by aggregating active basal cell votes for pre vs. post (like tempoAdjust2) -> if vote total = 0 (tied), use result of last vote :param tempoFactor: scaling signal to MC clock from last sequence item :return: adjusted scaling signal
4.120174
3.744555
1.100311
late_votes = (len(self.adtm.getNextBasalPredictedCells()) - len(self.apicalIntersect)) * -1 early_votes = len(self.apicalIntersect) votes = late_votes + early_votes print('vote tally', votes) if votes > 0: newScale = 0.5 print 'speed up' elif votes < 0: newScale = 2 ...
def tempoAdjust4(self, tempoFactor)
Adjust tempo by aggregating active basal cell votes for pre vs. post -> if vote total = 0 (tied), use result of last vote -> if two wrong scale decisions in a row, use max/min tempo in opposite direction :param tempoFactor: scaling signal to MC clock from last sequence item :return: adjusted scaling si...
4.747631
4.341558
1.093532
array = numpy.empty(k, dtype="uint32") rng.sample(numpy.arange(start, end, step, dtype="uint32"), array) return array
def _sampleRange(rng, start, end, step, k)
Equivalent to: random.sample(xrange(start, end, step), k) except it uses our random number generator. This wouldn't need to create the arange if it were implemented in C.
3.903696
4.068387
0.959519
selected = numpy.empty(k, dtype="uint32") rng.sample(numpy.asarray(arr, dtype="uint32"), selected) return selected
def _sample(rng, arr, k)
Equivalent to: random.sample(arr, k) except it uses our random number generator.
7.911719
6.501667
1.216876
return sum(sparseMatrix.countWhereGreaterOrEqual(row, row+1, 0, sparseMatrix.nCols(), threshold) for row in rows)
def _countWhereGreaterEqualInRows(sparseMatrix, rows, threshold)
Like countWhereGreaterOrEqual, but for an arbitrary selection of rows, and without any column filtering.
8.893586
8.415049
1.056867
if feedforwardGrowthCandidates is None: feedforwardGrowthCandidates = feedforwardInput # inference step if not learn: self._computeInferenceMode(feedforwardInput, lateralInputs) # learning step elif not self.onlineLearning: self._computeLearningMode(feedforwardInput, latera...
def compute(self, feedforwardInput=(), lateralInputs=(), feedforwardGrowthCandidates=None, learn=True, predictedInput = None,)
Runs one time step of the column pooler algorithm. @param feedforwardInput (sequence) Sorted indices of active feedforward input bits @param lateralInputs (list of sequences) For each lateral layer, a list of sorted indices of active lateral input bits @param feedfo...
3.561871
3.272141
1.088544
prevActiveCells = self.activeCells # If there are not enough previously active cells, then we are no longer on # a familiar object. Either our representation decayed due to the passage # of time (i.e. we moved somewhere else) or we were mistaken. Either way, # create a new SDR and learn on i...
def _computeLearningMode(self, feedforwardInput, lateralInputs, feedforwardGrowthCandidates)
Learning mode: we are learning a new object in an online fashion. If there is no prior activity, we randomly activate 'sdrSize' cells and create connections to incoming input. If there was prior activity, we maintain it. If we have a union, we simply do not learn at all. These cells will represent the ...
4.393059
4.09909
1.071716
if cells is None: cells = xrange(self.numberOfCells()) return _countWhereGreaterEqualInRows(self.proximalPermanences, cells, self.connectedPermanenceProximal)
def numberOfConnectedProximalSynapses(self, cells=None)
Returns the number of proximal connected synapses on these cells. Parameters: ---------------------------- @param cells (iterable) Indices of the cells. If None return count for all cells.
14.391035
16.348152
0.880285
if cells is None: cells = xrange(self.numberOfCells()) n = 0 for cell in cells: n += self.proximalPermanences.nNonZerosOnRow(cell) return n
def numberOfProximalSynapses(self, cells=None)
Returns the number of proximal synapses with permanence>0 on these cells. Parameters: ---------------------------- @param cells (iterable) Indices of the cells. If None return count for all cells.
5.918882
6.534113
0.905843
if cells is None: cells = xrange(self.numberOfCells()) n = 0 for cell in cells: if self.internalDistalPermanences.nNonZerosOnRow(cell) > 0: n += 1 for permanences in self.distalPermanences: if permanences.nNonZerosOnRow(cell) > 0: n += 1 return n
def numberOfDistalSegments(self, cells=None)
Returns the total number of distal segments for these cells. A segment "exists" if its row in the matrix has any permanence values > 0. Parameters: ---------------------------- @param cells (iterable) Indices of the cells
4.027986
3.540546
1.137674
if cells is None: cells = xrange(self.numberOfCells()) n = _countWhereGreaterEqualInRows(self.internalDistalPermanences, cells, self.connectedPermanenceDistal) for permanences in self.distalPermanences: n += _countWhereGreaterEqualInRows(permanences, ...
def numberOfConnectedDistalSynapses(self, cells=None)
Returns the number of connected distal synapses on these cells. Parameters: ---------------------------- @param cells (iterable) Indices of the cells. If None return count for all cells.
5.774129
6.081078
0.949524
permanences.incrementNonZerosOnOuter( activeCells, activeInput, permanenceIncrement) permanences.incrementNonZerosOnRowsExcludingCols( activeCells, activeInput, -permanenceDecrement) permanences.clipRowsBelowAndAbove( activeCells, 0.0, 1.0) if sampleSize == -1: permanences....
def _learn(# mutated args permanences, rng, # activity activeCells, activeInput, growthCandidateInput, # configuration sampleSize, initialPermanence, permanenceIncrement, permanenceDecrement, connectedPermanence)
For each active cell, reinforce active synapses, punish inactive synapses, and grow new synapses to a subset of the active input bits that the cell isn't already connected to. Parameters: ---------------------------- @param permanences (SparseMatrix) Matrix of permanences, with cells a...
4.366903
4.441433
0.983219
if not os.path.exists(folder): try: os.makedirs(folder) except OSError: # Multiple parallel tasks might create the folder. That's fine. pass filename = "{}/n_{}_w_{}_threshold_{}_cellsPerColumn_{}.json".format( folder, n, w, threshold, cellsPerColumn) if len(glob.glob(filename)) ...
def runExperiment(n, w, threshold, cellsPerColumn, folder, numTrials=5, cleverTMSDRs=False)
Run a PoolOfPairsLocation1DExperiment various union sizes.
3.780797
3.293423
1.147984
for iDriving, cDriving in enumerate(self.drivingOperandSDRs): minicolumnSDR = self.minicolumnSDRs[iDriving] self.pairLayerProximalConnections.associate(minicolumnSDR, cDriving) for iContext, cContext in enumerate(self.contextOperandSDRs): iResult = (iContext + iDriving) % self.numLoca...
def train(self)
Train the pair layer and pooling layer.
8.220368
7.130586
1.152832
# Grow basal segments in the pair layer. for iMinicolumn, contextsByCell in enumerate(pairLayerContexts): for iCell, cellContexts in enumerate(contextsByCell): iCellAbsolute = iMinicolumn*self.pairLayer.getCellsPerColumn() + iCell for context in cellContexts: segments = self...
def trainWithSpecificPairSDRs(self, pairLayerContexts)
Train the pair layer and pooling layer, manually choosing which contexts each cell will encode (i.e. the pair layer's distal connections). @param pairLayerContexts (list of lists of lists of ints) iContext integers for each cell, grouped by minicolumn. For example, [[[1, 3], [2,4]], [[1, 2]]] ...
4.81167
4.230341
1.137419
for dendrite_length in test_dendrite_lengths: nonlinearity = threshold_nonlinearity(dendrite_length / 2) fps = [] fns = [] for trial in range(num_trials): neuron = Neuron(size = dendrite_length*num_dendrites, num_dendrites = num_dendrites, dendrite_length = dendrite_length, dim = dim, nonl...
def run_HTM_false_positive_experiment_synapses(num_neurons = 1, a = 512, dim = 16000, num_samples = 1000, num_dendrites = 500, test_dendrite_lengths = range(2, 32, 2), nu...
Run an experiment to test the false positive rate based on number of synapses per dendrite, dimension and sparsity. Uses a single neuron, with a threshold nonlinearity of theta = s/2. Based on figure 5B in the original SDR paper. The parameters used in generating the figure for this experiment are: 1. a =...
3.224745
3.170412
1.017138
nonlinearity = threshold_nonlinearity(theta) for noise in test_noise_levels: fps = [] fns = [] for trial in range(num_trials): successful_initialization = False while not successful_initialization: neuron = Neuron(size = dendrite_length*num_dendrites, num_dendrites = num_dendr...
def run_noise_experiment(num_neurons = 1, a = 128, dim = 6000, test_noise_levels = range(15, 100, 5), num_samples = 500, num_dendrites = 500, dendrite_length = 30, theta = 8, num_trials = 100)
Tests the impact of noise on a neuron, using an HTM approach to a P&M model of a neuron. Nonlinearity is a simple threshold at theta, as in the original version of this experiment, and each dendrite is bound by the initialization to a single pattern. Only one neuron is used, unlike in the P&M classification e...
3.319988
3.056857
1.086079
self.name = params["name"] self.dataDir = params.get("datadir", "data") self.seed = params.get("seed", 42) + repetition torch.manual_seed(self.seed) np.random.seed(self.seed) random.seed(self.seed) # Training self.epochs = params.get("epochs", 1) self.batch_size = params.get("...
def initialize(self, params, repetition)
Initialize experiment parameters and default values from configuration file
2.020076
2.015135
1.002452
# Create denseCNN2 model model = nn.Sequential( nn.Conv2d(in_channels=self.in_channels, out_channels=self.out_channels[0], kernel_size=self.kernel_size[0], stride=self.stride[0], padding=self.padding[0]), nn.MaxPool2d(kernel_size=2), nn.ReLU(), nn.C...
def createDenseCNNModel(self)
Create a standard network composed of two CNN / MaxPool layers followed by a linear layer with using ReLU activation between the layers
1.85214
1.821736
1.016689
# Create sparseCNN2 model model = nn.Sequential( nn.Conv2d(in_channels=self.in_channels, out_channels=self.out_channels[0], kernel_size=self.kernel_size[0], stride=self.stride[0], padding=self.padding[0]), nn.MaxPool2d(kernel_size=2), KWinners2d(n=self.cnn_...
def createSparseCNNModel(self)
Create a sparse network composed of two CNN / MaxPool layers followed by a sparse linear layer with using k-winner activation between the layers
2.043214
1.942667
1.051757
if self.lr_scheduler_class is None: return None return self.lr_scheduler_class(optimizer, **self.lr_scheduler_params)
def createLearningRateScheduler(self, optimizer)
Creates the learning rate scheduler and attach the optimizer
2.933526
2.951635
0.993865
print "generate a pybrain dataset of sequences" print "the training data contains ", str(nTrain-predictionStep), "records" if encoderInput is None: inDim = 1 + int(useTimeOfDay) + int(useDayOfWeek) else: inDim = encoderInput.n + int(useTimeOfDay) + int(useDayOfWeek) if encoderOutput is None: ...
def getPyBrainDataSetScalarEncoder(sequence, nTrain, encoderInput, encoderOutput, predictionStep=1, useTimeOfDay=True, useDayOfWeek=True)
Use scalar encoder for the data :param sequence: :param nTrain: :param predictionStep: :param useTimeOfDay: :param useDayOfWeek: :return:
3.186166
3.236292
0.984511
pprint.pprint(params) self.initialize(params, repetition) # Load CIFAR dataset dataDir = params.get('dataDir', 'data') self.transform_train = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transform...
def reset(self, params, repetition)
Called at the beginning of each experiment and each repetition
2.288235
2.26755
1.009122
self.name = params["name"] self.dataDir = params.get("datadir", "data") self.seed = params.get("seed", 42) + repetition torch.manual_seed(self.seed) np.random.seed(self.seed) random.seed(self.seed) # Training self.epochs = params.get("epochs", 1) self.batch_size = params.get("...
def initialize(self, params, repetition)
Initialize experiment parameters and default values from configuration file. Called by reset() at the beginning of each experiment and each repetition.
2.044822
2.036327
1.004172
return torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=self.lr_scheduler_gamma)
def createLearningRateScheduler(self, optimizer)
Creates the learning rate scheduler and attach the optimizer
3.407973
3.462009
0.984392
return torch.optim.SGD(model.parameters(), lr=self.lr, momentum=self.momentum, weight_decay=self.weight_decay)
def createOptimizer(self, model)
Create a new instance of the optimizer
2.439306
2.370074
1.029211
for objectName, objectFeatures in self.objects.iteritems(): self.reset() for module in self.locationModules: module.activateRandomLocation() for feature in objectFeatures: locationOnObject = (feature["top"] + feature["height"]/2, feature["left"] +...
def learnObjects(self)
Learn each provided object. This method simultaneously learns 4 sets of synapses: - location -> input - input -> location - input -> object - object -> input
5.622913
5.229642
1.0752
for objectName, objectFeatures in self.objects.iteritems(): self.reset() inferred = False prevTouchSequence = None for _ in xrange(4): while True: touchSequence = list(objectFeatures) random.shuffle(touchSequence) if prevTouchSequence is not Non...
def inferObjectsWithRandomMovements(self)
Infer each object without any location input.
4.635252
4.55732
1.0171
command, (transform, src, dest) = args try: print(progress.value, "remaining") # Apply transformations to all files data = [] data_dir = os.path.join(src, command) for filename in os.listdir(data_dir): path = os.path.join(data_dir, filename) data.append(transform({'path': path}))...
def transform_folder(args)
Transform all the files in the source dataset for the given command and save the results as a single pickle file in the destination dataset :param args: tuple with the following arguments: - the command name: 'zero', 'one', 'two', ... - transforms to apply to wav file - ...
3.335598
3.197342
1.043241
numColumns = numpy.prod(self.getColumnDimensions()) if self.zombiePermutation is None: self.zombiePermutation = numpy.random.permutation(numColumns) self.numDead = int(round(percent * numColumns)) if self.numDead > 0: self.deadCols = self.zombiePermutation[0:self.numDead] else: ...
def killCells(self, percent=0.05)
Changes the percentage of cells that are now considered dead. The first time you call this method a permutation list is set up. Calls change the number of cells considered dead.
4.358484
4.075682
1.069388
self.deadCols = topology.wrappingNeighborhood(centerColumn, radius, self._columnDimensions) self.deadColumnInputSpan = self.getConnectedSpan(self.deadCols) self.removeDeadColumns()
def killCellRegion(self, centerColumn, radius)
Kill cells around a centerColumn, within radius
19.655849
19.517855
1.00707
if not isinstance(inputVector, numpy.ndarray): raise TypeError("Input vector must be a numpy array, not %s" % str(type(inputVector))) if inputVector.size != self._numInputs: raise ValueError( "Input vector dimensions don't match. Expecting %s but got %s" % ( ...
def compute(self, inputVector, learn, activeArray)
This is the primary public method of the SpatialPooler class. This function takes a input vector and outputs the indices of the active columns. If 'learn' is set to True, this method also updates the permanences of the columns. @param inputVector: A numpy array of 0's and 1's that comprises the input ...
4.982101
4.79959
1.038026
seq = np.array(sequence).astype('float64') meanSeq = np.mean(seq) stdSeq = np.std(seq) seq = (seq - np.mean(seq)) / np.std(seq) sequence = seq.tolist() return sequence, meanSeq, stdSeq
def normalizeSequence(sequence)
normalize sequence by subtracting the mean and :param sequence: a list of data samples :param considerDimensions: a list of dimensions to consider :return: normalized sequence
2.455128
3.076915
0.797919
argspec = inspect.getargspec(ColumnPooler.__init__) return argspec.args[1:], argspec.defaults
def getConstructorArguments()
Return constructor argument associated with ColumnPooler. @return defaults (list) a list of args and default values for each argument
7.873974
4.272577
1.84291
if self._pooler is None: params = { "inputWidth": self.inputWidth, "lateralInputWidths": [self.cellCount] * self.numOtherCorticalColumns, "cellCount": self.cellCount, "sdrSize": self.sdrSize, "onlineLearning": self.onlineLearning, "maxSdrSize": self.maxSdrS...
def initialize(self)
Initialize the internal objects.
2.926049
2.9072
1.006484
# Handle reset first (should be sent with an empty signal) if "resetIn" in inputs: assert len(inputs["resetIn"]) == 1 if inputs["resetIn"][0] != 0: # send empty output self.reset() outputs["feedForwardOutput"][:] = 0 outputs["activeCells"][:] = 0 return ...
def compute(self, inputs, outputs)
Run one iteration of compute. Note that if the reset signal is True (1) we assume this iteration represents the *end* of a sequence. The output will contain the representation to this point and any history will then be reset. The output at the next compute will start fresh, presumably with bursting col...
4.01076
3.893148
1.03021
path = os.path.join(resultsPath, "{0}.{1}.csv".format( env.spec.id, "train" if learn else "eval")) with open(path, "w") as f: log = csv.writer(f) log.writerow(["episode", "score", "losses", "values"]) score = 0 episode = 0 loss = 0 # Train for numSteps agent = DQN(env.action_spa...
def run(env, model, learn, numSteps, render, resultsPath, checkpoint=None)
Main RL loop where the agent acts on the environment based on the states :param environment: Open AI Gym environment :param model: Neural neural network model to use as a Q function approximator :param learn: Controls learning. Set to False when using a pre-trained model :param numSteps: Total number of steps/f...
2.383844
2.456816
0.970298
name = params['name'] fullpath = os.path.join(params['path'], params['name']) logname = os.path.join(fullpath, '%i.log'%rep) if os.path.exists(logname): logfile = open(logname, 'r') lines = logfile.readlines() logfile.close() return int(100 * len(lines) / params['ite...
def progress(params, rep)
Helper function to calculate the progress made on one experiment.
2.854577
2.738796
1.042274
if type(param) == types.StringType: return param else: return re.sub("0+$", '0', '%f'%param)
def convert_param_to_dirname(param)
Helper function to convert a parameter value to a valid directory name.
8.222196
8.06367
1.019659
optparser = optparse.OptionParser() optparser.add_option('-c', '--config', action='store', dest='config', type='string', default='experiments.cfg', help="your experiments config file") optparser.add_option('-n', '--numcores', action='store', dest='nc...
def parse_opt(self)
parses the command line options for different settings.
2.78268
2.733493
1.017994
self.cfgparser = ConfigParser() if not self.cfgparser.read(self.options.config): raise SystemExit('config file %s not found.'%self.options.config) # Change the current working directory to be relative to 'experiments.cfg' projectDir = os.path.dirname(self.options.c...
def parse_cfg(self)
parses the given config file for experiments.
3.736648
3.512094
1.063937
if not os.path.exists(path): os.makedirs(path)
def mkdir(self, path)
create a directory if it does not exist.
2.478549
2.290367
1.082163
exps = [] for dp, dn, fn in os.walk(path): if 'experiment.cfg' in fn: subdirs = [os.path.join(dp, d) for d in os.listdir(dp) if os.path.isdir(os.path.join(dp, d))] if all(map(lambda s: self.get_exps(s) == [], subdirs)): exps...
def get_exps(self, path='.')
go through all subdirectories starting at path and return the experiment identifiers (= directory names) of all existing experiments. A directory is considered an experiment if it contains a experiment.cfg file.
2.564457
2.234565
1.147632
params = {} for t,v in items: try: # try to evaluate parameter (float, int, list) if v in ['grid', 'list']: params[t] = v else: params[t] = eval(v) if isinstance(params[t],...
def items_to_params(self, items)
evaluate the found items (strings) to become floats, ints or lists.
4.079662
3.63209
1.123227
cfgp = ConfigParser() cfgp.read(os.path.join(exp, cfgname)) section = cfgp.sections()[0] params = self.items_to_params(cfgp.items(section)) params['name'] = section return params
def get_params(self, exp, cfgname='experiment.cfg')
reads the parameters of the experiment (= path) given.
3.319611
3.218252
1.031495
exps = [] for dp, dn, df in os.walk(path): if 'experiment.cfg' in df: cfgp = ConfigParser() cfgp.read(os.path.join(dp, 'experiment.cfg')) if name in cfgp.sections(): exps.append(dp) return exps
def get_exp(self, name, path='.')
given an experiment name (used in section titles), this function returns the correct path of the experiment.
3.296137
3.125627
1.054552
cfgp = ConfigParser() cfgp.add_section(params['name']) for p in params: if p == 'name': continue cfgp.set(params['name'], p, params[p]) f = open(os.path.join(path, 'experiment.cfg'), 'w') cfgp.write(f) f.close()
def write_config_file(self, params, path)
write a config file for this single exp in the folder path.
2.228428
2.053679
1.085091
params = self.get_params(exp) if params == None: raise SystemExit('experiment %s not found.'%exp) # make list of tags, even if it is only one if tags != 'all' and not hasattr(tags, '__iter__'): tags = [tags] ...
def get_history(self, exp, rep, tags)
returns the whole history for one experiment and one repetition. tags can be a string or a list of strings. if tags is a string, the history is returned as list of values, if tags is a list of strings or 'all', history is returned as a dictionary of lists of values.
2.963251
2.830747
1.046809
history = self.get_history(exp, rep, 'all') return history.keys()
def get_history_tags(self, exp, rep=0)
returns all available tags (logging keys) of the given experiment repetition. Note: Technically, each repetition could have different tags, therefore the rep number can be passed in as parameter, even though usually all repetitions have the same tags. The ...
5.638648
6.505589
0.866739
history = self.get_history(exp, rep, tags) # empty histories always return None if len(history) == 0: return None # distinguish dictionary (several tags) from list if type(history) == dict: for h in history: i...
def get_value(self, exp, rep, tags, which='last')
Like get_history(..) but returns only one single value rather than the whole list. tags can be a string or a list of strings. if tags is a string, the history is returned as a single value, if tags is a list of strings, history is returned as a dictionary of values. ...
2.294598
2.046194
1.121398
subexps = self.get_exps(exp) tagvalues = ['%s%s'%(k, convert_param_to_dirname(kwargs[k])) for k in kwargs] values = [self.get_value(se, rep, tag, which) for se in subexps if all(map(lambda tv: tv in se, tagvalues))] params = [self.get_params(se) for se in subexps if al...
def get_values_fix_params(self, exp, rep, tag, which='last', **kwargs)
this function uses get_value(..) but returns all values where the subexperiments match the additional kwargs arguments. if alpha=1.0, beta=0.01 is given, then only those experiment values are returned, as a list.
3.911224
3.70544
1.055536
subexps = self.get_exps(exp) tagvalues = [re.sub("0+$", '0', '%s%f'%(k, kwargs[k])) for k in kwargs] histories = [self.get_history(se, rep, tag) for se in subexps if all(map(lambda tv: tv in se, tagvalues))] params = [self.get_params(se) for se in subexps if all(map(lambda tv:...
def get_histories_fix_params(self, exp, rep, tag, **kwargs)
this function uses get_history(..) but returns all histories where the subexperiments match the additional kwargs arguments. if alpha=1.0, beta = 0.01 is given, then only those experiment histories are returned, as a list.
3.829128
3.703544
1.033909
params = self.get_params(exp) # explicitly make tags list in case of 'all' if tags == 'all': tags = self.get_history(exp, 0, 'all').keys() # make list of tags if it is just a string if not hasattr(tags, '__iter__'): tags = [tags]...
def get_histories_over_repetitions(self, exp, tags, aggregate)
this function gets all histories of all repetitions using get_history() on the given tag(s), and then applies the function given by 'aggregate' to all corresponding values in each history over all iterations. Typical aggregate functions could be 'mean' or 'max'.
2.935902
2.897089
1.013397
for d in self.get_exps('.'): params = self.get_params(d) name = params['name'] basename = name.split('/')[0] # if -e option is used, only show requested experiments if self.options.experiments and basename not in self.options.experiments: ...
def browse(self)
go through all subfolders (starting at '.') and return information about the existing experiments. if the -B option is given, all parameters are shown, -b only displays the most important ones. this function does *not* execute any experiments.
3.087791
2.967262
1.04062
# for one single experiment, still wrap it in list if type(paramlist) == types.DictType: paramlist = [paramlist] # get all options that are iteratable and build all combinations (grid) or tuples (list) iparamlist = [] for params in paramlist: ...
def expand_param_list(self, paramlist)
expands the parameters list according to one of these schemes: grid: every list item is combined with every other list item list: every n-th list item of parameter lists are combined
3.99448
3.911197
1.021293
# create experiment path and subdir fullpath = os.path.join(params['path'], params['name']) self.mkdir(fullpath) # delete old histories if --del flag is active if delete and os.path.exists(fullpath): os.system('rm %s/*' % fullpath) # write a co...
def create_dir(self, params, delete=False)
creates a subdirectory for the experiment, and deletes existing files, if the delete flag is true. then writes the current experiment.cfg file in the folder.
5.517259
5.290544
1.042853
self.parse_opt() self.parse_cfg() # if -b, -B or -p option is set, only show information, don't # start the experiments if self.options.browse or self.options.browse_big or self.options.progress: self.browse() raise SystemExit ...
def start(self)
starts the experiments as given in the config file.
5.585226
5.282595
1.057288
paramlist = self.expand_param_list(params) # create directories, write config files for pl in paramlist: # check for required param keys if ('name' in pl) and ('iterations' in pl) and ('repetitions' in pl) and ('path' in pl): self.create_d...
def do_experiment(self, params)
runs one experiment programatically and returns. params: either parameter dictionary (for one single experiment) or a list of parameter dictionaries (for several experiments).
4.940343
4.96181
0.995674
try: name = params['name'] fullpath = os.path.join(params['path'], params['name']) logname = os.path.join(fullpath, '%i.log'%rep) # check if repetition exists and has been completed restore = 0 if os.path.exists(logname): ...
def run_rep(self, params, rep)
run a single repetition including directory creation, log files, etc.
3.409382
3.344967
1.019257
if self._overlaps is None: self._populateOverlaps() overlaps = self._overlaps linkage = scipy.cluster.hierarchy.linkage(-overlaps, method=linkageMethod) self._linkage = linkage
def cluster(self, linkageMethod="single")
Perform hierarchical clustering on training vectors using specified linkage method. Results can be obtained using getLinkageMatrix(), etc. @param linkageMethod (string) Linkage method for computing between-class dissimilarities. Valid options are: "single" (aka min), "complete" (aka max), "...
4.103141
4.819445
0.851372
linkage = self.getLinkageMatrix() linkage[:, 2] -= linkage[:, 2].min() clusters = scipy.cluster.hierarchy.fcluster( linkage, numClusters, criterion="maxclust") prototypes = [] clusterSizes = [] for cluster_id in numpy.unique(clusters): ids = numpy.arange(len(clusters))[cluster...
def getClusterPrototypes(self, numClusters, numPrototypes=1)
Create numClusters flat clusters and find approximately numPrototypes prototypes per flat cluster. Returns an array with each row containing the indices of the prototypes for a single flat cluster. @param numClusters (int) Number of flat clusters to return (approximate). @param numPrototypes (int) Num...
2.624819
2.7213
0.964546
# find the number of data points based on the length of the overlap array # solves for n: len(overlaps) = n(n-1)/2 n = numpy.roots([1, -1, -2 * len(overlaps)]).max() k = len(indices) indices = numpy.array(indices, dtype=int) rowIdxs = numpy.ndarray((k, k-1), dtype=int) colIdxs = numpy....
def _getPrototypes(indices, overlaps, topNumber=1)
Given a compressed overlap array and a set of indices specifying a subset of those in that array, return the set of topNumber indices of vectors that have maximum average overlap with other vectors in `indices`. @param indices (arraylike) Array of indices for which to get prototypes. @param overlaps (...
3.878622
3.947066
0.982659
indicesA = numpy.array(indicesA, dtype=int) indicesB = numpy.array(indicesB, dtype=int) n = int(n) # Ensure that there are no self-comparisons assert (indicesA != indicesB).all() # re-arrange indices to ensure that rowIxs[i] < colIxs[i] for all i rowIxs = numpy.where(indicesA < indice...
def _condensedIndex(indicesA, indicesB, n)
Given a set of n points for which pairwise overlaps are stored in a flat array X in the format returned by _computeOverlaps (upper triangular of the overlap matrix in row-major order), this function returns the indices in X that correspond to the overlaps for the pairs of points specified. Example ...
2.904976
3.157258
0.920095
nVectors = data.shape[0] nDims = data.shape[1] nPairs = (nVectors+1)*nVectors/2 if selfOverlaps else ( nVectors*(nVectors-1)/2) overlaps = numpy.ndarray(nPairs, dtype=dtype) pos = 0 for i in xrange(nVectors): start = i if selfOverlaps else i+1 a = data[i] b = data[s...
def _computeOverlaps(data, selfOverlaps=False, dtype="int16")
Calculates all pairwise overlaps between the rows of the input. Returns an array of all n(n-1)/2 values in the upper triangular portion of the pairwise overlap matrix. Values are returned in row-major order. @param data (scipy.sparse.csr_matrix) A CSR sparse matrix with one vector per row. Any non-...
3.440997
3.197272
1.076229
print("\n================",expName,"=====================") try: expParams = suite.get_params(expName) pprint.pprint(expParams) for p in ["boost_strength", "k", "learning_rate", "weight_sparsity", "k_inference_factor", "boost_strength_factor", "c1_out_channels", "c1_k", "...
def analyzeParameters(expName, suite)
Analyze the impact of each list parameter in this experiment
6.030237
5.96038
1.01172