code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if seed != -1: self._random = np.random.RandomState(seed) else: self._random = np.random.RandomState()
def _seed(self, seed=-1)
Initialize the random seed
2.454509
2.201044
1.115157
n = self._outputSize m = self._inputSize self._Q = self._random.sample((n,m)) # Normalize the weights of each units for i in range(n): self._Q[i] /= np.sqrt( np.dot(self._Q[i], self._Q[i]) )
def initialize_weights(self)
Randomly initializes the visible-to-hidden connections.
5.613425
5.0085
1.12078
n = self._outputSize y = np.zeros(n) Q = self._Q W = self._W t = self._t lam = self._lambda try: y_star = np.random.sample(n) y_star = fixed_point(lambda p: expit(lam * ( np.dot(Q,x) + np.dot(W,p) - t)), ...
def encode(self, x)
Given an input array `x` it returns its associated encoding `y(x)`. Please cf. the paper for more details. Note that NO learning takes place.
6.113275
6.04693
1.010972
m = self._inputSize n = self._outputSize W = self._W Q = self._Q t = self._t alpha = self._alpha beta = self._beta gamma = self._gamma p = self._p for i in range(n): for j in range(n): ...
def update_weights(self, x, y)
Weight updates as described in the Földiák's paper.
2.708825
2.708288
1.000198
n,m = self.shape y = np.zeros(n) s = self.sparsity L = lateralConnections desiredWeight = self.codeWeight inhSignal = np.zeros(n) sortedIndices = np.argsort(overlaps, kind='mergesort')[::-1] currentWeight = 0 for i in sortedIndices: if overlaps[i] < self._stimu...
def _inhibitColumnsWithLateral(self, overlaps, lateralConnections)
Performs an experimentatl local inhibition. Local inhibition is iteratively performed on a column by column basis.
6.149565
5.989788
1.026675
oldL = self.lateralConnections newL = avgActivityPairs.copy() np.fill_diagonal(newL, 0.0) newL = newL/np.sum(newL, axis=1, keepdims=True) self.lateralConnections[:,:] = (1 - epsilon)*oldL + epsilon*newL
def _updateLateralConnections(self, epsilon, avgActivityPairs)
Sets the weights of the lateral connections based on average pairwise activity of the SP's columns. Intuitively: The more two columns fire together on average the stronger the inhibitory connection gets.
3.29382
2.938506
1.120916
if not isinstance(inputVector, np.ndarray): raise TypeError("Input vector must be a numpy array, not %s" % str(type(inputVector))) if inputVector.size != self._numInputs: raise ValueError( "Input vector dimensions don't match. Expecting %s but got %s" % ( ...
def compute(self, inputVector, learn, activeArray, applyLateralInhibition=True)
This is the primary public method of the LateralPooler class. This function takes a input vector and outputs the indices of the active columns. If 'learn' is set to True, this method also updates the permanences of the columns and their lateral inhibitory connection weights.
4.393295
4.294409
1.023027
m = self._numInputs n = self._numColumns W = np.zeros((n, m)) for i in range(self._numColumns): self.getPermanence(i, W[i, :]) return W
def feedforward(self)
Soon to be depriciated. Needed to make the SP implementation compatible with some older code.
6.41884
5.405944
1.187367
inputIndices = np.where(inputVector > 0)[0] permChanges = np.zeros(self._numInputs, dtype=realDType) permChanges.fill(-1 * self._synPermInactiveDec) permChanges[inputIndices] = self._synPermActiveInc for columnIndex in activeColumns: perm = self._permanences[columnIndex] maskPotent...
def _adaptSynapses(self, inputVector, activeColumns, overlaps)
The primary method in charge of learning. Adapts the permanence values of the synapses based on the input vector, and the chosen columns after inhibition round. Permanence values are increased for synapses connected to input bits that are turned on, and decreased for synapses connected to inputs bits th...
6.26278
5.789261
1.081793
path = suite.cfgparser.get(name, "path") path = os.path.join(path, name) touches = {} for exp in suite.get_exps(path=path): params = suite.get_params(exp) cols = params["num_cortical_columns"] features = params["num_features"] if not features in touches: touches[features] = {} tou...
def plotSensationByColumn(suite, name)
Plots the convergence graph: touches by columns.
3.428682
3.278974
1.045657
print params["name"], ":", repetition self.debug = params.get("debug", False) L2Params = json.loads('{' + params["l2_params"] + '}') L4Params = json.loads('{' + params["l4_params"] + '}') L6aParams = json.loads('{' + params["l6a_params"] + '}') # Make sure random seed is different for ea...
def reset(self, params, repetition)
Take the steps necessary to reset the experiment before each repetition: - Make sure random seed is different for each repetition - Create the L2-L4-L6a network - Generate objects used by the experiment - Learn all objects used by the experiment
3.443871
3.14487
1.095076
objectToInfer = self.objects[iteration] stats = collections.defaultdict(list) touches = self.infer(objectToInfer, stats) results = {'touches': touches} results.update(stats) return results
def iterate(self, params, repetition, iteration)
For each iteration try to infer the object represented by the 'iteration' parameter returning the number of touches required to unambiguously classify the object. :param params: Specific parameters for this iteration. See 'experiments.cfg' for list of parameters :param repetition: Cur...
8.69014
5.366867
1.61922
self.setLearning(True) for obj in self.objects: self.sendReset() previousLocation = [None] * self.numColumns displacement = [0., 0.] features = obj["features"] numOfFeatures = len(features) # Randomize touch sequences touchSequence = np.random.permutation(numOfF...
def learn(self)
Learn all objects on every column. Each column will learn all the features of every object and store the the object's L2 representation to be later used in the inference stage
5.812037
5.544649
1.048225
self.setLearning(False) self.sendReset() touches = None previousLocation = [None] * self.numColumns displacement = [0., 0.] features = objectToInfer["features"] objName = objectToInfer["name"] numOfFeatures = len(features) # Randomize touch sequences touchSequence = np.ran...
def infer(self, objectToInfer, stats=None)
Attempt to recognize the specified object with the network. Randomly move the sensor over the object until the object is recognized.
5.23973
5.139767
1.019449
L6aLearnableCells = self.getL6aLearnableCells() L6aSensoryAssociatedCells = self.getL6aSensoryAssociatedCells() L6aRepresentations = self.getL6aRepresentations() L4Representations = self.getL4Representations() L4PredictedCells = self.getL4PredictedCells() L2Representation = self.getL2Repres...
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.199705
3.194462
1.001641
halfWindowSize = int(round(float(windowSize)/2)) window_center = range(halfWindowSize, len(data)-halfWindowSize, int(round(float(halfWindowSize)/5.0))) nrmse = [] for wc in window_center: nrmse.append(NRMSE(data[wc-halfWindowSize:wc+halfWindowSize], pred[wc-halfWindowSize:wc+halfW...
def NRMSE_sliding(data, pred, windowSize)
Computing NRMSE in a sliding window :param data: :param pred: :param windowSize: :return: (window_center, NRMSE)
2.587064
2.260579
1.144425
# Create each column numCorticalColumns = networkConfig["numCorticalColumns"] for i in xrange(numCorticalColumns): networkConfigCopy = copy.deepcopy(networkConfig) randomSeedBase = networkConfigCopy["randomSeedBase"] networkConfigCopy["L2Params"]["seed"] = randomSeedBase + i networkConfigCopy[...
def createL2456Columns(network, networkConfig)
Create a network consisting of multiple L2456 columns as described in the file comments above.
2.869272
2.858686
1.003703
tm = tpregion.getSelf()._tfdr print "------------PY TemporalMemory Parameters ------------------" print "numberOfCols =", tm.columnDimensions print "cellsPerColumn =", tm.cellsPerColumn print "minThreshold =", tm.minThreshold print "activationThreshold =", tm.activ...
def printTPRegionParams(tpregion)
Note: assumes we are using TemporalMemory/TPShim in the TPRegion
6.859672
6.179527
1.110064
with tf.variable_scope(self.name, reuse=tf.AUTO_REUSE): nonZeros = int(round(input_shape[-1].value * self.sparsity)) # Create random mask with k elements set to 1, all other elements set to 0 values = tf.random_uniform(input_shape) topk, _ = tf.math.top_k(input=values, k=nonZeros, sort...
def _build(self, input_shape, dtype=tf.float32)
Called on the first iteration once the input shape is known :param input_shape: Input shape including batch size
3.277853
3.351933
0.977899
if not self._mmTransitionTracesStale: return self._mmData["predictedActiveCellsForSequence"] = defaultdict(set) self._mmTraces["predictedActiveCells"] = IndicesTrace(self, "predicted => active cells (correct)") self._mmTraces["predictedInactiveCells"] = IndicesTrace(self, "predi...
def _mmComputeTransitionTraces(self)
Computes the transition traces, if necessary. Transition traces are the following: predicted => active cells predicted => inactive cells predicted => active columns predicted => inactive columns unpredicted => active columns
2.363129
2.168403
1.089802
data = data.toDense() correlations = numpy.corrcoef(data, rowvar = False) highest_correlations = [] for row in correlations: highest_correlations += sorted(row, reverse = True)[1:threshold+1] return numpy.mean(highest_correlations)
def get_biased_correlations(data, threshold= 10)
Gets the highest few correlations for each bit, across the entirety of the data. Meant to provide a comparison point for the pairwise correlations reported in the literature, which are typically between neighboring neurons tuned to the same inputs. We would expect these neurons to be among the most correlated...
3.745681
3.459581
1.082698
patterns = [data.rowNonZeros(i)[0] for i in range(data.nRows())] dense_data = data.toDense() correlations = numpy.corrcoef(dense_data, rowvar = False) correlations = numpy.nan_to_num(correlations) pattern_correlations = [] for pattern in patterns: pattern_correlations.append([correlations[i, j] ...
def get_pattern_correlations(data)
Gets the average correlation between all bits in patterns, across the entire dataset. Assumes input is a sparse matrix. Weighted by pattern rather than by bit; this is the average pairwise correlation for every pattern in the data, and is not the average pairwise correlation for all bits that ever cooccur. T...
3.10181
2.706784
1.145939
# Chooses clusters to clusters = [] cells = set(range(dim)) # Associate cluster sizes with how many cells they should have, then generate # clusters. for size, num_cells in zip(cluster_sizes, num_cells_per_cluster_size): # Must have (num_cells/size) clusters in order to have num_cells cells # ...
def generate_correlated_data(dim = 2000, num_active = 40, num_samples = 1000, num_cells_per_cluster_size = [2000]*8, cluster_sizes = range(2, 10))
Generates a set of data drawn from a uniform distribution, but with bits clustered to force correlation between neurons. Clusters are randomly chosen to form an activation pattern, in such a way as to maintain sparsity. The number of clusters of each size is defined by num_cells_per_cluster_size, as cluster_s...
3.694466
3.654023
1.011068
if noise >= 1: noise = noise/100. for i in range(data.nRows()): ones = data.rowNonZeros(i)[0] replace_indices = numpy.random.choice(ones, size = int(len(ones)*noise), replace = False) for index in replace_indices: data[i, index] = 0 new_indices = numpy.random.choice(data.nCols...
def apply_noise(data, noise)
Applies noise to a sparse matrix. Noise can be an integer between 0 and 100, indicating the percentage of ones in the original input to move, or a float in [0, 1), indicating the same thing. The input matrix is modified in-place, and nothing is returned. This operation does not affect the sparsity of the matri...
2.965688
2.822598
1.050694
print "Shuffling data" new_matrix = matrix.toDense() rng_state = numpy.random.get_state() numpy.random.shuffle(new_matrix) numpy.random.set_state(rng_state) numpy.random.shuffle(labels) print "Data shuffled" return SM32(new_matrix), numpy.asarray(labels)
def shuffle_sparse_matrix_and_labels(matrix, labels)
Shuffles a sparse matrix and set of labels together. Resorts to densifying and then re-sparsifying the matrix, for convenience. Still very fast.
3.416458
3.389837
1.007853
if matrix.nRows() < num_categories: return [matrix.getSlice(i, i+1, 0, matrix.nCols()) for i in range(matrix.nRows())] + [SM32() for i in range(num_categories - matrix.nRows())] else: inc = matrix.nRows()/num_categories divisions = [matrix.getSlice(i*inc, (i+1)*inc, 0, matrix.nCols())...
def split_sparse_matrix(matrix, num_categories)
An analog of numpy.split for our sparse matrix. If the number of categories does not divide the number of rows in the matrix, all overflow is placed in the final bin. In the event that there are more categories than rows, all later categories are considered to be an empty sparse matrix.
3.436674
3.044468
1.128826
indices = [numpy.random.choice(dim, size = num_active, replace = False) for _ in range(num_samples)] data = SM32() data.reshape(0, dim) for row in indices: data.addRowNZ(row, [1]*num_active) # data.reshape(num_samples, dim) # for sample, datapoint in enumerate(indices): # for index in dat...
def generate_evenly_distributed_data_sparse(dim = 2000, num_active = 40, num_samples = 1000)
Generates a set of data drawn from a uniform distribution. The binning structure from Poirazi & Mel is ignored, and all (dim choose num_active) arrangements are possible.
4.450409
4.655642
0.955917
sparse_data = [numpy.random.choice(dim, size = num_active, replace = False) for i in range(num_samples)] data = [[0 for i in range(dim)] for i in range(num_samples)] for datapoint, sparse_datapoint in zip(data, sparse_data): for i in sparse_datapoint: datapoint[i] = 1 negatives = data[:num_...
def generate_evenly_distributed_data(dim = 2000, num_active = 40, num_samples = 1000, num_negatives = 500)
Generates a set of data drawn from a uniform distribution. The binning structure from Poirazi & Mel is ignored, and all (dim choose num_active) arrangements are possible. num_negatives samples are put into a separate negatives category for output compatibility with generate_data, but are otherwise identical.
2.511584
2.360094
1.064188
positives, negatives = [], [] positive, negative = generate_matrices(dim) for i in range(num_samples): phase_1 = generate_phase_1(dim) phase_2 = generate_phase_2(phase_1, dim) if i < num_samples/2: positives.append(numpy.dot(positive, phase_2)) else: negatives.append(numpy.dot(n...
def generate_data(dim = 40, num_samples = 30000, num_bins = 10, sparse = False)
Generates data following appendix V of (Poirazi & Mel, 2001). Positive and negative examples are drawn from the same distribution, but are multiplied by different square matrices, one of them uniform on [-1, 1 and one the sum of a uniform matrix and a normal one. It is assumed that half the samples are negativ...
2.621589
2.551354
1.027529
phase_1 = numpy.random.normal(0, 1, dim) for i in range(dim - 4, dim): phase_1[i] = 1.0 return phase_1
def generate_phase_1(dim = 40)
The first step in creating datapoints in the Poirazi & Mel model. This returns a vector of dimension dim, with the last four values set to 1 and the rest drawn from a normal distribution.
3.443713
2.481184
1.387931
phase_2 = [] for i in range(dim): indices = [numpy.random.randint(0, dim) for i in range(4)] phase_2.append(numpy.prod([phase_1[i] for i in indices])) return phase_2
def generate_phase_2(phase_1, dim = 40)
The second step in creating datapoints in the Poirazi & Mel model. This takes a phase 1 vector, and creates a phase 2 vector where each point is the product of four elements of the phase 1 vector, randomly drawn with replacement.
2.765825
2.157004
1.282253
positive = numpy.random.uniform(-1, 1, (dim, dim)) negative = positive + numpy.random.normal(0, 1, (dim, dim)) return positive, negative
def generate_matrices(dim = 40)
Generates the matrices that positive and negative samples are multiplied with. The matrix for positive samples is randomly drawn from a uniform distribution, with elements in [-1, 1]. The matrix for negative examples is the sum of the positive matrix with a matrix drawn from a normal distribution with mean 0 ...
3.044719
1.902645
1.600256
intervals = [] for i in range(dim): current_dim_data = [data[x][i] for x in range(len(data))] current_dim_data = numpy.sort(current_dim_data) intervals.append([current_dim_data[int(len(current_dim_data)*x/num_bins)] for x in range(1, num_bins)]) return intervals
def generate_RF_bins(data, dim = 40, num_bins = 10)
Generates bins for the encoder. Bins are designed to have equal frequency, per Poirazi & Mel (2001), which requires reading the data once. Bins are represented as the intervals dividing them.
2.521757
2.421984
1.041195
index = numpy.searchsorted(intervals, datapoint) return [0 if index != i else 1 for i in range(len(intervals) + 1)]
def bin_number(datapoint, intervals)
Given a datapoint and intervals representing bins, returns the number represented in binned form, where the bin including the value is set to 1 and all others are 0.
4.254135
3.983351
1.067979
intervals = generate_RF_bins(data, dim, num_bins) binned_data = [numpy.concatenate([bin_number(data[x][i], intervals[i]) for i in range(len(data[x]))]) for x in range(len(data))] return binned_data
def bin_data(data, dim = 40, num_bins = 10)
Fully bins the data generated by generate_data, using generate_RF_bins and bin_number.
4.370989
2.931849
1.490864
if killCellPercent <= 0: return numHiddenNeurons = self.net.numHiddenNeurons numDead = round(killCellPercent * numHiddenNeurons) zombiePermutation = numpy.random.permutation(numHiddenNeurons) deadCells = zombiePermutation[0:numDead] liveCells = zombiePermutation[numDead:] self....
def killCells(self, killCellPercent)
kill a fraction of cells from the network
2.923385
2.802375
1.043181
r batchSize = len(X) W = self.connections.visible_to_hidden n, m = W.shape bias = self.connections.hidden_bias incr = self.weight_incr decr = self.weight_decr boost_bias = self.boost_strength_bias alpha = self.average_activity ...
def numenta(self, X, Y)
r""" Method that updates the network's connections. Numenta's classic update: - Visible to hidden: $ \Delta W_{ij} = y_i \cdot ( \varepsilon_{\small{+}} \ x_j - \varepsilon_{\small{-}} \ \bar x_j ) $ - Bias: $ b_{i} = B_b \cdot \alpha_i $
5.302036
4.752441
1.115645
r batchSize = len(X) W = self.connections.visible_to_hidden H = self.connections.hidden_to_hidden n, m = W.shape bias = self.connections.hidden_bias incr = self.weight_incr decr = self.weight_decr boost_bias = self.boost_stre...
def numenta_new_local_inhibition(self, X, Y)
r""" Weight updates for the new local inhibition procedure (experimental and work in progress). See "Numenta’s local inhibition revisited" (Section 6) in `latex/notes.pdf`. Note that we directly encode the "activation probability" $a_{ij}$ as $h_{ij}$. This is just a temporary hack. In Consequence, t...
4.03636
3.854922
1.047067
filePath = 'data/'+dataSet+'.csv' if dataSet == 'nyc_taxi' or dataSet == 'nyc_taxi_perturb' or dataSet == 'nyc_taxi_perturb_baseline': seq = pd.read_csv(filePath, header=0, skiprows=[1, 2], names=['time', 'data', 'timeofday', 'dayofweek']) seq['time'] = pd.to_datetime(seq['time']) if noise > 0: ...
def readDataSet(dataSet, noise=0)
:param dataSet: dataset name :param noise: amount of noise added to the dataset :return:
3.06791
3.101088
0.989301
# create empty simple object machine objects = createObjectMachine( machineType="simple", numInputBits=20, sensorInputSize=1024, externalInputSize=1024, numCorticalColumns=numCorticalColumns, numFeatures=0, numLocations=0, ) for _ in range(numCorticalColumns): objects.locatio...
def loadThingObjects(numCorticalColumns=1, objDataPath='./data/')
Load simulated sensation data on a number of different objects There is one file per object, each row contains one feature, location pairs The format is as follows [(-33.6705, 75.5003, 2.4207)/10] => [[list of active bits of location], [list of active bits of feature]] The...
3.758769
3.540038
1.061788
avgBits = float(counts.sum())/numWords print "Retina width=128, height=128" print "Total number of words processed=",numWords print "Average number of bits per word=",avgBits, print "avg sparsity=",avgBits/size print "counts matrix sum=",counts.sum(), print "max=",counts.max(), "min=",counts.min(), p...
def printFrequencyStatistics(counts, frequencies, numWords, size)
Print interesting statistics regarding the counts and frequency matrices
4.279368
4.116426
1.039584
# Accumulate counts by inplace-adding sparse matrices counts = SparseMatrix() size = 128*128 counts.resize(1, size) # Pre-allocate buffer sparse matrix sparseBitmap = SparseMatrix() sparseBitmap.resize(1, size) random.seed(42) # Accumulate counts for each bit for each word numWords=0 for ter...
def countRandomBitFrequencies(numTerms = 100000, percentSparsity = 0.01)
Create a uniformly random counts matrix through sampling.
5.261882
5.262554
0.999872
data = [ go.Histogram( x=tuple(count for _, _, count in counts.getNonZerosSorted()) ) ] py.plot(data, filename=os.environ.get("HEATMAP_NAME", str(datetime.datetime.now())))
def plotlyFrequencyHistogram(counts)
x-axis is a count of how many times a bit was active y-axis is number of bits that have that frequency
6.586141
7.250218
0.908406
# Initialize weights in the typical fashion. w = torch.Tensor(outputSize, inputSize, ) if onlyPositive: w.data.uniform_(0, fixedRange) else: w.data.uniform_(-fixedRange, fixedRange) # Zero out weights for sparse weight matrices if numNonzeros < inputSize: numZeros = inputSize - numNonzeros ...
def getSparseTensor(numNonzeros, inputSize, outputSize, onlyPositive=False, fixedRange=1.0/24)
Return a random tensor that is initialized like a weight matrix Size is outputSize X inputSize, where weightSparsity% of each row is non-zero
3.034167
2.972322
1.020807
W2 = W.repeat(m2, 1) nz = W[0].nonzero() numberToZero = int(round(noisePct * kw)) for i in range(m2): indices = np.random.permutation(kw)[0:numberToZero] for j in indices: W2[i,nz[j]] = 0 return W2
def getPermutedTensors(W, kw, n, m2, noisePct)
Generate m2 noisy versions of W. Noisy version of W is generated by randomly permuting noisePct of the non-zero components to other components. :param W: :param n: :param m2: :param noisePct: :return:
4.042987
4.079152
0.991134
theDots = np.zeros(nTrials) w1 = getSparseTensor(k, k, nTrials, fixedRange=1.0/k) for i in range(nTrials): theDots[i] = w1[i].dot(w1[i]) dotMean = theDots.mean() print("k=", k, "min/mean/max diag of w dot products", theDots.min(), dotMean, theDots.max()) theta = dotMean / 2.0 print("Using...
def getTheta(k, nTrials=100000)
Estimate a reasonable value of theta for this k.
5.247477
5.006151
1.048206
# How many weight vectors and input vectors to generate at a time m1 = 4 m2 = 1000 weights = getSparseTensor(kw, n, m1, fixedRange=1.0 / kw) # Initialize random input vectors using given scaling and see how many match inputVectors = getSparseTensor(kv, n, m2, onlyPositi...
def returnMatches(kw, kv, n, theta, inputScaling=1.0)
:param kw: k for the weight vectors :param kv: k for the input vectors :param n: dimensionality of input vector :param theta: threshold for matching after dot product :return: percent that matched, number that matched, total match comparisons
8.383288
7.335753
1.142799
W = getSparseTensor(kw, n, 1, fixedRange=1.0 / kw) # Get permuted versions of W and see how many match m2 = 10 inputVectors = getPermutedTensors(W, kw, n, m2, noisePct) dot = inputVectors.matmul(W.t()) numMatches = ((dot >= theta).sum()).item() pctMatches = numMatches / float(m2) return pctMatche...
def returnFalseNegatives(kw, noisePct, n, theta)
Generate a weight vector W, with kw non-zero components. Generate 1000 noisy versions of W and return the match statistics. Noisy version of W is generated by randomly setting noisePct of the non-zero components to zero. :param kw: k for the weight vectors :param noisePct: percent noise, from 0 to 1 :param n...
9.082752
7.551876
1.202715
kv = args["k"] n = args["n"] kw = args["kw"] theta = args["theta"] if kv == -1: kv = int(round(n/2.0)) numMatches = 0 totalComparisons = 0 for t in range(args["nTrials"]): pct, num, total = returnMatches(kw, kv, n, theta, args["inputScaling"]) numMatches += num totalComparisons += t...
def computeMatchProbability(args)
Runs a number of trials of returnMatches() and returns an overall probability of matches given the parameters. :param args is a dictionary containing the following keys: kw: k for the weight vectors kv: k for the input vectors. If -1, kv is set to n/2 n: dimensionality of input vector theta: threshold...
4.071841
2.88244
1.412637
# Create arguments for the possibilities we want to test args = [] theta, _ = getTheta(kw) for ki, k in enumerate(listofkValues): for si, s in enumerate(listOfScales): args.append({ "k": k, "kw": kw, "n": n, "theta": theta, "nTrials": nTrials, "inputScaling": s, "error...
def computeScaledProbabilities( listOfScales=[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0], listofkValues=[64, 128, 256], kw=32, n=1000, numWorkers=10, nTrials=1000, )
Compute the impact of S on match probabilities for a fixed value of n.
4.643153
4.529514
1.025088
omegaProb = np.zeros(bMax+1) for b in range(1, bMax+1): xwb = getSparseTensor(b, b, nTrials, fixedRange=1.0/k) xib = getSparseTensor(b, b, nTrials, onlyPositive=True, fixedRange=2.0/k) r = xwb.matmul(xib.t()) numMatches = ((r >= theta).sum()).item() omegaProb[b] = numMatches / float(nTrials ...
def computeMatchProbabilityOmega(k, bMax, theta, nTrials=100)
The Omega match probability estimates the probability of matching when both vectors have exactly b components in common. This function computes this probability for b=1 to bMax. For each value of b this function: 1) Creates nTrials instances of Xw(b) which are vectors with b components where each component...
4.677921
3.838826
1.218581
w, h = figaspect(0.4) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(w,h)) plotMatches(listofNValues, errors, fileName=None, fig=fig, ax=ax1) plotScaledMatches(listOfScales, scaleErrors, fileName=None, fig=fig, ax=ax2) plt.savefig(fileName) plt.close()
def plotMatches2(listofNValues, errors, listOfScales, scaleErrors, fileName = "images/scalar_matches.pdf")
Plot two figures side by side in an aspect ratio appropriate for the paper.
2.536922
2.294116
1.105839
# Graph for computeMatchProbabilities(kw=32, nTrials=3000) listofNValues = [250, 500, 1000, 1500, 2000, 2500] kw = 32 errors = np.array([ [3.65083333e-03, 3.06166667e-04, 1.89166667e-05, 4.16666667e-06, 1.50000000e-06, 9.16666667e-07], [2.44633333e-02, 3.64491667e-03, 3.16083333e-04, 6.9333...
def createPregeneratedGraphs()
Creates graphs based on previous runs of the scripts. Useful for editing graph format for writeups.
2.705407
2.69975
1.002096
self.bumpPhases = np.empty((2,0), dtype="float") self.phaseDisplacement = np.empty((0,2), dtype="float") self.cellsForActivePhases = np.empty(0, dtype="int") self.activeCells = np.empty(0, dtype="int") self.learningCells = np.empty(0, dtype="int") self.sensoryAssociatedCells = np.empty(0, d...
def reset(self)
Clear the active cells.
4.411718
4.325625
1.019903
self.bumpPhases = np.array([np.random.random(2)]).T self._computeActiveCells()
def activateRandomLocation(self)
Set the location to a random point.
22.633408
19.827457
1.141518
if noiseFactor != 0: displacement = copy.deepcopy(displacement) xnoise = np.random.normal(0, noiseFactor) ynoise = np.random.normal(0, noiseFactor) displacement[0] += xnoise displacement[1] += ynoise # Calculate delta in the module's coordinates. phaseDisplacement = np.m...
def movementCompute(self, displacement, noiseFactor = 0)
Shift the current active cells by a vector. @param displacement (pair of floats) A translation vector [di, dj].
4.573158
4.376856
1.04485
if len(anchorInput) == 0: return overlaps = self.connections.computeActivity(anchorInput, self.connectedPermanence) activeSegments = np.where(overlaps >= self.activationThreshold)[0] sensorySupportedCells = np.unique( self.connections.ma...
def _sensoryComputeInferenceMode(self, anchorInput)
Infer the location from sensory input. Activate any cells with enough active synapses to this sensory input. Deactivate all other cells. @param anchorInput (numpy array) A sensory input. This will often come from a feature-location pair layer.
8.150085
8.330157
0.978383
# Learn on existing segments connections.adjustSynapses(learningSegments, activeInput, permanenceIncrement, -permanenceDecrement) # Grow new synapses. Calculate "maxNew", the maximum number of synapses to # grow per segment. "maxNew" might be a number or it might be ...
def _learn(connections, rng, learningSegments, activeInput, potentialOverlaps, initialPermanence, sampleSize, permanenceIncrement, permanenceDecrement, maxSynapsesPerSegment)
Adjust synapse permanences, grow new synapses, and grow new segments. @param learningActiveSegments (numpy array) @param learningMatchingSegments (numpy array) @param segmentsToPunish (numpy array) @param activeInput (numpy array) @param potentialOverlaps (numpy array)
4.290848
4.398784
0.975462
firingFieldDiameter = 2 * (1./cellsPerAxis)*(2./math.sqrt(3)) if minimumActiveDiameter: firingFieldDiameter = max(firingFieldDiameter, minimumActiveDiameter) return ThresholdedGaussian2DLocationModule.gaussian( bumpSigma, firingFieldDiameter / 2.)
def chooseReliableActiveFiringRate(cellsPerAxis, bumpSigma, minimumActiveDiameter=None)
When a cell is activated by sensory input, this implies that the phase is within a particular small patch of the rhombus. This patch is roughly equivalent to a circle of diameter (1/cellsPerAxis)(2/sqrt(3)), centered on the cell. This 2/sqrt(3) accounts for the fact that when circles are packed into hex...
6.666723
4.160562
1.602361
self.activePhases = np.empty((0,2), dtype="float") self.phaseDisplacement = np.empty((0,2), dtype="float") self.cellsForActivePhases = np.empty(0, dtype="int") self.activeCells = np.empty(0, dtype="int") self.sensoryAssociatedCells = np.empty(0, dtype="int")
def reset(self)
Clear the active cells.
4.126636
3.953562
1.043777
self.activePhases = np.array([np.random.random(2)]) if self.anchoringMethod == "discrete": # Need to place the phase in the middle of a cell self.activePhases = np.floor( self.activePhases * self.cellDimensions)/self.cellDimensions self._computeActiveCells()
def activateRandomLocation(self)
Set the location to a random point.
8.933426
8.614503
1.037022
if noiseFactor != 0: displacement = copy.deepcopy(displacement) xnoise = np.random.normal(0, noiseFactor) ynoise = np.random.normal(0, noiseFactor) displacement[0] += xnoise displacement[1] += ynoise # Calculate delta in the module's coordinates. phaseDisplacement = (np...
def movementCompute(self, displacement, noiseFactor = 0)
Shift the current active cells by a vector. @param displacement (pair of floats) A translation vector [di, dj].
4.522262
4.317428
1.047443
if len(anchorInput) == 0: return overlaps = self.connections.computeActivity(anchorInput, self.connectedPermanence) activeSegments = np.where(overlaps >= self.activationThreshold)[0] sensorySupportedCells = np.unique( self.connections.ma...
def _sensoryComputeInferenceMode(self, anchorInput)
Infer the location from sensory input. Activate any cells with enough active synapses to this sensory input. Deactivate all other cells. @param anchorInput (numpy array) A sensory input. This will often come from a feature-location pair layer.
3.790674
3.813837
0.993927
overlaps = self.connections.computeActivity(anchorInput, self.connectedPermanence) activeSegments = np.where(overlaps >= self.activationThreshold)[0] potentialOverlaps = self.connections.computeActivity(anchorInput) matchingSegments = np.where(potent...
def _sensoryComputeLearningMode(self, anchorInput)
Associate this location with a sensory input. Subsequently, anchorInput will activate the current location during anchor(). @param anchorInput (numpy array) A sensory input. This will often come from a feature-location pair layer.
3.947383
4.076261
0.968383
votesByCell = np.zeros(self.cellCount, dtype="int") self.activeSegmentsByColumn = [] for (connections, activeSensorToBodyCells, activeSensorToSpecificObjectCells) in zip(self.connectionsByColumn, sensorToBodyByColumn, ...
def compute(self, sensorToBodyByColumn, sensorToSpecificObjectByColumn)
Compute the "body's location relative to a specific object" from an array of "sensor's location relative to a specific object" and an array of "sensor's location relative to body" These arrays consist of one module per cortical column. This is a metric computation, similar to that of...
4.302897
4.286812
1.003752
overlaps = self.metricConnections.computeActivity({ "bodyToSpecificObject": bodyToSpecificObject, "sensorToBody": sensorToBody, }) self.activeMetricSegments = np.where(overlaps >= 2)[0] self.activeCells = np.unique( self.metricConnections.mapSegmentsToCells( self.activeMe...
def metricCompute(self, sensorToBody, bodyToSpecificObject)
Compute the "sensor's location relative to a specific object" from the "body's location relative to a specific object" and the "sensor's location relative to body" @param sensorToBody (numpy array) Active cells of a single module that represents the sensor's location relative to t...
6.125459
6.111917
1.002216
if learn: self._anchorComputeLearningMode(anchorInput) else: overlaps = self.anchorConnections.computeActivity( anchorInput, self.connectedPermanence) self.activeSegments = np.where(overlaps >= self.activationThreshold)[0] self.activeCells = np.unique( self.anchorCo...
def anchorCompute(self, anchorInput, learn)
Compute the "sensor's location relative to a specific object" from the feature-location pair. @param anchorInput (numpy array) Active cells in the feature-location pair layer @param learn (bool) If true, maintain current cell activity and learn this input on the currently active cells
7.257623
8.038177
0.902894
offsetInCellFields = (np.matmul(self.rotationMatrix, egocentricLocation) * self.cellFieldsPerUnitDistance) np.mod(offsetInCellFields, self.cellDimensions, out=offsetInCellFields) self.activeCells = np.unique( np.ravel_multi_index(np.floor(offsetInCellFields).T.astype('i...
def compute(self, egocentricLocation)
Compute the new active cells from the given "sensor location relative to body" vector. @param egocentricLocation (pair of floats) [di, dj] offset of the sensor from the body.
5.671448
5.732129
0.989414
try: coreDistribution = pkg_resources.get_distribution("htmresearch-core") if pkg_resources.parse_version(coreDistribution.version).is_prerelease: # A pre-release dev version of htmresearch-core is installed. return True except pkg_resources.DistributionNotFound: pass # Silently ignore. ...
def htmresearchCorePrereleaseInstalled()
Make an attempt to determine if a pre-release version of htmresearch-core is installed already. @return: boolean
4.672348
4.755789
0.982455
requirementsPath = os.path.join(REPO_DIR, "requirements.txt") requirements = parse_file(requirementsPath) # User has a pre-release version of numenta packages installed, which is only # possible if the user installed and built the packages from source and # it is up to the user to decide when to update th...
def findRequirements()
Read the requirements.txt file and parse into requirements for setup's install_requirements option.
7.741521
7.721543
1.002587
self._setLearningMode() for objectName, sensationList in objects.iteritems(): # ignore empty sensation lists if len(sensationList) == 0: continue # keep track of numbers of iterations to run iterations = 0 for sensations in sensationList: # learn each patte...
def learnObjects(self, objects, reset=True)
Learns all provided objects, and optionally resets the network. The provided objects must have the canonical learning format, which is the following. objects should be a dict objectName: sensationList, where the sensationList is a list of sensations, and each sensation is a mapping from cortical c...
4.6751
3.199121
1.46137
self._unsetLearningMode() statistics = collections.defaultdict(list) if objectName is not None: if objectName not in self.objectRepresentationsL2: raise ValueError("The provided objectName was not given during" " learning") for sensations in sensationList: ...
def infer(self, sensationList, reset=True, objectName=None)
Infer on a given set of sensations for a single object. The provided sensationList is a list of sensations, and each sensation is a mapping from cortical column to a tuple of three SDR's respectively corresponding to the locationInput, the coarseSensorInput, and the sensorInput. For example, the i...
5.079022
4.289986
1.183925
# Handle logging - this has to be done first if self.logCalls: frame = inspect.currentframe() args, _, _, values = inspect.getargvalues(frame) values.pop('frame') values.pop('self') (_, filename, _, _, _, _) = inspect.getouterframes(inspect.currentframe())[1] if o...
def _sendReset(self, sequenceId=0)
Sends a reset signal to the network.
4.331966
4.279464
1.012268
return { "sensorParams": { "outputWidth": self.sensorInputSize, }, "coarseSensorParams": { "outputWidth": self.sensorInputSize, }, "locationParams": { "activeBits": 41, "outputWidth": self.sensorInputSize, "radius": 2, "verbosity...
def getDefaultParams(self)
Returns a good default set of parameters to use in L2456 regions
2.306859
2.269827
1.016315
self.sensors = [] self.coarseSensors = [] self.locationInputs = [] self.L4Columns = [] self.L2Columns = [] self.L5Columns = [] self.L6Columns = [] for i in xrange(self.numColumns): self.sensors.append( self.network.regions["sensorInput_" + str(i)].getSelf() ) ...
def _retrieveRegions(self)
Retrieve and store Python region instances for each column
1.927502
1.858679
1.037028
for column in self.L4Columns: column.setParameter("learn", 0, False) for column in self.L6Columns: column.setParameter("learn", 0, False) for column in self.L2Columns: column.setParameter("learningMode", 0, False) for column in self.L5Columns: column.setParameter("learning...
def _unsetLearningMode(self)
Unsets the learning mode, to start inference.
3.020037
2.967481
1.017711
for column in self.L4Columns: column.setParameter("learn", 0, True) for column in self.L6Columns: column.setParameter("learn", 0, True) for column in self.L2Columns: column.setParameter("learningMode", 0, True) for column in self.L5Columns: column.setParameter("learningMode...
def _setLearningMode(self)
Sets the learning mode.
3.077565
2.948475
1.043782
L4Representations = self.getL4Representations() L4PredictedCells = self.getL4PredictedCells() L2Representations = self.getL2Representations() L5Representations = self.getL5Representations() L6Representations = self.getL6Representations() L6PredictedCells = self.getL6PredictedCells() fo...
def _updateInferenceStats(self, statistics, objectName=None)
Updates the inference statistics. Parameters: ---------------------------- @param statistics (dict) Dictionary in which to write the statistics @param objectName (str) Name of the inferred object, if known. Otherwise, set to None.
2.018327
2.014198
1.00205
num_bits = num_streams*bits_per_axis # Setting up the scalar encoder encoder_params = { "dimensions" : num_streams, "max_values" : [[0.,1.]]*num_streams, "bits_per_axis" : [bits_per_axis]*num_streams, "weight_per_axis" : [weight_per_axis]*num_streams, ...
def n_to_one(num_inputs, num_streams, bits_per_axis, weight_per_axis)
Creating inputs of the form: ``( x, y, ..., y )'' |---------| n Here n = num_streams -1. To be more precise, for each component we allocate a fixed number of units `bits_per_axis` and encode each component with a scalar encoder. This is a toy exampl...
3.132329
3.123845
1.002716
return dict(("Object %d" % i, zip(xrange(numLocationsPerObject), [random.choice(featurePool) for _ in xrange(numLocationsPerObject)])) for i in xrange(1, numObjects + 1))
def createRandomObjectDescriptions(numObjects, numLocationsPerObject, featurePool=("A", "B", "C"))
Returns {"Object 1": [(0, "C"), (1, "B"), (2, "C"), ...], "Object 2": [(0, "C"), (1, "A"), (2, "B"), ...]}
3.468817
2.715516
1.277406
# # Run the experiment # noiseLevels = [x * 0.01 for x in xrange(0, 101, 5)] l2Overrides = {"sampleSizeDistal": 20} columnCounts = [1, 2, 3, 4] results = defaultdict(list) for trial in xrange(1): print "trial", trial objectDescriptions = createRandomObjectDescriptions(10, 10) for numC...
def plotSuccessRate_varyNumColumns(noiseSigma, noiseEverywhere)
Run and plot the experiment, varying the number of cortical columns.
2.976571
2.974927
1.000553
noiseLevels = [0.30, 0.40, 0.45, 0.50, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90] l2Overrides = {"sampleSizeDistal": 20} columnCounts = [1, 2, 3, 4, 5] results = defaultdict(list) for trial in xrange(1): print "trial", trial objectDescriptions = createRandomObjectDescriptions(10, 10) fo...
def logCellActivity_varyNumColumns(noiseSigma, noiseEverywhere)
Run the experiment, varying the column counts, and save each [# correctly active cells, # incorrectly active cells] pair to a JSON file that can be visualized.
3.604926
3.599766
1.001434
newSensations = [] for _ in range(numTraversals): s = copy.deepcopy(sensations) random.shuffle(s) newSensations += s return newSensations
def randomTraversal(sensations, numTraversals)
Given a list of sensations, return the SDRs that would be obtained by numTraversals random traversals of that set of sensations. Each sensation is a dict mapping cortical column index to a pair of SDR's (one location and one feature).
2.461363
2.699876
0.911658
objects = self.getObjects() if len(objects) == 0: return 0.0, 0.0, 0.0 sumCommonLocations = 0 sumCommonFeatures = 0 sumCommonPairs = 0 numObjects = 0 commonPairHistogram = numpy.zeros(len(objects[0]), dtype=numpy.int32) for o1, s1 in objects.iteritems(): for o2, s2 in ...
def objectConfusion(self)
Compute overlap between each pair of objects. Computes the average number of feature/location pairs that are identical, as well as the average number of shared locations and features. This function will raise an exception if two objects are identical. Returns the tuple: (avg common pairs, avg c...
2.607346
2.290383
1.138388
for objectName, sensationList in objects.iteritems(): if objectName not in self.objects: raise ValueError( "Invalid object name \"{}\" sent to experiment".format(objectName) ) for sensations in sensationList: if set(sensations.keys()) != set(range(self.numColumns)...
def _checkObjectsToLearn(self, objects)
Checks that objects have the correct format before being sent to the experiment.
4.316936
3.938062
1.096208
for sensations in sensationList: if set(sensations.keys()) != set(range(self.numColumns)): raise ValueError( "Invalid number of cortical column sensations sent to experiment" ) for pair in sensations.values(): if not isinstance(pair, tuple) or len(pair) != 2 or \ ...
def _checkObjectToInfer(self, sensationList)
Checks that objects have the correct format before being sent to the experiment.
5.327795
4.822605
1.104755
indices = random.sample(xrange(totalSize), numBits) return set(indices)
def _generatePattern(numBits, totalSize)
Generates a random SDR with specified number of bits and total size.
5.276425
5.531906
0.953817
dx = xt - xt1 dy = yt - yt1 if self.numPoints < self.maxPoints: self.dxValues[self.numPoints,0] = dx self.dxValues[self.numPoints,1] = dy self.thetaValues[self.numPoints,0] = theta1 self.thetaValues[self.numPoints,1] = theta2 self.numPoints += 1 # print >>sys.std...
def compute(self, xt1, yt1, xt, yt, theta1t1, theta2t1, theta1, theta2)
Accumulate the various inputs.
3.109732
3.035276
1.02453
cell1Coords = np.unravel_index(cell1, moduleDimensions) cell2Coords = np.unravel_index(cell2, moduleDimensions) transformCoords = [(c2 - c1) % m for c1, c2, m in itertools.izip(cell1Coords, cell2Coords, moduleDimensions)] return np.rav...
def bind(cell1, cell2, moduleDimensions)
Return transform index for given cells. Convert to coordinate space, calculate transform, and convert back to an index. In coordinate space, the transform represents `C2 - C1`.
2.669557
2.62541
1.016815
cell1Coords = np.unravel_index(cell1, moduleDimensions) transformCoords = np.unravel_index(transform, moduleDimensions) cell2Coords = [(t + c1) % m for c1, t, m in itertools.izip(cell1Coords, transformCoords, moduleDimensions)] return np.ravel_...
def unbind(cell1, transform, moduleDimensions)
Return the cell index corresponding to the other half of the transform. Assumes that `transform = bind(cell1, cell2)` and, given `cell1` and `transform`, returns `cell2`.
2.92583
3.012729
0.971156
filenames = [join(mypath, f) for f in listdir(mypath) if isfile(join(mypath, f))] filenames = [f for f in filenames if f.endswith(".p")] W = [] for filename in filenames: with open(filename, 'r') as f: data = pickle.load(f) W.append(np.expand_dims(data[key], axis=-1...
def gather_data(mypath, key="width")
Loads trials from a folder and returns an array indexed by: m, k, t.
2.204001
2.282568
0.965579
stdpScaler = 1 stdpTimeScaler = 1. # Set up STDP directions if inhibitoryPresyn and not inhibitoryPostsyn: #I-E, anti-Hebbian (weakening inhibitory connections) stdpScaler *= 1 elif not inhibitoryPresyn and inhibitoryPostsyn: # E-I, Hebbian stdpScaler *= 1 elif inhibitoryPresyn and inhi...
def defaultSTDPKernel(preSynActivation, postSynActivation, dt, inhibitoryPresyn=False, inhibitoryPostsyn=False)
This function implements a modified version of the STDP kernel from Widloski & Fiete, 2014. :param preSynActivation: Vector of pre-synaptic activations :param postSynActivation: Vector of post-synaptic activations :param dt: the difference in time between the two (in seconds), positive if after and ne...
3.311357
3.090982
1.071296
self.weightsPI += np.outer(self.activationsI - self.boostTarget, self.activationsP)*self.dt*\ self.learnFactorP*self.learningRate self.weightsPEL += np.outer(self.activationsEL - self.boostTarget, self.activationsP...
def updatePlaceWeights(self)
We use a simplified version of Hebbian learning to learn place weights. Cells above the boost target are wired to the currently-active places, cells below it have their connection strength to them reduced.
2.682783
2.315702
1.158519
# Set up plotting if self.plotting: self.fig = plt.figure() self.ax1 = self.fig.add_subplot(311) self.ax2 = self.fig.add_subplot(312) self.ax3 = self.fig.add_subplot(313) plt.ion() self.ax1.set_xlabel("Excitatory population activity") self.ax2.set_xlabel("Inhibito...
def simulate(self, time, feedforwardInputI, feedforwardInputE, v, recurrent=True, dt=None, envelope=False, inputNoise=None, sampleFreq=1, startFrom=0, save=True)
:param time: Amount of time to simulate. Divided into chunks of len dt. :param feedforwardInputI: feedforward input to inhibitory cells. Must have shape (numInhibitory,). Should be total input over period time. :param feedforwardInputE: feedforward input to excitatory cells. Must have ...
2.470066
2.433594
1.014987
self.ax1.clear() x = np.arange(0, len(self.activationsER), 1) self.ax1.plot(x, self.activationsEL, color = "b", label = "EL Activation") self.ax1.plot(x, self.activationsER, color = "r", label = "ER Activation") self.ax1.legend(loc = "best") self.ax2.clear() x = np.arange(0, len(self.a...
def plotActivation(self, position=None, time=None, velocity=None, boosting=True)
Plot the activation of the current cell populations. Assumes that two axes have already been created, ax1 and ax2. If done in a Jupyter notebook, this plotting will overwrite the old plot. :param position: The current location of the animal :param time: The current time in the simulation :param ve...
2.034943
2.094185
0.971711
if clearBuffer: while len(self.activationBuffer) > 1: baseI, baseEL, baseER, baseP, t = self.activationBuffer.popleft() for (I, EL, ER, P, i) in self.activationBuffer: t = (i - t) * self.dt self.weightsPI += placeSTDPKernel(self.learningRate *\ ...
def stdpUpdate(self, time, clearBuffer=False, onlyPlace=False)
Adds the current activations to the tracking queue, and then performs an STDP update if possible. :param time: The current time. Must be provided. :param clearBuffer: Set as True to clear the activation buffer. This should be done at the end of training. :param onlyPlace: Only learn place c...
1.73816
1.71668
1.012513
# Set up plotting if self.plotting: self.fig = plt.figure() self.ax1 = self.fig.add_subplot(221) self.ax2 = self.fig.add_subplot(222) self.ax3 = self.fig.add_subplot(223) plt.ion() self.ax1.set_xlabel("Excitatory population activity") self.ax2.set_xlabel("Inhibito...
def simulate(self, time, feedforwardInputI, feedforwardInputE, v, recurrent=True, dt=None, envelope=False, inputNoise=None)
:param time: Amount of time to simulate. Divided into chunks of len dt. :param feedforwardInputI: feedforward input to inhibitory cells. Must have shape (numInhibitory,). Should be total input over period time. :param feedforwardInputE: feedforward input to excitatory cells. Must have ...
2.989278
2.984582
1.001574
np.matmul(self.weightsPI, self.activationsP*self.placeGainI, self.instantaneousI) if recurrent: self.instantaneousI += np.matmul(np.minimum(self.weightsII, 0), self.activationsI, ) self.instantaneousI += s...
def update(self, feedforwardInputI, feedforwardInputE, v, recurrent=True, envelope=False, iSpeedTuning=False)
Do one update of the CAN network, of length self.dt. :param feedforwardInputI: The feedforward input to inhibitory cells. :param feedforwardInputR: The feedforward input to excitatory cells. :param placeActivity: Activity of the place code. :param v: The current velocity. :param recurrent: Whether o...
3.501759
3.474431
1.007866
envelopeX = [1 if np.abs(p) < 1 - self.envelopeWidth else np.exp(-1.*self.envelopeFactor * ((np.abs(p) - 1 + self.envelopeWidth)/self.envelopeWidth)**2) for p in np.linspace(-1, 1, self.dimensions[0])] envelopeY = [1 if np.abs(p) < 1 - self...
def computeEnvelope(self)
Compute an envelope for use in suppressing border cells. :return: A numpy array that can be elementwise-multiplied with activations for the given cell population to apply the envelope.
2.724405
2.779691
0.980111
self.weightsII -= self.weightsII*self.dt/decayConst self.weightsPI -= self.weightsPI*self.dt/decayConst for k, w in self.weightsIE.items(): w -= w*self.dt/decayConst for k, w in self.weightsEI.items(): w -= w*self.dt/decayConst for k, w in self.weightsPE.items(): w -= w*self.d...
def decayWeights(self, decayConst=60)
Decay the network's weights. :param decayConst: The time constant (in seconds) to use for decay. Note: If applied, decay must be used extremely carefully, as it has a tendency to cause asymmetries in the network weights.
2.434155
2.562567
0.949889