code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
plt.ion() plt.show() x = numpy.linspace(0, 15, 100) y = numpy.zeros(x.shape) y = self.excite(y, x) plt.plot(x, y) plt.xlabel('Input') plt.ylabel('Persistence') plt.title('Sigmoid Activation Function')
def plot(self)
plot the activation function
4.109727
3.540371
1.160818
accuracy = [] numIteration = [] numSequences = [] for i in xrange(len(predictions) - 1): if num is not None and i > num: continue if truths[i] is None: continue # identify the end of sequence if resets is not None or randoms is not None: if not (resets[i+1] or randoms[i+1...
def computeAccuracyEnding(predictions, truths, iterations, resets=None, randoms=None, num=None, sequenceCounter=None)
Compute accuracy on the sequence ending
3.206361
3.280075
0.977527
indices = np.random.permutation(len(dataset)) training_count = int(len(indices) * ratio) train = torch.utils.data.SubsetRandomSampler(indices=indices[:training_count]) validate = torch.utils.data.SubsetRandomSampler(indices=indices[training_count:]) return (train, validate)
def createValidationDataSampler(dataset, ratio)
Create `torch.utils.data.Sampler`s used to split the dataset into 2 ramdom sampled subsets. The first should used for training and the second for validation. :param dataset: A valid torch.utils.data.Dataset (i.e. torchvision.datasets.MNIST) :param ratio: The percentage of the dataset to be used for training. T...
2.459312
2.360279
1.041958
# Split dataset based on the group by function and keep track of indices indicesByGroup = collections.defaultdict(list) for k, g in itertools.groupby(enumerate(dataset), key=lambda x: groupby(x[1])): indicesByGroup[k].extend([i[0] for i in g]) # Sort by group and create a Subset dataset for each of the...
def splitDataset(dataset, groupby)
Split the given dataset into multiple datasets grouped by the given groupby function. For example:: # Split mnist dataset into 10 datasets, one dataset for each label splitDataset(mnist, groupby=lambda x: x[1]) # Split mnist dataset into 5 datasets, one dataset for each label pair: [0,1], [2,3],.....
3.624
3.520751
1.029326
if not hasattr(module, "__counter_nonzero__"): raise ValueError("register_counter_nonzero was not called for this network") if module.training: return size = module.__counter_nonzero__.get("input", 0) size += sum([torch.nonzero(i).size(0) for i in inputs]) module.__counter_nonzero__["input"] = si...
def _nonzero_counter_hook(module, inputs, output)
Module hook used to count the number of nonzero floating point values from all the tensors used by the given network during inference. This hook will be called every time before :func:`forward` is invoked. See :func:`torch.nn.Module.register_forward_hook`
1.914278
1.924491
0.994693
if hasattr(network, "__counter_nonzero__"): raise ValueError("nonzero counter was already registered for this network") if not isinstance(stats, dict): raise ValueError("stats must be a dictionary") network.__counter_nonzero__ = stats handles = [] for name, module in network.named_modules(): ...
def register_nonzero_counter(network, stats)
Register forward hooks to count the number of nonzero floating points values from all the tensors used by the given network during inference. :param network: The network to attach the counter :param stats: Dictionary holding the counter.
3.026444
3.016599
1.003264
if not hasattr(network, "__counter_nonzero_handles__"): raise ValueError("register_counter_nonzero was not called for this network") for h in network.__counter_nonzero_handles__: h.remove() delattr(network, "__counter_nonzero_handles__") for module in network.modules(): if hasattr(module, "__co...
def unregister_counter_nonzero(network)
Unregister nonzero counter hooks :param network: The network previously registered via `register_nonzero_counter`
2.65635
2.58236
1.028652
super(TinyCIFARExperiment, self).initialize(params, repetition) self.network_type = params.get("network_type", "sparse")
def initialize(self, params, repetition)
Initialize experiment parameters and default values from configuration file. Called at the beginning of each experiment and each repetition.
5.9246
5.785095
1.024115
print("Learning rate: {:f}".format(self.lr_scheduler.get_lr()[0])) entropies = getEntropies(self.model) print("Entropy and max entropy: ", float(entropies[0]), entropies[1]) print("Training time for epoch=", self.epoch_train_time) for noise in self.noise_values: print("Noise= {:3.2f}, los...
def logger(self, iteration, ret)
Print out relevant information at each epoch
4.345517
4.206178
1.033127
if not os.path.exists(plotDir): os.makedirs(plotDir) plt.figure() # plot request stats for field in fields: fieldKey = field[0] + " C0" plt.plot(stats[fieldKey], marker='+', label=field[1]) # format plt.legend(loc="upper right") plt.xlabel("Input number") plt.xticks(range(stats["numSte...
def plotOneInferenceRun(stats, fields, basename, itemType="", plotDir="plots", ymax=100, trialNumber=0)
Plots individual inference runs.
3.680963
3.771442
0.97601
if not os.path.exists(plotDir): os.makedirs(plotDir) plt.figure() colorList = ['r', 'b', 'g', 'm', 'c', 'k', 'y'] # plot request stats for i, field in enumerate(fields): fieldKey = field[0] + " C0" trace = [] for s in stats: trace += s[fieldKey] plt.plot(trace, label=field[1], ...
def plotMultipleInferenceRun(stats, fields, basename, plotDir="plots")
Plots individual inference runs.
4.123451
4.216527
0.977926
# Read out results and get the ranges we want. with open(resultsFig5B, "rb") as f: results = cPickle.load(f) objectRange = [] featureRange = [] for r in results: if r["numObjects"] not in objectRange: objectRange.append(r["numObjects"]) if r["numFeatures"] not in featureRange: featureRange.app...
def plotAccuracyDuringSensorimotorInference(resultsFig5B, title="", yaxis="")
Plot accuracy vs number of features
2.663566
2.653704
1.003716
decrementRange = [] mcRange = [] for r in results: if r["basalPredictedSegmentDecrement"] not in decrementRange: decrementRange.append(r["basalPredictedSegmentDecrement"]) if r["inputSize"] not in mcRange: mcRange.append(r["inputSize"]) decrementRange.sort() mcRange.sort() print decr...
def plotAccuracyAndMCsDuringDecrementChange(results, title="", yaxis="")
Plot accuracy vs decrement value
3.548363
3.516586
1.009036
# Read in results file with open(os.path.join(dirName, "sequence_batch_high_dec_normal_features.pkl"), "rb") as f: results = cPickle.load(f) locationRange = [] featureRange = [] for r in results: if r["numLocations"] not in locationRange: locationRange.append(r["numLocations"]) if ...
def plotAccuracyDuringSequenceInference(dirName, title="", yaxis="")
Plot accuracy vs number of locations
2.818039
2.808732
1.003314
# Generate images similar to those used in the first plot for the section # "Simulations with Pure Temporal Sequences" try: resultsFig4A = os.path.join(dirName, "pure_sequences_example.pkl") with open(resultsFig4A, "rb") as f: results = cPickle.load(f) for trialNum, stat in enumerate(results...
def gen4(dirName)
Plots 4A and 4B
4.562902
4.479687
1.018576
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.317295
2.308841
1.003662
tm = tpregion.getSelf()._tfdr print "------------PY TemporalMemory Parameters ------------------" print "numberOfCols =", tm.getColumnDimensions() print "cellsPerColumn =", tm.getCellsPerColumn() print "minThreshold =", tm.getMinThreshold() print "activationThreshold ...
def printTPRegionParams(tpregion)
Note: assumes we are using TemporalMemory/TPShim in the TPRegion
5.639239
5.124546
1.100437
predictedField = model.getInferenceArgs()['predictedField'] print "run TM through the train data multiple times" for nPass in xrange(nMultiplePass): for j in xrange(nTrain): inputRecord = getInputRecord(df, predictedField, j) result = model.run(inputRecord) if j % 100 == 0: print ...
def runMultiplePass(df, model, nMultiplePass, nTrain)
run CLA model through data record 0:nTrain nMultiplePass passes
8.629616
8.423676
1.024448
predictedField = model.getInferenceArgs()['predictedField'] print "run TM through the train data multiple times" for nPass in xrange(nMultiplePass): for j in xrange(nTrain): inputRecord = getInputRecord(df, predictedField, j) model._sensorCompute(inputRecord) model._spCompute() if ...
def runMultiplePassSPonly(df, model, nMultiplePass, nTrain)
run CLA model SP through data record 0:nTrain nMultiplePass passes
8.298979
7.822387
1.060927
spec = { "description":"Sensor for sending sparse data to an HTM network.", "singleNodeOnly":True, "outputs":{ "dataOut":{ "description":"Encoded text", "dataType":"Real32", "count":0, "regionLevel":True, "isDefaultOutput":True, ...
def getSpec(cls)
Return base spec for this region. See base class method for more info.
4.445354
4.36599
1.018178
if len(self.queue) > 0: # Take the top element of the data queue data = self.queue.pop() else: raise Exception("RawSensor: No data to encode: queue is empty ") # Copy data into output vectors outputs["resetOut"][0] = data["reset"] outputs["sequenceIdOut"][0] = data["sequence...
def compute(self, inputs, outputs)
Get the next record from the queue and encode it. The fields for inputs and outputs are as defined in the spec above.
4.763624
4.408133
1.080644
if type(nonZeros) == type(""): nonZeroList = eval(nonZeros) elif type(nonZeros) == type([]): nonZeroList = nonZeros else: raise Exception("RawSensor.addDataToQueue: unknown type for nonZeros") self.queue.appendleft({ "sequenceId": int(sequenceId), "reset": int(reset),...
def addDataToQueue(self, nonZeros, 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 nonZeros A list of the non-zero elements corresponding to the sparse output. This list can be specified in two ways, as a pyt...
3.28437
2.958598
1.11011
sequenceList = [] currentSequence = [] for s in generatedSequences: if s is None: sequenceList.append(currentSequence) currentSequence = [] else: currentSequence.append(s) return sequenceList
def convertSequenceMachineSequence(generatedSequences)
Convert a sequence from the SequenceMachine into a list of sequences, such that each sequence is a list of set of SDRs.
2.485859
2.341522
1.061642
# Lots of room for noise sdrs patternAlphabetSize = 10*(sequenceLength * sequenceCount) patternMachine = PatternMachine(n, w, patternAlphabetSize, seed) sequenceMachine = SequenceMachine(patternMachine, seed) numbers = sequenceMachine.generateNumbers(sequenceCount, sequenceLength, ...
def generateSequences(n=2048, w=40, sequenceLength=5, sequenceCount=2, sharedRange=None, seed=42)
Generate high order sequences using SequenceMachine
7.271219
7.211458
1.008287
if enableFeedback: print "Feedback enabled: " else: print "Feedback disabled: " error = 0 activityTraces = [] responses = [] for i,sequence in enumerate(sequences): (avgActiveCells, avgPredictedActiveCells, activityTrace, responsesThisSeq) = exp.infer( sequence, sequenceNumber=i, enabl...
def runInference(exp, sequences, enableFeedback=True)
Run inference on this set of sequences and compute error
4.196146
4.152342
1.010549
exp = L4L2Experiment( "lateral_disambiguation", numCorticalColumns=2, ) objects = createObjectMachine( machineType="simple", numInputBits=20, sensorInputSize=1024, externalInputSize=1024, numCorticalColumns=2, ) objects.addObject([(1, 1), (2, 2)]) objects.addObject([(1, 1), (...
def runLateralDisambiguation(noiseLevel=None, profile=False)
Runs a simple experiment where two objects share a (location, feature) pair. At inference, one column sees that ambiguous pair, and the other sees a unique one. We should see the first column rapidly converge to a unique representation. Parameters: ---------------------------- @param noiseLevel (float) ...
5.280596
5.05337
1.044965
exp = L4L2Experiment( "stretch_L10_F10_C2", numCorticalColumns=2, ) objects = createObjectMachine( machineType="simple", numInputBits=20, sensorInputSize=1024, externalInputSize=1024, numCorticalColumns=2, ) objects.createRandomObjects(10, 10, numLocations=10, numFeatures=10) ...
def runStretch(noiseLevel=None, profile=False)
Stretch test that learns a lot of objects. Parameters: ---------------------------- @param noiseLevel (float) Noise level to add to the locations and features during inference @param profile (bool) If True, the network will be profiled after learning and inference
5.043151
4.882978
1.032802
model.train() if progress_bar is not None: loader = tqdm(loader, **progress_bar) # update progress bar total based on batches_in_epoch if batches_in_epoch < len(loader): loader.total = batches_in_epoch for batch_idx, (data, target) in enumerate(loader): data, target = data.to(device), ta...
def trainModel(model, loader, optimizer, device, criterion=F.nll_loss, batches_in_epoch=sys.maxsize, batch_callback=None, progress_bar=None)
Train the given model by iterating through mini batches. An epoch ends after one pass through the training set, or if the number of mini batches exceeds the parameter "batches_in_epoch". :param model: pytorch model to be trained :type model: torch.nn.Module :param loader: train dataset loader :type loader:...
1.921642
1.976849
0.972073
model.eval() loss = 0 correct = 0 dataset_len = len(loader.sampler) if progress is not None: loader = tqdm(loader, **progress) with torch.no_grad(): for batch_idx, (data, target) in enumerate(loader): data, target = data.to(device), target.to(device) output = model(data) loss ...
def evaluateModel(model, loader, device, batches_in_epoch=sys.maxsize, criterion=F.nll_loss, progress=None)
Evaluate pre-trained model using given test dataset loader. :param model: Pretrained pytorch model :type model: torch.nn.Module :param loader: test dataset loader :type loader: :class:`torch.utils.data.DataLoader` :param device: device to use ('cpu' or 'cuda') :type device: :class:`torch.device :param ba...
1.707588
1.676085
1.018795
numpy.random.seed(seed) fps = [] fns = [] totalUnclassified = 0 for trial in range(numTrials): # data = generate_evenly_distributed_data_sparse(dim = dim, # num_active = numActive, # num_samples = nu...
def run_false_positive_experiment_dim( numActive = 128, dim = 500, numSamples = 1000, numDendrites = 500, synapses = 24, numTrials = 10000, ...
Run an experiment to test the false positive rate based on number of synapses per dendrite, dimension and sparsity. Uses two competing neurons, along the P&M model. Based on figure 5B in the original SDR paper.
2.515414
2.532143
0.993393
objects = {} for objectName, locationList in learningConfig.iteritems(): sensationList = [] physicalObject = self.objects[objectName] if plot: fig, ax = physicalObject.plot() for element in locationList: # location name and number of points if len(elemen...
def provideObjectsToLearn(self, learningConfig, plot=False)
Returns the objects in a canonical format to be sent to an experiment. The input, learningConfig, should have the following format. It is a mapping from object to a list of features to sample locations from, and the number of points to sample from each feature. Note that these objects should be first a...
3.358575
2.998951
1.119917
if "numSteps" in inferenceConfig: numSteps = inferenceConfig["numSteps"] else: numSteps = len(inferenceConfig["pairs"][0]) if "noiseLevel" in inferenceConfig: noise = inferenceConfig["noiseLevel"] else: noise = None # some checks if numSteps == 0: raise Value...
def provideObjectToInfer(self, inferenceConfig, plot=False)
Returns the sensations in a canonical format to be sent to an experiment. The input inferenceConfig should be a dict with the following form. The "pairs" field provide a mapping from cortical column to a list of sensations, each sensations being either: - a feature key to sample a location from ...
3.332418
2.770831
1.202678
if name is None: name = len(self.objects) self.objects[name] = object
def addObject(self, object, name=None)
Adds an object to the Machine. Objects should be PhysicalObjects.
4.378327
4.124614
1.061512
sensations = {} for col in xrange(self.numColumns): location, featureID = pairs[col] location = [int(coord) for coord in location] location = self.locationEncoder.encode( (np.array(location, dtype="int32"), self._getRadius(location)) ) location = set(location.nonzero(...
def _getSDRPairs(self, pairs, noise=None)
This method takes a list of (location, feature) pairs (one pair per cortical column), and returns a sensation dict in the correct format, adding noise if necessary. In each pair, the location is an actual integer location to be encoded, and the feature is just an index.
4.253633
3.787627
1.123034
# TODO: find better heuristic return int(math.sqrt(sum([coord ** 2 for coord in location])))
def _getRadius(self, location)
Returns the radius associated with the given location. This is a bit of an awkward argument to the CoordinateEncoder, which specifies the resolution (in was used to encode differently depending on speed in the GPS encoder). Since the coordinates are object-centric, for now we use the "point radius" as ...
9.608878
7.031229
1.3666
if pattern is None: return None newBits = [] for bit in pattern: if random.random() < noiseLevel: newBits.append(random.randint(0, max(pattern))) else: newBits.append(bit) return set(newBits)
def _addNoise(self, pattern, noiseLevel)
Adds noise the given list of patterns and returns a list of noisy copies.
3.334855
3.193841
1.044152
cellsIndices = range(totalSize) random.shuffle(cellsIndices) return set(cellsIndices[:numBits])
def _generatePattern(self, numBits, totalSize)
Generates a random SDR with specified number of bits and total size.
8.23354
6.986134
1.178554
# Calculate predictions for this timestep (activeApicalSegments, matchingApicalSegments, apicalPotentialOverlaps) = self._calculateSegmentActivity( self.apicalConnections, apicalInput, self.connectedPermanence, self.activationThreshold, self.minThreshold, self.reducedBasalThreshold) ...
def apicalCheck(self, apicalInput)
Return 'recent' apically predicted cells for each tick of apical timer - finds active apical segments corresponding to predicted basal segment, @param apicalInput (numpy array) List of active input bits for the apical dendrite segments
9.741291
8.693081
1.12058
self.split(dataPath, numLabels, **kwargs) if not ordered: self.randomizeData(seed) filename, ext = os.path.splitext(dataPath) classificationFileName = "{}_category.json".format(filename) dataFileName = "{}_network{}".format(filename, ext) if stripCats: self.stripCateg...
def setupData(self, dataPath, numLabels=0, ordered=False, stripCats=False, seed=42, **kwargs)
Main method of this class. Use for setting up a network data file. @param dataPath (str) Path to CSV file. @param numLabels (int) Number of columns of category labels. @param textPreprocess (bool) True will preprocess text while tokenizing. @param ordered (bool) Keep...
4.534409
4.646829
0.975807
if filePath: dataDict = readCSV(filePath, numLabels=numLabels) if dataDict is None: raise Exception("No data given, or could not read CSV.") preprocessor = TextPreprocess(abbrCSV=abbrCSV, contrCSV=contrCSV) expandAbbr = (abbrCSV != "") expandContr = (contrCSV != "") for recor...
def split(self, filePath=None, numLabels=3, textPreprocess=False, dataDict=None, abbrCSV="", contrCSV="", ignoreCommon=100, removeStrings="[identifier deleted]", correctSpell=True)
Split all the comments in a file into tokens, w/ or w/o preprocessing. Specifying both filePath and dataDict will prefer filePath. @param filePath (str) Path to csv file @param dataDict (dict) Data as returned by readCSV() @param numLabels (int) Number of columns of category...
4.368145
4.218163
1.035556
record = {"_category":categories, "_sequenceId":seqID} data = [] reset = 1 for t in tokens: tokenRecord = record.copy() tokenRecord["_token"] = t tokenRecord["_reset"] = reset tokenRecord["ID"] = uniqueID reset = 0 data.append(tokenRecord) retu...
def _formatSequence(tokens, categories, seqID, uniqueID)
Write the sequence of data records for this sample.
4.469882
4.399307
1.016042
if self.records is None: return False if not dataOutputFile.endswith("csv"): raise TypeError("data output file must be csv.") if not categoriesOutputFile.endswith("json"): raise TypeError("category output file must be json") # Ensure directory exists dataOutputDirectory = os...
def saveData(self, dataOutputFile, categoriesOutputFile)
Save the processed data and the associated category mapping. @param dataOutputFile (str) Location to save data @param categoriesOutputFile (str) Location to save category map @return (str) Path to the saved data file iff saveData() is s...
2.217153
2.185551
1.01446
# TODO: enable text preprocessing; abstract out the logic in split() into a common method. tokens = TextPreprocess().tokenize(text) cat = [-1] self.sequenceCount += 1 uniqueID = "q" data = self._formatSequence(tokens, cat, self.sequenceCount-1, uniqueID) return data
def generateSequence(self, text, preprocess=False)
Return a list of lists representing the text sequence in network data format. Does not preprocess the text.
17.460127
15.473565
1.128384
try: with open(netDataFile) as f: reader = csv.reader(f) header = next(reader, None) next(reader, None) resetIdx = next(reader).index("R") tokenIdx = header.index("_token") catIdx = header.index("_category") idIdx = header.index("ID") curre...
def getSamples(netDataFile)
Returns samples joined at reset points. @param netDataFile (str) Path to file (in the FileRecordStream format). @return samples (OrderedDict) Keys are sample number (in order they are read in). Values are two-tuples of samp...
2.565422
2.26397
1.133152
try: with open(networkDataFile) as f: reader = csv.reader(f) next(reader, None) next(reader, None) specials = next(reader) resetIdx = specials.index("R") classIdx = specials.index("C") classifications = [] for line in reader: if i...
def getClassifications(networkDataFile)
Returns the classifications at the indices where the data sequences reset. @param networkDataFile (str) Path to file in the FileRecordStream format @return (list) list of string versions of the classification...
2.826684
2.790323
1.013031
try: with open(networkDataFile) as f: reader = csv.reader(f) next(reader, None) next(reader, None) resetIdx = next(reader).index("R") count = 0 numTokens = [] for line in reader: if int(line[resetIdx]) == 1: if count != 0: ...
def getNumberOfTokens(networkDataFile)
Returns the number of tokens for each sequence @param networkDataFile (str) Path to file in the FileRecordStream format @return (list) list of number of tokens
2.711782
2.716469
0.998274
try: with open(networkDataFile) as f: reader = csv.reader(f) next(reader, None) next(reader, None) resetIdx = next(reader).index("R") resets = [] for i, line in enumerate(reader): if int(line[resetIdx]) == 1: resets.append(i) ...
def getResetsIndices(networkDataFile)
Returns the indices at which the data sequences reset.
2.676874
2.64864
1.01066
noiseValues = ["0.0", "0.05", "0.1", "0.15", "0.2", "0.25", "0.3", "0.35", "0.4", "0.45", "0.5"] print("\nNOISE CURVE =====",expPath,"====== ITERATION:",iteration,"=========") try: result = suite.get_value(expPath, 0, noiseValues, iteration) info = [] for k in noiseValue...
def lastNoiseCurve(expPath, suite, iteration="last")
Print the noise errors from the last iteration of this experiment
3.948734
3.980001
0.992144
print("\nLEARNING CURVE ================",expPath,"=====================") try: headers=["testResults","validation","bgResults","elapsedTime"] result = suite.get_value(expPath, 0, headers, "all") info = [] maxValidationAccuracy = -1.0 maxTestAccuracy = -1.0 maxBGAccuracy = -1.0 maxIte...
def learningCurve(expPath, suite)
Print the test, validation and other scores from each iteration of this experiment. We select the test score that corresponds to the iteration with maximum validation accuracy.
3.46739
3.207745
1.080943
maxValidationAccuracy = -1.0 maxTestAccuracy = -1.0 maxTotalAccuracy = -1.0 maxBGAccuracy = -1.0 maxIter = -1 try: headers=["testResults", "validation", "bgResults", "elapsedTime", "totalCorrect"] result = suite.get_value(expPath, 0, headers, "all") for i,v in enumerate(zip(result["testResult...
def bestScore(expPath, suite)
Given a single experiment, return the test, validation and other scores from the iteration with maximum validation accuracy.
3.330517
3.107547
1.071751
writer = csv.writer(outFile) headers = ["testAccuracy", "bgAccuracy", "maxTotalAccuracy", "experiment path"] writer.writerow(headers) info = [] print("\n================",expName,"=====================") try: # Retrieve the last totalCorrect from each experiment # Print them sorted from best to w...
def findOptimalResults(expName, suite, outFile)
Go through every experiment in the specified folder. For each experiment, find the iteration with the best validation score, and return the metrics associated with that iteration.
6.149668
5.930447
1.036965
exps = suite.get_exps(expPath) testScores = np.zeros(len(exps)) noiseScores = np.zeros(len(exps)) for i,e in enumerate(exps): maxTestAccuracy, maxValidationAccuracy, maxBGAccuracy, maxIter, maxTotalAccuracy = bestScore( e, suite) testScores[i] = maxTestAccuracy noiseScores[i] = maxTotalAccu...
def getErrorBars(expPath, suite)
Go through each experiment in the path. Get the best scores for each experiment based on accuracy on validation set. Print out overall mean, and stdev for test accuracy, BG accuracy, and noise accuracy.
3.960792
3.39512
1.166613
aKey = aKey if aKey is not None else a bKey = bKey if bKey is not None else b aWithinBMask = np.in1d(aKey, bKey) if rightMinusLeft: bWithinAMask = np.in1d(bKey, aKey) if leftMinusRight: return (a[aWithinBMask], a[~aWithinBMask], b[bWithinAMask]) else: re...
def setCompare(a, b, aKey=None, bKey=None, leftMinusRight=False, rightMinusLeft=False)
Compute the intersection and differences between two arrays, comparing elements by their key. @param a (numpy array) The left set to compare. @param b (numpy array) The right set to compare. @param aKey (numpy array or None) If specified, elements in "a" are compared by their corresponding entry in "...
2.186207
2.246718
0.973067
if not assumeSorted: # Use a stable sort algorithm sorter = np.argsort(groupKeys, kind="mergesort") a = a[sorter] groupKeys = groupKeys[sorter] _, indices, lengths = np.unique(groupKeys, return_index=True, return_counts=True) maxValues = np.maximum.reduceat(...
def argmaxMulti(a, groupKeys, assumeSorted=False)
This is like numpy's argmax, but it returns multiple maximums. It gets the indices of the max values of each group in 'a', grouping the elements by their corresponding value in 'groupKeys'. @param a (numpy array) An array of values that will be compared @param groupKeys (numpy array) An array with the sa...
4.15093
4.36429
0.951112
# Add # [[beginningOfColumn0], # [beginningOfColumn1], # ...] # to # [0, 1, 2, ..., cellsPerColumn - 1] # to get # [beginningOfColumn0 + 0, beginningOfColumn0 + 1, ... # beginningOfColumn1 + 0, ... # ...] # then flatten it. return ((columns * cellsPerColumn).reshape((-1, 1...
def getAllCellsInColumns(columns, cellsPerColumn)
Calculate all cell indices in the specified columns. @param columns (numpy array) @param cellsPerColumn (int) @return (numpy array) All cells within the specified columns. The cells are in the same order as the provided columns, so they're sorted if the columns are sorted.
3.847792
3.815498
1.008464
sequence = [] for letter in letters: i = ord(letter) - ord('A') sequence.append(set(range(i*w,(i+1)*w))) return sequence
def letterSequence(letters, w=40)
Return a list of input vectors corresponding to sequence of letters. The vector for each letter has w contiguous bits ON and represented as a sequence of non-zero indices.
3.76383
3.118295
1.207015
if it%10==3: s = numpy.random.randint(5) if it <= switchover: if s==0: label="XABCDE" elif s==1: label="YCBEAF" elif s==2: label="GHIJKL" elif s==3: label="WABCMN" else: label="ZDBCAE" else: if s==0: label="XCBEAF" ...
def getHighOrderSequenceChunk(it, switchover=1000, w=40, n=2048)
Given an iteration index, returns a list of vectors to be appended to the input stream, as well as a string label identifying the sequence. This version generates a bunch of high order sequences. The first element always provides sufficient context to predict the rest of the elements. After switchover iteratio...
4.807491
4.592319
1.046855
noisyVecs = [] for vec in vecs: nv = vec.copy() for idx in vec: if numpy.random.random() <= percent: nv.discard(idx) nv.add(numpy.random.randint(n)) noisyVecs.append(nv) return noisyVecs
def addNoise(vecs, percent=0.1, n=2048)
Add noise to the given sequence of vectors and return the modified sequence. A percentage of the on bits are shuffled to other locations.
2.998626
2.883747
1.039836
pcols = float(pac + pic) if pcols == 0: return 0.0 else: return (pac / pcols)
def computePredictionAccuracy(pac, pic)
Given a temporal memory instance return the prediction accuracy. The accuracy is computed as 1 - (#correctly predicted cols / # predicted cols). The accuracy is 0 if there were no predicted columns.
4.981888
5.279805
0.943574
pac = tm.mmGetTracePredictedActiveColumns() pic = tm.mmGetTracePredictedInactiveColumns() upac = tm.mmGetTraceUnpredictedActiveColumns() resultsFilename = os.path.join("results", options.name+"_"+str(int(100*options.noise))+".csv") with open(resultsFilename,"wb") as resultsFile: csvWriter = csv.write...
def createReport(tm, options, sequenceString, numSegments, numSynapses)
Create CSV file with detailed trace of predictions, missed predictions, accuracy, segment/synapse growth, etc.
4.05996
3.96516
1.023908
# Kill cells if called for if options.simulation == "killer": if i == options.switchover: print "i=",i,"Killing cells for the first time!" tm.killCells(percent = options.noise) if i == options.secondKill: print "i=",i,"Killing cells again up to",options.secondNoise tm.killCells...
def killCells(i, options, tm)
Kill cells as appropriate
4.984075
4.939836
1.008956
table = PrettyTable(["Parameter name", "Value", ]) table.add_row(["columnDimensions", tm.getColumnDimensions()]) table.add_row(["cellsPerColumn", tm.getCellsPerColumn()]) table.add_row(["activationThreshold", tm.getActivationThreshold()]) table.add_row(["minThreshold", tm.getMinThreshold()]) table.add_r...
def printTemporalMemory(tm, outFile)
Given an instance of TemporalMemory, print out the relevant parameters
2.719948
2.66326
1.021285
print >>outFile, "TM parameters:" printTemporalMemory(tm, outFile) print >>outFile, "Experiment parameters:" for k,v in options.__dict__.iteritems(): print >>outFile, " %s : %s" % (k,str(v)) outFile.flush()
def printOptions(options, tm, outFile)
Pretty print the set of options
3.632389
3.649803
0.995229
exp = L4L2Experiment( "basic_continuous", numCorticalColumns=2 ) objects = createObjectMachine( machineType="continuous", numInputBits=21, sensorInputSize=1024, externalInputSize=1024, numCorticalColumns=2, ) objects.addObject(Sphere(radius=20), name="sphere") objects.addObj...
def runBasic(noiseLevel=None, profile=False)
Runs a basic experiment on continuous locations, learning a few locations on four basic objects, and inferring one of them. This experiment is mostly used for testing the pipeline, as the learned locations are too random and sparse to actually perform inference. Parameters: ---------------------------- @p...
5.339211
5.172245
1.032281
columnNumber = np.product(sp.getColumnDimensions()) fig, ax = plt.subplots(nrows=4, ncols=4) for rowI in range(4): for colI in range(4): col = np.random.randint(columnNumber) connectedSynapses = np.zeros((nDim1*nDim2,), dtype=uintType) sp.getConnectedSynapses(col, connectedSynapses) ...
def plotReceptiveFields(sp, nDim1=8, nDim2=8)
Plot 2D receptive fields for 16 randomly selected columns :param sp: :return:
2.964285
2.912522
1.017773
numInputVector, inputSize = inputVectors.shape columnNumber = np.prod(sp.getColumnDimensions()) boostFactorsTrace = np.zeros((columnNumber, numInputVector)) activeDutyCycleTrace = np.zeros((columnNumber, numInputVector)) minActiveDutyCycleTrace = np.zeros((columnNumber, numInputVector)) for i in range(nu...
def plotBoostTrace(sp, inputVectors, columnIndex)
Plot boostfactor for a selected column Note that learning is ON for SP here :param sp: sp instance :param inputVectors: input data :param columnIndex: index for the column of interest
2.223404
2.322222
0.957447
return [exp for exp in results if any(map(lambda v: v in exp, filter))]
def filterResults(results, filter)
Filter results containing the given condition :param results: list of experiments returned by `suite.get_exps` :param filter: list of conditions on the experiment parameters. For example: ["dropout0.0", "dropout0.50"] :return: filtered results
8.201285
8.393058
0.977151
formats = dict() results = [] for i in xrange(len(experiments)): path = suite.get_exp(experiments[i])[0] data = suite.get_exps(path=path) if filter is not None: data = filterResults(data, filter) # Format Linear Noise curve if len(data) > 1: format = {exp: { "label": "{...
def configureNoisePlot(suite, experiments, labels, linestyles, marker, filter=None)
Load experiment results anc configure the "Noise curve" Plot :param suite: The configured experiment suite. Must call `parse_opt` and ` parse_cfg` before calling this functions :param experiments: list containing the experiments to load :param experiments: list containing the experiments to load ...
2.963937
2.93164
1.011016
results = defaultdict(dict) formats = dict() for i in xrange(len(experiments)): experiment = experiments[i] formats[experiment] = {"label": labels[i], "linestyle": linestyles[i]} path = suite.get_exp(experiment)[0] data = suite.get_exps(path=path) for exp in data: dropout = suite.get...
def configureDropoutByTotalCorrectPlot(suite, experiments, labels, linestyles)
Load experiment results anc configure the "Dropout By Total Correct" Plot :param suite: The configured experiment suite. Must call `parse_opt` and ` parse_cfg` before calling this functions :param experiments: list containing the experiments to load :param labels: list containing the plot labels f...
3.98737
3.668045
1.087056
datadir = suite.cfgparser.defaults()["datadir"] transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) dataset = datasets.MNIST(datadir, train=False, download=True, transform=transform) num_noise = len...
def plotImagesWithNoise(suite, noise_values, plotPath)
Plot Sample MNIST images with noise :param suite: The configured experiment suite. Must call `parse_opt` and ` parse_cfg` before calling this functions :param noise: list of noise values to plot
2.612351
2.557193
1.02157
randomSDRs = np.zeros((numSDR, numDims), dtype=uintType) indices = np.array(range(numDims)) np.random.seed(seed) for i in range(numSDR): sparsity = np.random.random() * (maxSparsity - minSparsity) + minSparsity numActiveInputBits = int(sparsity * numDims) randomIndices = np.random.permutation(ind...
def generateRandomSDRVaryingSparsity(numSDR, numDims, minSparsity, maxSparsity, seed=42)
Generate a set of random SDRs with varying sparsity :param numSDR: number of SDRs :param numDims: length of SDRs :param minSparsity: minimum sparsity :param maxSparsity: maximum sparsity :param seed:
2.402207
2.684201
0.894943
cellTrace = copy.deepcopy(self._mmTraces[activityType].data) for i in xrange(len(cellTrace)): cellTrace[i] = self.getCellIndices(cellTrace[i]) return self.mmGetCellTracePlot(cellTrace, self.numberOfCells(), activityType, title, showReset, ...
def mmGetCellActivityPlot(self, title="", showReset=False, resetShading=0.25, activityType="activeCells")
Returns plot of the cell activity. @param title (string) an optional title for the figure @param showReset (bool) if true, the first set of cell activities after a reset will have a gray background @param resetShading (float) if showReset is true, this fl...
5.179843
5.898524
0.878159
epoch = next(self._all_epochs) folder = os.path.join(self._root, str(epoch), self._subset) self.data = [] silence = None gc.disable() for filename in os.listdir(folder): command = os.path.splitext(os.path.basename(filename))[0] with open(os.path.join(folder, filename), "r") as...
def next_epoch(self)
Load next epoch from disk
3.914953
3.841631
1.019086
nclasses = len(self.classes) count = np.ones(nclasses) for item in self.data: count[item[1]] += 1 N = float(sum(count)) weight_per_class = N / count weight = np.zeros(len(self.data)) for idx, item in enumerate(self.data): weight[idx] = weight_per_class[item[1]] return ...
def make_weights_for_balanced_classes(self)
adopted from https://discuss.pytorch.org/t/balanced-sampling-between-classes-with-torchvision-dataloader/2703/3
2.176901
2.046193
1.063878
# Validate by checking for the training 'silence.pkl' on the given epoch # This file is unique to our pre-processed dataset generated by 'process_dataset.py' return os.path.exists(os.path.join(folder, str(epoch), "train", "silence.pkl"))
def isValid(folder, epoch=0)
Check if the given folder is a valid preprocessed dataset
8.915192
8.340394
1.068917
if self.zombiePermutation is None: self.zombiePermutation = numpy.random.permutation(self.numberOfCells()) self.numDead = int(round(percent * self.numberOfCells())) if self.numDead > 0: self.deadCells = set(self.zombiePermutation[0:self.numDead]) else: self.deadCells = set() ...
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.
3.64348
3.382746
1.077078
start = self.cellsPerColumn * column # Strip out destroyed cells before passing along to base _burstColumn() cellsForColumn = [cellIdx for cellIdx in xrange(start, start + self.cellsPerColumn) if cellIdx not in self.deadCells] ret...
def burstColumn(self, column, columnMatchingSegments, prevActiveCells, prevWinnerCells, learn)
Activates all of the cells in an unpredicted active column, chooses a winner cell, and, if learning is turned on, learns on one segment, growing a new segment if necessary. @param column (int) Index of bursting column. @param columnMatchingSegments (iter) Matching segments in this column, or N...
6.800851
7.301071
0.931487
columnCasualties = numpy.zeros(self.numberOfColumns()) for cell in self.deadCells: col = self.columnForCell(cell) columnCasualties[col] += 1 for col in range(self.numberOfColumns()): print col, columnCasualties[col]
def printDeadCells(self)
Print statistics for the dead cells
3.764466
3.758756
1.001519
try: print("\nStarting iteration",iteration) t1 = time.time() ret = {} # Update learning rate using learning rate scheduler if configured if self.lr_scheduler is not None: # ReduceLROnPlateau lr_scheduler step should be called after validation, # all other lr_sche...
def iterate(self, params, repetition, iteration)
Called once for each training iteration (== epoch here).
3.957766
3.903016
1.014027
# Callback used to log information on every batch def log(model, batch_idx): if batch_idx % params["log_interval"] == 0: entropy = model.entropy() print("logging: {} learning iterations, entropy: {} / {}".format( model.getLearningIterations(), float(entropy), model.maxEntro...
def train(self, params, epoch)
Train one epoch of this model by iterating through mini batches. An epoch ends after one pass through the training set, or if the number of mini batches exceeds the parameter "batches_in_epoch".
4.468987
4.349415
1.027492
self._unionSDR = numpy.zeros(shape=(self._numInputs,)) self._activeCellsHistory = []
def reset(self)
Reset Union Pooler, clear active cell history
45.933907
17.367531
2.644815
self._activeCellsHistory.append(activeCells) if len(self._activeCellsHistory) > self._historyLength: self._activeCellsHistory.pop(0) self._unionSDR = numpy.zeros(shape=(self._numInputs,)) if (len(self._activeCellsHistory) >= self._minHistory) or forceOutput: for i in self._activeCellsH...
def updateHistory(self, activeCells, forceOutput=False)
Computes one cycle of the Union Pooler algorithm. Return the union SDR Parameters: ---------------------------- @param activeCells: A list that stores indices of active cells @param forceOutput: if True, a union will be created without regard to minHistory
3.506581
3.057123
1.14702
if isinstance(inputVector, numpy.ndarray): if inputVector.size == self._numInputs: activeBits = numpy.where(inputVector)[0] else: raise ValueError( "Input vector dimensions don't match. Expecting %s but got %s" % ( self._numInputs, inputVector.size)) elif i...
def unionIntoArray(self, inputVector, outputVector, forceOutput=False)
Create a union of the inputVector and copy the result into the outputVector Parameters: ---------------------------- @param inputVector: The inputVector can be either a full numpy array containing 0's and 1's, or a list of non-zero entry indices @param ou...
3.523139
3.08751
1.141094
sparsity = numpy.sum(self._unionSDR) / self._numInputs return sparsity
def getSparsity(self)
Return the sparsity of the current union SDR
17.338726
7.186763
2.412592
path, params, minWeight, minDutycycle, position = args device = torch.device("cuda" if torch.cuda.is_available() else "cpu") datadir = os.path.join(params["datadir"], "speech_commands") testDataDir = os.path.join(datadir, "test") # Initialize speech test dataset for this experiment n_mels = 32 testF...
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.652335
3.494068
1.045296
plt.figure() axes = table.T.plot(subplots=True, sharex=True, grid=True, legend=True, title=title, figsize=(8, 11)) # Use fixed scale for "accuracy" accuracy = next(ax for ax in axes if ax.lines[0].get_label() == 'accuracy') accuracy.set_ylim(0.0, 1.0) plt.savefig(plotPath) plt.c...
def plotDataframe(table, title, plotPath)
Plot Panda dataframe. :param table: Panda dataframe returned by :func:`analyzeWeightPruning` :type table: :class:`pandas.DataFrame` :param title: Plot title :type title: str :param plotPath: Plot full path :type plotPath: str
4.014184
4.396131
0.913117
tables = pool.map(analyzeWeightPruning, args) merged = pd.concat(tables, axis=1).sort_index(axis=1) filename = "{}_{}".format(name, expName) plotDataframe(merged, filename, "{}.pdf".format(filename)) print() print(filename) print(tabulate(merged, headers='keys', tablefmt='fancy_grid', ...
def run(pool, expName, name, args)
Runs :func:`analyzeWeightPruning` in parallel and save the results :param pool: multiprocessing pool :param expName: Experiment name :param name: File/Plot name (i.e. 'weight_prunning') :param args: Argument list to be passed to :func:`analyzeWeightPruning` :return: panda dataframe with all the results
4.823578
4.349695
1.108946
files = os.listdir(src_folder) os.mkdir("unused") for name in files: full_path = os.path.join(src_folder, name) if os.path.isdir(full_path): if not( name in categories or name == "_background_noise_"): newPath = os.path.join("unused", name) print("moving: ", full_path, "-->", newP...
def remove_unused_directories(src_folder, categories)
list all directories. Remove all that are not in categories list (excluding background noise) :param src_folder: :param categories: :return:
2.798588
2.634998
1.062083
if isinstance(m, SparseWeightsBase): _, inputSize = m.module.weight.shape fan = int(inputSize * m.weightSparsity) gain = nn.init.calculate_gain('leaky_relu', math.sqrt(5)) std = gain / np.math.sqrt(fan) bound = math.sqrt(3.0) * std # Calculate uniform bounds from standard deviation nn.init...
def normalizeSparseWeights(m)
Initialize the weights using kaiming_uniform initialization normalized to the number of non-zeros in the layer instead of the whole input size. Similar to torch.nn.Linear.reset_parameters() but applying weight sparsity to the input size
2.542136
2.372547
1.07148
dataSet = 'nyc_taxi' filePath = './data/' + dataSet + '.csv' data = pd.read_csv(filePath, header=0, skiprows=[1, 2], names=['datetime', 'value', 'timeofday', 'dayofweek']) xaxisDate = pd.to_datetime(data['datetime']) return xaxisDate
def getDatetimeAxis()
use datetime as x-axis
4.55034
4.393322
1.03574
dx = xt - xt1 dy = yt - yt1 self.minDx = min(self.minDx, dx) self.maxDx = max(self.maxDx, dx) print >>sys.stderr, "Learn: ", learn print >>sys.stderr, "Training iterations: ", self.trainingIterations print >>sys.stderr, "Test iterations: ", self.testIterations print >>sys.stderr, ...
def compute(self, xt1, yt1, xt, yt, theta1t1, theta2t1, theta1, theta2, learn)
The main function to call. If learn is False, it will print a prediction: (theta1, theta2)
2.962939
2.960613
1.000786
dxe = self.dxEncoder.encode(dx) dye = self.dyEncoder.encode(dy) ex = numpy.outer(dxe,dye) return ex.flatten().nonzero()[0]
def encodeDeltas(self, dx,dy)
Return the SDR for dx,dy
4.995172
5.292006
0.943909
# print >> sys.stderr, "encoded theta1 value = ", theta1 # print >> sys.stderr, "encoded theta2 value = ", theta2 t1e = self.theta1Encoder.encode(theta1) t2e = self.theta2Encoder.encode(theta2) # print >> sys.stderr, "encoded theta1 = ", t1e.nonzero()[0] # print >> sys.stderr, "encoded thet...
def encodeThetas(self, theta1, theta2)
Return the SDR for theta1 and theta2
2.517581
2.627945
0.958004
a = numpy.zeros(self.bottomUpInputSize) a[predictedCells] = 1 a = a.reshape((self.theta1Encoder.getWidth(), self.theta1Encoder.getWidth())) theta1PredictedBits = a.mean(axis=0).nonzero()[0] theta2PredictedBits = a.mean(axis=1).nonzero()[0] # To decode it we need to create a flattened array...
def decodeThetas(self, predictedCells)
Given the set of predicted cells, return the predicted theta1 and theta2
3.028886
2.967639
1.020638
self.reset() # print >> sys.stderr, "Bottom up: ", bottomUp # print >> sys.stderr, "ExternalInput: ",externalInput self.tm.compute(bottomUp, basalInput=externalInput, learn=False) # print >> sys.stderr, ("new active cells " + str(self.tm.getActiveCells())...
def inferTM(self, bottomUp, externalInput)
Run inference and return the set of predicted cells
4.174506
4.026449
1.036771
output = open(filename, 'wb') cPickle.dump(self.tm, output, protocol=cPickle.HIGHEST_PROTOCOL)
def save(self, filename="temp.pkl")
Save TM in the filename specified above
3.525052
2.526327
1.395327
inputFile = open(filename, 'rb') self.tm = cPickle.load(inputFile)
def load(self, filename="temp.pkl")
Save TM in the filename specified above
6.735172
3.992999
1.686745
probDist = numpy.exp(encoding) / numpy.sum(numpy.exp(encoding)) sortIdx = numpy.argsort(probDist) return sortIdx[-num:].tolist()
def classify(self, encoding, num=1)
Classify with basic one-hot local incoding
4.396517
3.877035
1.133989
if params['reset_every_training']: n = params['encoding_num'] self.net = buildNetwork(n, params['num_cells'], n, hiddenclass=LSTMLayer, bias=True, outputbias=params['output_bias'], ...
def train(self, params)
Train LSTM network on buffered dataset history After training, run LSTM on history[:-1] to get the state correct :param params: :return:
3.600427
3.22647
1.115903
if killCellPercent <= 0: return inputLayer = self.net['in'] lstmLayer = self.net['hidden0'] numLSTMCell = lstmLayer.outdim numDead = round(killCellPercent * numLSTMCell) zombiePermutation = numpy.random.permutation(numLSTMCell) deadCells = zombiePermutation[0:numDead] # rem...
def killCells(self, killCellPercent)
kill a fraction of LSTM cells from the network :param killCellPercent: :return:
2.454593
2.435522
1.00783