code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
coordinates = [random.uniform(-1, 1) * dim / 2. for dim in self.dimensions] dim = random.choice(range(self.dimension)) coordinates[dim] = self.dimensions[dim] / 2. * random.choice([-1, 1]) return coordinates
def _sampleFromFaces(self)
We start by sampling a dimension to "max out", then sample the sign and the other dimensions' values.
4.173516
3.40356
1.226221
dimensionsToChooseFrom = range(self.dimension) random.shuffle(dimensionsToChooseFrom) dim1, dim2 = dimensionsToChooseFrom[0], dimensionsToChooseFrom[1] coordinates = [random.uniform(-1, 1) * dim / 2. for dim in self.dimensions] coordinates[dim1] = self.dimensions[dim1] / 2. * random.choice([-1,...
def _sampleFromEdges(self)
We start by sampling dimensions to "max out", then sample the sign and the other dimensions' values.
2.559247
2.245201
1.139874
coordinates = [ self.dimensions[0] / 2. * random.choice([-1, 1]), self.dimensions[1] / 2. * random.choice([-1, 1]), self.dimensions[2] / 2. * random.choice([-1, 1]), ] return coordinates
def _sampleFromVertices(self)
We start by sampling dimensions to "max out", then sample the sign and the other dimensions' values.
2.637494
2.489786
1.059325
fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # generate cylinder x = np.linspace(- self.dimensions[0]/2., self.dimensions[0]/2., numPoints) y = np.linspace(- self.dimensions[1]/2., self.dimensions[1]/2., numPoints) z = np.linspace(- self.dimensions[2]/2., self.dimensions[2...
def plot(self, numPoints=100)
Specific plotting method for boxes. Only supports 3-dimensional objects.
1.514041
1.499041
1.010007
truthyFeature = self.contains(location) if not truthyFeature: return self.EMPTY_FEATURE elif truthyFeature=='face': return self.FLAT elif truthyFeature=='vertex': return self.POINTY elif truthyFeature=="edge": return self.EDGE elif truthyFeature=="surface": ret...
def getFeatureID(self, location)
Returns the feature index associated with the provided location. In the case of a sphere, it is always the same if the location is valid.
4.512386
4.436668
1.017066
for vertex in self.vertices: V = np.array((vertex['x'], vertex['y'], vertex['z'])).T if np.allclose(location, V, rtol=1.e-3): return "vertex" for face in self.faces: edges = np.choose(np.array(list(combinations(range(3),2))), self.vertices[face]) for edge in edges: i...
def contains(self, location)
Checks that the provided point is on the model (object).
3.852931
3.624126
1.063134
if feature == "surface": return self.sampleLocationFromFeature('face') # Temporary workaround for surfaces elif feature=="face": indx = self.rng.choice(range(self.faces.count)) rndFace = self.faces[indx] return self._sampleLocationOnFace(rndFace) elif feature == "edge": i...
def sampleLocationFromFeature(self, feature)
Samples a location from the provided specific feature. TODO surface feature is not handled correctly. forwarded to sample from face instead.
3.276244
2.989363
1.095967
try: import pyqtgraph as pg import pyqtgraph.multiprocess as mp import pyqtgraph.opengl as gl except ImportError as e: print("PyQtGraph needs to be installed.") return (None, None, None, None, None) class PlyVisWindow: def __init__(self): self.proc =...
def visualize(self, numPoints=100)
Visualization utility for models. Helps to debug the math and logic. Helps to monitor complex objects with difficult to define boundaries. Only supports 3-dimensional objects. TODO: center the objects using scale, rotate and translate operations on mesh objects.
3.266839
3.243906
1.007069
predictedField = SWARM_CONFIG['inferenceArgs']['predictedField'] data = pd.read_csv(filePath, header=0, skiprows=[1,2]) predictedFieldVals = data[predictedField].astype('float') firstDifference = predictedFieldVals.diff() data[predictedField] = firstDifference inputFile = open(filePath, "...
def calculateFirstDifference(filePath, outputFilePath)
Create an auxiliary data file that contains first difference of the predicted field :param filePath: path of the original data file
3.53739
3.575668
0.989295
if name is None: name = len(self.objects) sequence = [] for f in featureIndices: sequence += [(0, f,)] self.objects[name] = sequence
def addObject(self, featureIndices, name=None)
Adds a sequence (list of feature indices) to the Machine.
6.407701
5.152197
1.243683
for _ in xrange(numSequences): self.addObject( [numpy.random.randint(0, self.numFeatures) for _ in xrange(sequenceLength)] )
def createRandomSequences(self, numSequences, sequenceLength)
Creates a set of random sequences, each with sequenceLength elements, and adds them to the machine.
7.411317
6.980832
1.061667
sensations = {} for col in xrange(self.numColumns): locationID, featureID = pairs[col] # generate random location if requested if includeRandomLocation: locationID = random.randint(0, self.numLocations-1) location = self.locations[col][locationID] # generate union ...
def _getSDRPairs(self, pairs, noise=None, includeRandomLocation=False)
This method takes a list of (location, feature) index pairs (one pair per cortical column), and returns a sensation dict in the correct format, adding noise if necessary.
2.678652
2.491953
1.074921
if pattern is None: return None # Bits that could be noise. These can't be from the original set. candidateBits = list(set(range(inputSize)) - set(pattern)) random.shuffle(candidateBits) newBits = set() for bit in pattern: if random.random() < noiseLevel: newBits.add(c...
def _addNoise(self, pattern, noiseLevel, inputSize)
Adds noise to the given pattern and returns the new one. A noiseLevel of 0.1 means that 10% of the ON bits will be replaced by other randomly chosen ON bits. The returned SDR will still contain the same number of bits.
4.278103
3.991843
1.071711
size = self.sensorInputSize bits = self.numInputBits self.features = [] for _ in xrange(self.numColumns): self.features.append( [self._generatePattern(bits, size) for _ in xrange(self.numFeatures)] )
def _generateFeatures(self)
Generates a pool of features to be used for the experiments. For each index, numColumns SDR's are created, as locations for the same feature should be different for each column.
6.787313
6.018703
1.127704
objectA = zip(range(10), range(10)) objectB = [(0, 0), (2, 2), (1, 1), (1, 4), (4, 2), (4, 1)] objectC = [(0, 0), (1, 1), (3, 1), (0, 1)] return [objectA, objectB, objectC]
def createThreeObjects()
Helper function that creates a set of three objects used for basic experiments. :return: (list(list(tuple)) List of lists of feature / location pairs.
2.74981
2.727993
1.007997
exp = L4L2Experiment( "shared_features", enableLateralSP=True, enableFeedForwardSP=True ) pairs = createThreeObjects() objects = createObjectMachine( machineType="simple", numInputBits=20, sensorInputSize=1024, externalInputSize=1024 ) for object in pairs: objects.addObje...
def runSharedFeatures(noiseLevel=None, profile=False)
Runs a simple experiment where three objects share a number of location, feature pairs. Parameters: ---------------------------- @param noiseLevel (float) Noise level to add to the locations and features during inference @param profile (bool) If True, the network will be profil...
9.614019
9.014836
1.066466
if missingLoc is None: missingLoc = {} exp = L4L2Experiment( "uncertain_location", enableLateralSP = True, enableFeedForwardSP=True ) pairs = createThreeObjects() objects = createObjectMachine( machineType="simple", numInputBits=20, sensorInputSize=1024, externalInputSize=...
def runUncertainLocations(missingLoc=None, profile=False)
Runs the same experiment as above, with missing locations at some timesteps during inference (if it was not successfully computed by the rest of the network for example). @param missingLoc (dict) A dictionary mapping indices in the object to location index to replace with during inference...
10.26815
10.308541
0.996082
exp = L4L2Experiment( "profiling_experiment", enableLateralSP = True, enableFeedForwardSP=True ) objects = createObjectMachine( machineType="simple", numInputBits=20, sensorInputSize=1024, externalInputSize=1024 ) objects.createRandomObjects(numObjects=numObjects, numPoints=10)...
def runStretchExperiment(numObjects=25)
Generates a lot of random objects to profile the network. Parameters: ---------------------------- @param numObjects (int) Number of objects to create and learn.
12.151751
11.988327
1.013632
if boostStrength > 0.0: targetDensity = float(k) / x.size(1) boostFactors = torch.exp((targetDensity - dutyCycles) * boostStrength) boosted = x.detach() * boostFactors else: boosted = x.detach() # Take the boosted version of the input x, find the top k winners. # Compute an...
def forward(ctx, x, dutyCycles, k, boostStrength)
Use the boost strength to compute a boost factor for each unit represented in x. These factors are used to increase the impact of each unit to improve their chances of being chosen. This encourages participation of more columns in the learning process. The boosting function is a curve defined as: boost...
4.011259
3.538754
1.133523
indices, = ctx.saved_tensors grad_x = torch.zeros_like(grad_output, requires_grad=True) # Probably a better way to do it, but this is not terrible as it only loops # over the batch size. for i in range(grad_output.size(0)): grad_x[i, indices[i]] = grad_output[i, indices[i]] return g...
def backward(ctx, grad_output)
In the backward pass, we set the gradient to 1 for the winning units, and 0 for the others.
3.414654
3.476353
0.982252
batchSize = x.shape[0] if boostStrength > 0.0: targetDensity = float(k) / (x.shape[1] * x.shape[2] * x.shape[3]) boostFactors = torch.exp((targetDensity - dutyCycles) * boostStrength) boosted = x.detach() * boostFactors else: boosted = x.detach() # Take the boosted version ...
def forward(ctx, x, dutyCycles, k, boostStrength)
Use the boost strength to compute a boost factor for each unit represented in x. These factors are used to increase the impact of each unit to improve their chances of being chosen. This encourages participation of more columns in the learning process. See :meth:`k_winners.forward` for more details. :p...
3.485439
3.451246
1.009907
batchSize = grad_output.shape[0] indices, = ctx.saved_tensors g = grad_output.reshape((batchSize, -1)) grad_x = torch.zeros_like(g, requires_grad=False) grad_x.scatter_(1, indices, g.gather(1, indices)) grad_x = grad_x.reshape(grad_output.shape) return grad_x, None, None, None
def backward(ctx, grad_output)
In the backward pass, we set the gradient to 1 for the winning units, and 0 for the others.
2.544587
2.559928
0.994007
fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for feature in self._FEATURES: for _ in xrange(numPoints): x, y, z = tuple(self.sampleLocationFromFeature(feature)) ax.scatter(x, y, z, marker=".") ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z')...
def plot(self, numPoints=100)
Plots the object in a 3D scatter. This method should be overriden when possible. This default behavior simply samples numPoints points from the object and plots them in a 3d scatter.
2.91613
2.837854
1.027583
numElements = len(x) s = "" for j in range(numElements): s += formatString % x[j] print s
def printSequence(x, formatString="%d")
Compact print a list or numpy array.
3.20614
3.127179
1.02525
[seqLen, numElements] = x.shape for i in range(seqLen): s = "" for j in range(numElements): s += formatString % x[i][j] print s
def printSequences(x, formatString="%d")
Print a bunch of sequences stored in a 2D numpy array.
2.913006
2.613397
1.114644
self.setRandomSeed(self.seed) self.dim = numpy.shape(self.spatialConfig)[-1] self.spatialMap = dict( zip( map(tuple, list(self.spatialConfig)), self.sensoryInputElements)) self.lengthMotorInput1D = (2*self.maxDisplacement + 1) * \ ...
def initialize(self, useRandomEncoder)
Initialize the various data structures.
5.074663
5.061616
1.002577
motorSequence = [] sensorySequence = [] sensorimotorSequence = [] currentEyeLoc = self.nupicRandomChoice(self.spatialConfig) for i in xrange(sequenceLength): currentSensoryInput = self.spatialMap[tuple(currentEyeLoc)] nextEyeLoc, currentEyeV = self.getNextEyeLocation(currentEyeLo...
def generateSensorimotorSequence(self, sequenceLength)
Generate sensorimotor sequences of length sequenceLength. @param sequenceLength (int) Length of the sensorimotor sequence. @return (tuple) Contains: sensorySequence (list) Encoded sensory input for whole sequence. motorSequence (list) ...
3.728189
3.54987
1.050233
sequenceLength = len(eyeLocs) - 1 motorSequence = [] sensorySequence = [] sensorimotorSequence = [] for i in xrange(sequenceLength): currentEyeLoc = eyeLocs[i] nextEyeLoc = eyeLocs[i+1] currentSensoryInput = self.spatialMap[currentEyeLoc] currentEyeV = nextEyeLoc - c...
def encodeSensorimotorSequence(self, eyeLocs)
Encode sensorimotor sequence given the eye movements. Sequence will have length len(eyeLocs) - 1 because only the differences of eye locations can be used to encoder motor commands. @param eyeLocs (list) Numpy coordinates describing where the eye is looking. @return (tuple) Contains: ...
2.666857
2.408164
1.107423
possibleEyeLocs = [] for loc in self.spatialConfig: shift = abs(max(loc - currentEyeLoc)) if self.minDisplacement <= shift <= self.maxDisplacement: possibleEyeLocs.append(loc) nextEyeLoc = self.nupicRandomChoice(possibleEyeLocs) eyeDiff = nextEyeLoc - currentEyeLoc retur...
def getNextEyeLocation(self, currentEyeLoc)
Generate next eye location based on current eye location. @param currentEyeLoc (numpy.array) Current coordinate describing the eye location in the world. @return (tuple) Contains: nextEyeLoc (numpy.array) Coordinate of the next eye location. eyeDiff (numpy...
6.686521
6.452107
1.036331
self.seed = seed self._random = Random() self._random.setSeed(seed)
def setRandomSeed(self, seed)
Reset the nupic random generator. This is necessary to reset random seed to generate new sequences. @param seed (int) Seed for nupic.bindings.Random.
4.534546
5.844172
0.775909
if not hasattr(motorInput, "__iter__"): motorInput = list([motorInput]) return self.motorEncoder.encode(motorInput)
def encodeMotorInput(self, motorInput)
Encode motor command to bit vector. @param motorInput (1D numpy.array) Motor command to be encoded. @return (1D numpy.array) Encoded motor command.
5.920012
6.776738
0.873579
key = self.motorEncoder.decode(motorInputPattern)[0].keys()[0] motorCommand = self.motorEncoder.decode(motorInputPattern)[0][key][1][0] return motorCommand
def decodeMotorInput(self, motorInputPattern)
Decode motor command from bit vector. @param motorInputPattern (1D numpy.array) Encoded motor command. @return (1D numpy.array) Decoded motor command.
4.7489
4.722415
1.005608
print "\nsensory coding scheme: " for loc in self.spatialConfig: sensoryElement = self.spatialMap[tuple(loc)] print sensoryElement, "%s : " % loc, printSequence(self.encodeSensoryInput(sensoryElement))
def printSensoryCodingScheme(self)
Print sensory inputs along with their encoded versions.
9.625228
8.439109
1.14055
for i in range(-self.maxDisplacement, self.maxDisplacement+1): next = vec + [i] if n == 1: print '{:>5}\t'.format(next), " = ", printSequence(self.encodeMotorInput(next)) else: self.build(n-1, next)
def build(self, n, vec)
Recursive function to help print motor coding scheme.
6.892307
5.785554
1.191296
sampleSize = int(1.5 * numInputBits) if numInputBits == 20: activationThreshold = 18 minThreshold = 18 elif numInputBits == 10: activationThreshold = 8 minThreshold = 8 else: activationThreshold = int(numInputBits * .6) minThreshold = activationThreshold re...
def getDefaultTMParams(self, inputSize, numInputBits)
Returns a good default set of parameters to use in the TM region.
4.808485
4.714622
1.019909
numCorrectSparsity = 0.0 numCorrectClassifications = 0.0 numStats = 0.0 # For each object or sequence we classify every point or element # # A sequence element is considered correctly classified only if the number # of predictedActive cells is within a reasonable range and if the KNN ...
def averageSequenceAccuracy(self, minOverlap, maxOverlap, firstStat=0, lastStat=None)
For each object, decide whether the TM uniquely classified it by checking that the number of predictedActive cells are in an acceptable range.
6.402074
5.678325
1.127458
for region in self.TMRegions: region.setParameter("learn", False) super(L4TMExperiment, self)._unsetLearningMode()
def _unsetLearningMode(self)
Unsets the learning mode, to start inference.
16.485287
17.347216
0.950313
for region in self.TMRegions: region.setParameter("learn", True) super(L4TMExperiment, self)._setLearningMode()
def _setLearningMode(self)
Sets the learning mode.
18.244923
17.541908
1.040076
L4Representations = self.getL4Representations() L4PredictedCells = self.getL4PredictedCells() L4PredictedActiveCells = self.getL4PredictedActiveCells() L2Representation = self.getL2Representations() TMPredictedActive = self.getTMPredictedActiveCells() TMNextPredicted = self.getTMNextPredict...
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.
3.182617
3.186449
0.998797
externalInputName = "externalInput" + suffix sensorInputName = "sensorInput" + suffix L4ColumnName = "L4Column" + suffix L2ColumnName = "L2Column" + suffix TMColumnName = "TMColumn" + suffix L4Params = copy.deepcopy(networkConfig["L4Params"]) L4Params["basalInputWidth"] = networkConfig["externalInput...
def createL4L2TMColumn(network, networkConfig, suffix="")
Create a a single column containing one L4, one L2, and one TM. networkConfig is a dict that must contain the following keys (additional keys ok): { "externalInputSize": 1024, "sensorInputSize": 1024, "L4Params": { <constructor parameters for ApicalTMPairRegion> }, "L2Par...
3.155094
2.621269
1.203651
FFMpegWriter = manimation.writers['ffmpeg'] metadata = dict(title=title) writer = FFMpegWriter(fps=fps, metadata=metadata) with writer.saving(fig, filename, dpi): t = 0 while True: if update_figure(t): writer.grab_frame() t += 1...
def create_movie(fig, update_figure, filename, title, fps=15, dpi=100)
Helps us to create a movie.
2.04471
2.043815
1.000438
# 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._tm.reset() outputs["activeCells"][:] = 0 outputs["nextPredictedCells"][:] = 0 ou...
def compute(self, inputs, outputs)
Run one iteration of TM's compute.
3.073885
2.913617
1.055006
if hasattr(self, parameterName): setattr(self, parameterName, parameterValue) else: raise Exception("Unknown parameter: " + parameterName)
def setParameter(self, parameterName, index, parameterValue)
Set the value of a Spec parameter. Most parameters are handled automatically by PyRegion's parameter set mechanism. The ones that need special treatment are explicitly handled here.
3.096019
3.025696
1.023242
experimentArguments = [] # for n in [300, 500, 700, 900, 1100, 1300, 1500, 1700, 1900, 2100, 2300, # 2500, 2700, 2900, 3100, 3300, 3500, 3700, 3900]: for n in [1500, 1700, 1900, 2100]: for a in [128]: # Some parameter combinations are just not worth running! if ( a==64 and n<=1500 )...
def createExperimentArgs()
Run the basic probability of false positives experiment.
2.990853
3.014153
0.99227
experimentArguments = [] n = 6000 for a in [128]: noisePct = 0.75 while noisePct <= 0.85: noise = int(round(noisePct*a,0)) # Some parameter combinations are just not worth running! experimentArguments.append( ("./sdr_calculations2", "results_noise_10m/temp_"+str(n)+"_...
def createNoiseExperimentArgs()
Run the probability of false negatives with noise experiment.
6.50501
6.653774
0.977642
if not os.path.exists("sdrs"): os.makedirs("sdrs") filename = "sdrs/{}_{}_{}.json".format(n, w, threshold) if len(glob.glob(filename)) > 0: with open(filename, "r") as fIn: sdrs = json.load(fIn) else: begin = time.time() sdrs = enumerateDistantSDRsBruteForce(n, w, threshold) end =...
def generateMinicolumnSDRs(n, w, threshold)
Wraps enumerateDistantSDRsBruteForce, caching its result on the filesystem.
2.413715
1.962199
1.230107
assert w <= n available = np.arange(n) np.random.shuffle(available) SDRs = [] for _ in xrange(numSDRs): selected = available[:w] available = available[w:] if available.size == 0: remainderSelected = np.random.choice( np.setdiff1d(np.arange(n), selected), size=(w - sele...
def createEvenlySpreadSDRs(numSDRs, n, w)
Return a set of ~random SDRs that use every available bit an equal number of times, +- 1.
2.718391
2.76163
0.984343
minicolumns = [] for _ in xrange(numMinicolumns): contextsForCell = [set() for _ in xrange(numCells)] contexts = range(numContexts) random.shuffle(contexts) while len(contexts) > 0: eligibleCells = range(len(contextsForCell)) while len(contexts) > 0 and len(eligibleCells) > 0: ...
def carefullyCollideContexts(numContexts, numCells, numMinicolumns)
Use a greedy algorithm to choose how each minicolumn should distribute contexts between its cells. @return (list of lists of lists of ints) iContext integers for each cell, grouped by minicolumn. For example, [[[1, 3], [2,4]], [[1, 2]]] would specify that cell 0 connects to location 1 and location 3, ...
3.650424
3.893167
0.937649
print "Segments for cell", cell, ":" for seg in tm.basalConnections._cells[cell]._segments: print " ", synapses = seg._synapses for s in synapses: print "%d:%g" %(s.presynapticCell,s.permanence), print
def printSegmentForCell(tm, cell)
Print segment information for this cell
7.129744
7.132131
0.999665
reberString = '' for i in xrange(len(sequence)): index = np.where(sequence[i]==1.)[0][0] reberString += chars[index] return reberString
def sequenceToWord(sequence)
converts a sequence (one-hot) in a reber string
4.260151
2.802363
1.520199
missN = 0 for i in xrange(len(possibleOutcome)): miss = 1 for j in xrange(len(predictedOutcome)): if predictedOutcome[j] == possibleOutcome[i]: miss = 0 missN += miss fpN = 0 for i in xrange(len(predictedOutcome)): fp = 1 for j in xrange(len(possibleOutcome)): if pred...
def checkPrediction2(possibleOutcome, predictedOutcome)
:param possibleOutcome: list of all possible outcomes :param predictedOutcome: list of all predicted outomes :return missN: number of misses (a possible outcome not predicted) fpN: number of false positives (a predicted outcome is not possible to happen)
1.994572
1.708928
1.167148
######################################################################## # # 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)
Plots the convergence graph: iterations vs number of columns. Each curve shows the convergence for a given number of unique features.
4.467163
4.239516
1.053696
######################################################################## # # Accumulate all the results per column in a convergence array. # # Convergence[c,o] = how long it took it to converge with f unique features # and c columns. convergence = numpy.zeros((max(columnRange), max(objectRange) + 1)) ...
def plotConvergenceByObjectMultiColumn(results, objectRange, columnRange)
Plots the convergence graph: iterations vs number of objects. Each curve shows the convergence for a given number of columns.
4.091653
3.958462
1.033647
if len(self.queue) > 0: # Take the top element of the data queue data = self.queue.pop() else: raise Exception("RawValues: No data: queue is empty ") # Copy data into output vectors outputs["resetOut"][0] = data["reset"] outputs["dataOut"][:] = data["dataOut"]
def compute(self, inputs, outputs)
Get the next record from the queue and outputs it.
8.409822
7.489078
1.122945
self.queue.appendleft({ "dataOut": list(displacement), "reset": bool(reset) })
def addDataToQueue(self, displacement, reset=False)
Add the given displacement to the region's internal queue. Calls to compute will cause items in the queue to be dequeued in FIFO order. :param displacement: Two floats representing translation vector [dx, dy] to be passed to the linked regions via 'dataOut' :type displacement: list...
7.552688
7.9081
0.955057
currentTime = time.time() for i in xrange(len(inputSequences)): sensorPattern = inputSequences[i] inputCategory = inputCategories[i] self.runNetworkOnPattern(sensorPattern, tmLearn=tmLearn, upLearn=upLearn, ...
def runNetworkOnSequences(self, inputSequences, inputCategories, tmLearn=True, upLearn=None, classifierLearn=False, verbosity=0, progressInterval=None)
Runs Union Temporal Pooler network on specified sequence. @param inputSequences One or more sequences of input patterns. Each should be terminated with None. @param inputCategories A sequence of category representations ...
4.159519
4.255513
0.977442
activeCells = numpy.zeros(self.tm.numberOfCells()).astype(realDType) activeCells[list(self.tm.activeCellsIndices())] = 1 predictedActiveCells = numpy.zeros(self.tm.numberOfCells()).astype( realDType) predictedActiveCells[list(self.tm.predictedActiveCellsIndices())] = 1 burstingColumns =...
def getUnionTemporalPoolerInput(self)
Gets the Union Temporal Pooler input from the Temporal Memory
3.65467
3.533061
1.03442
traceData = self.tm.mmGetTraceUnpredictedActiveColumns().data resetData = self.tm.mmGetTraceResets().data countTrace = [] for x in xrange(len(traceData)): if not resetData[x]: countTrace.append(len(traceData[x])) mean = numpy.mean(countTrace) stdDev = numpy.std(countTrace) ...
def getBurstingColumnsStats(self)
Gets statistics on the Temporal Memory's bursting columns. Used as a metric of Temporal Memory's learning performance. :return: mean, standard deviation, and max of Temporal Memory's bursting columns over time
5.971946
5.495388
1.08672
numpy.random.seed(seed) possible_cluster_sizes = range(2, 10) for trial in range(num_trials): num_cluster_sizes = numpy.random.choice([1, 1, 2] + range(1, 8), 1) cluster_sizes = numpy.random.choice(possible_cluster_sizes, num_cluster_sizes, replace = False) num_cells_per_cluster_size = [numpy.ran...
def run_false_positive_experiment_correlation(seed, num_neurons = 1, a = 32, dim = 4000, num_samples = 20000, ...
Run an experiment to test the false positive rate based on the correlation between bits. Correlation is measured as the average pairwise correlation between bits for each pattern in the data (across all of the data). To generate the results shown in the false positive vs. correlation figure, we used the param...
3.204544
3.226258
0.99327
n, m = self.connections.visible_to_hidden.shape self.connections.visible_to_hidden = np.zeros((n, m)) for i in range(n): random_vector = self._random.rand(m) # norm = np.sqrt( np.sum(random_vector * random_vector) ) self.connections.visible_...
def initialize_connections(self)
Randomly initializes the visible-to-hidden connections. Each weight is independently sampled from a uniform distribution $U(0,1)$. The weights are NOT normalized!
4.090587
3.219846
1.270429
x = inputVector y = self.encode(x) active_units = np.where(y==1.)[0] if learn: self.update_statistics([y]) self.update_weights([x],[y]) activeArray[active_units] = 1. return active_units
def compute(self, inputVector, learn, activeArray)
This method resembles the primary public method of the SpatialPooler class. It takes a input vector and outputs the indices of the active columns. If 'learn' is set to True, this method also performs weight updates and updates to the activity statistics according to the respective methods imp...
5.843715
4.562922
1.280696
E = self.energy y_min = self.find_energy_minimum(E, x) return y_min
def encode(self, x)
Given an input array `x` it returns its associated encoding `y(x)`, that is, a stable configuration (local energy minimum) of the hidden units while the visible units are clampled to `x`. Note that NO learning takes place.
13.518936
9.16186
1.475567
X = inputBatch encode = self.encode Y = np.array([ encode(x) for x in X]) return Y
def encode_batch(self, inputBatch)
Encodes a whole batch of input arrays, without learning.
6.370936
6.005524
1.060846
y = self.encode(x) self.update_statistics([y]) self.update_weights([x],[y]) return y
def learn(self, x)
Encodes an input array, and performs weight updates and updates to the activity statistics according to the respective methods implemented below.
7.587844
5.7842
1.311823
X = inputBatch Y = self.encode_batch(X) self.update_statistics(Y) self.update_weights(X,Y) return Y
def learn_batch(self, inputBatch)
Encodes a whole batch of input arrays, and performs weight updates and updates to the activity statistics according to the respective methods implemented below.
5.27903
3.91919
1.34697
Y = activityVectors n = self.output_size A = np.zeros((n, n)) batchSize = len(Y) for y in Y: active_units = np.where( y == 1 )[0] for i in active_units: for j in active_units: A[i,j] += 1. A = A/batchS...
def update_statistics(self, activityVectors)
Updates the variable that maintains exponential moving averages of individual and pairwise unit activiy
3.672479
3.414017
1.075706
r E = energy y = np.zeros(self.output_size) min_so_far = E(x, y) for _ in range(maxSteps): neighbours = self.get_neighbours(y) energies = np.array([ E(x,z) for z in neighbours ]) steepest_descent = np.argmin(energies) ...
def find_energy_minimum(self, energy, x, maxSteps=40000)
r""" Naive hill descend algorithm: Starts at $y=0$ and iteratively chooses the direction of steepest descent from a neighbourhood of the current position. If not indicated otherwise the neighbourhood consists of elements at Hamming distance less than or equal to $1$.
3.206179
3.100343
1.034137
r onBits = np.where( y == 1. )[0] offBits = np.where( y == 0. )[0] neighbours = [y.copy()] for on in onBits: z = y.copy() z[on] = 0. neighbours.append(z) for off in offBits: z = y.copy() z[off] ...
def get_neighbours(y)
r""" Returns a neigbourhood $N$ of $y$ consisting of elements that share $|y| - 1$ bits with $y$, i.e $$ N(y) = \{ x : x^T \cdot y = |y| - 1 \} $$
2.789108
2.80486
0.994384
r pooler = self W = pooler.connections.visible_to_hidden H = pooler.connections.hidden_to_hidden b = pooler.connections.hidden_bias n, m = pooler.output_size, pooler.input_size w = pooler.code_weight size_penalty = 0 if dot(y,y) <= w...
def energy(self, x, y)
r""" Numenta's energy with an additional term (the H-term) to decorrelate pairwise column activity: $$ E(x,y) = - \sum_i y_i \cdot \exp( - b_i - \sum_j H_{ij} \ y_j ) \cdot (\sum_j W_{ij} \ x_j ) + S(y) $$ where the size size penalty is given by $$ ...
8.110684
4.635683
1.74962
# Initialize weights in the typical fashion. w = torch.Tensor(outputSize, inputSize) stdv = 1. / math.sqrt(w.size(1)) w.data.uniform_(-stdv, stdv) numZeros = int(round((1.0 - weightSparsity) * inputSize)) outputIndices = np.arange(outputSize) inputIndices = np.array([np.random.permutation(inputSize)[...
def getSparseWeights(weightSparsity, inputSize, outputSize)
Return a randomly initialized weight matrix Size is outputSize X inputSize, with sparsity weightSparsity%
2.742242
2.894689
0.947336
overlaps = v.matmul(w.t()) # Plot histogram of overlaps bins = np.linspace(float(overlaps.min()), float(overlaps.max()), 28) plt.hist(overlaps, bins, alpha=0.5, label='All cols') plt.legend(loc='upper right') plt.xlabel("Overlap scores") plt.ylabel("Frequency") plt.title(title) plt.savefig(base+"_...
def plotOverlapHistogram(v, w, title, base="random")
Given a vector v, compute the overlap with the weight matrix w and save the histogram of overlaps.
3.397432
3.186455
1.066211
for i,v in enumerate(vList): if i==0: col = "m" label = "Random vector" else: col="c" label = "" if i==1: label="Test images" # Get a sorted list of overlap values, in decreasing order overlaps = v.matmul(w.t()) sortedOverlaps = overlaps.sort()[0].tolist()[0][::-1]...
def plotOverlaps(vList, w, base="random", k=20)
Given a list of vectors v, compute the overlap of each with the weight matrix w and plot the overlap curves.
5.00751
4.769196
1.049969
weights = weights.numpy() weights = weights.reshape(28*28*500) bins = np.linspace(-0.1, 0.1, 50) nz = weights.nonzero()[0] nzw = weights[nz] print("zero before and after:", (weights==0).sum(), (nzw==0).sum()) print("Small weights:", (abs(nzw)>0.0).sum(), (abs(nzw)<0.01).sum(), (abs(nzw)<0.02).sum(), (a...
def analyzeWeightDistribution(weights,base)
Plot histogram of non-zero weight values.
3.243419
3.101432
1.045781
model = torch.load(modelName) model.eval() analyzeWeightDistribution(model.l1.weight.data, base)
def analyzeModelWeightDistribution(modelName,base)
Plot histogram of non-zero weight values.
5.933491
5.912217
1.003598
if self.activationFunction is "sig": H = sigmoidActFunc(features, self.inputWeights, self.bias) else: print " Unknown activation function type" raise NotImplementedError return H
def calculateHiddenLayerActivation(self, features)
Calculate activation level of the hidden layer :param features feature matrix with dimension (numSamples, numInputs) :return: activation level (numSamples, numHiddenNeurons)
9.295233
10.280284
0.904181
assert features.shape[0] == targets.shape[0] assert features.shape[1] == self.inputs assert targets.shape[1] == self.outputs # randomly initialize the input->hidden connections self.inputWeights = np.random.random((self.numHiddenNeurons, self.inputs)) self.inputWeights = self.inputWeights ...
def initializePhase(self, features, targets)
Step 1: Initialization phase :param features feature matrix with dimension (numSamples, numInputs) :param targets target matrix with dimension (numSamples, numOutputs)
3.523789
3.450581
1.021216
(numSamples, numOutputs) = targets.shape assert features.shape[0] == targets.shape[0] H = self.calculateHiddenLayerActivation(features) Ht = np.transpose(H) try: self.M -= np.dot(self.M, np.dot(Ht, np.dot( pinv(np.eye(numSamples) + np.dot(H, np.dot(self.M...
def train(self, features, targets)
Step 2: Sequential learning phase :param features feature matrix with dimension (numSamples, numInputs) :param targets target matrix with dimension (numSamples, numOutputs)
3.915092
3.967425
0.98681
H = self.calculateHiddenLayerActivation(features) prediction = np.dot(H, self.beta) return prediction
def predict(self, features)
Make prediction with feature matrix :param features: feature matrix with dimension (numSamples, numInputs) :return: predictions with dimension (numSamples, numOutputs)
9.572327
8.712815
1.098649
''' %This function returns an envelope for network of size N; The envelope can %either be suppressive (periodic = 0) or flat and equal to one (periodic = 1) ''' kappa = 0.3; # controls width of main body of envelope a0 = 30; # contrls steepness of envelope if periodic==0: A = np.zeros(N) ...
def create_envelope(periodic,N)
%This function returns an envelope for network of size N; The envelope can %either be suppressive (periodic = 0) or flat and equal to one (periodic = 1)
6.412524
3.475876
1.844866
externalInputName = "externalInput" + suffix sensorInputName = "sensorInput" + suffix L4ColumnName = "L4Column" + suffix L2ColumnName = "L2Column" + suffix if networkConfig["externalInputSize"] > 0: network.addRegion( externalInputName, "py.RawSensor", json.dumps({"outputWidth": net...
def createCombinedSequenceColumn(network, networkConfig, suffix="")
Create a a single column containing one L4, one L2, and one TM. networkConfig is a dict that must contain the following keys (additional keys ok): { "externalInputSize": 1024, "sensorInputSize": 1024, "L2Params": { <constructor parameters for ColumnPoolerRegion> }, "TMPar...
3.533852
2.977036
1.187037
# Create function arguments for every possibility args = [] for c in reversed(numColumns): for o in reversed(numObjects): for l in numLocations: for f in numFeatures: for n in networkType: for p in longDistanceConnectionsRange: for t in range(nTrials): ...
def runExperimentPool(numObjects, numLocations, numFeatures, numColumns, networkType=["MultipleL4L2Columns"], longDistanceConnectionsRange = [0.0], numWorkers=7, nTri...
Allows you to run a number of experiments using multiple processes. For each parameter except numWorkers, pass in a list containing valid values for that parameter. The cross product of everything is run, and each combination is run nTrials times. Returns a list of dict containing detailed results from each ex...
2.597448
2.671392
0.97232
######################################################################## # # Accumulate all the results per column in a convergence array. # # Convergence[f, c, t] = how long it took it to converge with f unique # features, c columns and topology t. convergence = numpy.zeros((max(featureRange), max(c...
def plotConvergenceByColumnTopology(results, columnRange, featureRange, networkType, numTrials)
Plots the convergence graph: iterations vs number of columns. Each curve shows the convergence for a given number of unique features.
4.019226
3.908194
1.02841
######################################################################## # # Accumulate all the results per column in a convergence array. # # Convergence[f, c, t] = how long it took it to converge with f unique # features, c columns and topology t. convergence = numpy.zeros((len(featureRange), len(lo...
def plotConvergenceByDistantConnectionChance(results, featureRange, columnRange, longDistanceConnectionsRange, numTrials)
Plots the convergence graph: iterations vs number of columns. Each curve shows the convergence for a given number of unique features.
4.114738
3.969478
1.036594
(n, d) = Y.shape A = np.expand_dims(Y, axis=1) * np.expand_dims(Y, axis=0) assert(A.shape == (n, n, d)) Q = np.mean(A, axis=2) Q[np.where(Q == 0.)] = 0.000001 assert(P.shape == Q.shape) return beta*P + (1-beta)*Q
def update_statistics(Y, P, beta=0.9)
Args ---- Y: 2d array whose columns encode the activity of the output units P: 2d array encoding the pairwise average activity of the output units Returns ------- The updated average activities
2.88484
2.898262
0.995369
d = X.shape[1] size = minibatch_size minibatches = [] if Y is None: Y = np.zeros((1, d)) np.random.seed(seed) perm = np.random.permutation(d) for t in range(0, d, size): subset = perm[t: t+size] minibatches.append((X[:, subset], Y[:, subset])) return minibatches
def random_mini_batches(X, Y, minibatch_size, seed=None)
Compute a list of minibatches from inputs X and targets Y. A datapoint is expected to be represented as a column in the data matrices X and Y.
3.31505
2.827817
1.1723
if not os.path.exists("traces"): os.makedirs("traces") locationConfigs = [] for i in xrange(5): scale = 10.0 * (math.sqrt(2) ** i) for _ in xrange(4): orientation = np.radians(random.gauss(7.5, 7.5)) orientation = random.choice([orientation, -orientation]) locationConfigs.appen...
def doPointsExperiment(cellDimensions, cellCoordinateOffsets)
Learn a set of objects. Then try to recognize each object. Output an interactive visualization. @param cellDimensions (pair) The cell dimensions of each module @param cellCoordinateOffsets (sequence) The "cellCoordinateOffsets" parameter for each module
5.626193
5.759933
0.976781
startLocation = np.array(startLocation) direction = np.array(direction) barMovie = [] for step in range(steps): barCenter = startLocation + step * direction barMovie.append(getBar(imageSize, barCenter, barHalfLength, ori...
def getMovingBar(startLocation, direction, imageSize=(20, 20), steps=5, barHalfLength=3, orientation='horizontal')
Generate a list of bars :param startLocation: (list) start location of the bar center, e.g. (10, 10) :param direction: direction of movement, e.g., (1, 0) :param imageSize: (list) number of pixels on horizontal and vertical dimension :param steps: (int) number of steps :par...
2.828276
3.21109
0.880784
(nX, nY) = imageSize (xLoc, yLoc) = barCenter bar = np.zeros((nX, nY), dtype=uintType) if orientation == 'horizontal': xmin = max(0, (xLoc - barHalfLength)) xmax = min(nX - 1, (xLoc + barHalfLength + 1)) bar[xmin:xmax, yLoc] = 1 elif orientation == 'vertical': ymin = max(0, (yLoc - barHalfL...
def getBar(imageSize, barCenter, barHalfLength, orientation='horizontal')
Generate a single horizontal or vertical bar :param imageSize a list of (numPixelX. numPixelY). The number of pixels on horizontal and vertical dimension, e.g., (20, 20) :param barCenter: (list) center of the bar, e.g. (10, 10) :param barHalfLength (int) half length of the bar....
1.922351
2.000701
0.960838
randomSDRs = np.zeros((numSDR, numDims), dtype=uintType) indices = np.array(range(numDims)) np.random.seed(seed) for i in range(numSDR): randomIndices = np.random.permutation(indices) activeBits = randomIndices[:numActiveInputBits] randomSDRs[i, activeBits] = 1 return randomSDRs
def generateRandomSDR(numSDR, numDims, numActiveInputBits, seed=42)
Generate a set of random SDR's @param numSDR: @param nDim: @param numActiveInputBits:
2.550469
2.873818
0.887485
nonZeroX1 = np.count_nonzero(x1) nonZeroX2 = np.count_nonzero(x2) percentOverlap = 0 minX1X2 = min(nonZeroX1, nonZeroX2) if minX1X2 > 0: overlap = float(np.dot(x1.T, x2)) percentOverlap = overlap / minX1X2 return percentOverlap
def percentOverlap(x1, x2)
Computes the percentage of overlap between vectors x1 and x2. @param x1 (array) binary vector @param x2 (array) binary vector @param size (int) length of binary vectors @return percentOverlap (float) percentage overlap between x1 and x2
2.604458
2.71214
0.960297
if vectorType == 'sparse': corruptSparseVector(inputVector, noiseLevel) elif vectorType == 'dense': corruptDenseVector(inputVector, noiseLevel) else: raise ValueError("vectorType must be 'sparse' or 'dense' ")
def addNoiseToVector(inputVector, noiseLevel, vectorType)
Add noise to SDRs @param inputVector (array) binary vector to be corrupted @param noiseLevel (float) amount of noise to be applied on the vector. @param vectorType (string) "sparse" or "dense"
2.590141
2.374957
1.090606
size = len(vector) for i in range(size): rnd = random.random() if rnd < noiseLevel: if vector[i] == 1: vector[i] = 0 else: vector[i] = 1
def corruptDenseVector(vector, noiseLevel)
Corrupts a binary vector by inverting noiseLevel percent of its bits. @param vector (array) binary vector to be corrupted @param noiseLevel (float) amount of noise to be applied on the vector.
2.031543
2.53148
0.802512
numNoiseBits = int(noiseLevel * np.sum(sdr)) if numNoiseBits <= 0: return sdr activeBits = np.where(sdr > 0)[0] inActiveBits = np.where(sdr == 0)[0] turnOffBits = np.random.permutation(activeBits) turnOnBits = np.random.permutation(inActiveBits) turnOffBits = turnOffBits[:numNoiseBits] turnOnBi...
def corruptSparseVector(sdr, noiseLevel)
Add noise to sdr by turning off numNoiseBits active bits and turning on numNoiseBits in active bits @param sdr (array) Numpy array of the SDR @param noiseLevel (float) amount of noise to be applied on the vector.
2.314077
1.957514
1.182151
columnNumber = np.prod(sp.getColumnDimensions()) numInputVector, inputSize = inputVectors.shape outputColumns = np.zeros((numInputVector, columnNumber), dtype=uintType) outputColumnsCorrupted = np.zeros((numInputVector, columnNumber), dtype=uintType) noiseLevelList = n...
def calculateOverlapCurve(sp, inputVectors)
Evalulate noise robustness of SP for a given set of SDRs @param sp a spatial pooler instance @param inputVectors list of arrays. :return:
2.871689
2.838216
1.011794
numTargets, numDims = targetOutputColumns.shape overlap = np.zeros((numTargets,)) for i in range(numTargets): overlap[i] = percentOverlap(outputColumns, targetOutputColumns[i, :]) classLabel = np.argmax(overlap) return classLabel
def classifySPoutput(targetOutputColumns, outputColumns)
Classify the SP output @param targetOutputColumns (list) The target outputs, corresponding to different classes @param outputColumns (array) The current output @return classLabel (int) classification outcome
3.887246
3.982241
0.976145
numInputVector, inputSize = inputVectors.shape if sp is None: targetOutputColumns = copy.deepcopy(inputVectors) else: columnNumber = np.prod(sp.getColumnDimensions()) # calculate target output given the uncorrupted input vectors targetOutputColumns = np.zeros((numInputVector, columnNumber), ...
def classificationAccuracyVsNoise(sp, inputVectors, noiseLevelList)
Evaluate whether the SP output is classifiable, with varying amount of noise @param sp a spatial pooler instance @param inputVectors (list) list of input SDRs @param noiseLevelList (list) list of noise levels :return:
3.499533
3.6178
0.96731
numInputVector, inputSize = inputVectors.shape numColumns = np.prod(sp.getColumnDimensions()) outputColumns = np.zeros((numInputVector, numColumns), dtype=uintType) inputOverlap = np.zeros((numInputVector, numColumns), dtype=uintType) connectedCounts = np.zeros((numColumns,), dtype=uintType) sp.getConn...
def plotExampleInputOutput(sp, inputVectors, saveFigPrefix=None)
Plot example input & output @param sp: an spatial pooler instance @param inputVectors: a set of input vectors
2.267155
2.303358
0.984282
numInputVector, inputSize = inputVectors.shape numColumns = np.prod(sp.getColumnDimensions()) outputColumns = np.zeros((numInputVector, numColumns), dtype=uintType) inputOverlap = np.zeros((numInputVector, numColumns), dtype=uintType) connectedCounts = np.zeros((numColumns, ), dtype=uintType) sp.getCon...
def inspectSpatialPoolerStats(sp, inputVectors, saveFigPrefix=None)
Inspect the statistics of a spatial pooler given a set of input vectors @param sp: an spatial pooler instance @param inputVectors: a set of input vectors
2.982633
3.08497
0.966827
entropy = - x*np.log2(x) - (1-x)*np.log2(1-x) entropy[x*(1 - x) == 0] = 0 return entropy
def binaryEntropyVectorized(x)
Calculate entropy for a list of binary random variables :param x: (numpy array) the probability of the variable to be 1. :return: entropy: (numpy array) entropy
3.102654
3.872453
0.801212
activationProb = np.mean(activeColumns, 0) if type == 'binary': totalEntropy = np.sum(binaryEntropyVectorized(activationProb)) elif type == 'renyi': totalEntropy = np.sum(renyiEntropyVectorized(activationProb)) else: raise ValueError('unknown entropy type') numberOfColumns = activeColum...
def calculateEntropy(activeColumns, type='binary')
calculate the mean entropy given activation history @param activeColumns (array) 2D numpy array of activation history @return entropy (float) mean entropy
4.584942
4.648404
0.986348