def test(self, imgs, labels): spikemon_output = SpikeMonitor(self.net["output"], name='output_spikes') spikemon_hidden = SpikeMonitor(self.net["hidden"], name='hidden_spikes') spikemon_input = SpikeMonitor(self.net["input"], name='input_spikes') spikemon_list = [spikemon_input, spikemon_hidden, spikemon_output] self.net.add(spikemon_list) num = len(labels) correct_num = 0 last_count = np.zeros(self.output_layer_size) for _ in range(num): self.set_input(array(imgs[_]).flatten()) self.net.run(self.test_steps * self.time_step * ms) current_count = self.net.get_states()["output_spikes"]["count"] increased_count = np.subtract(current_count, last_count) last_count = current_count correct_num += int(labels[_] == np.argmax(increased_count)) print(increased_count, end=", ") print(labels[_]) # device.build(directory='output', compile=True, run=True, debug=False) accuarcy = float(correct_num) / num print("# Accuracy:%f" % accuarcy) record_file = open('test_record_reim.txt', 'a+') localtime = time.asctime(time.localtime(time.time())) record_file.writelines('%s , Accuarcy : %f\n' % (localtime, accuarcy)) record_file.close() self.net.remove(spikemon_list) print(self.net)
def neuron_sim(stim_V=0.8): """simulating the neuron using brian2 library""" # initiate stimuli timing stimulus = br2.TimedArray( [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, stim_V, 0, 0, 0, 0, 0, 0, 0, 0, 0], dt=100 * br2.ms) # initiating neurons eqs = ''' dv/dt = (-v + stimulus(t)-0.1*rand()) / tau : 1 tau : second ''' # creating neuron group G = br2.NeuronGroup(10, eqs, dt=0.2 * br2.ms) # creating different tau's for the neuron model G.tau = np.linspace(10, 100, 10) * br2.ms # defining state monitor to record voltage M = br2.StateMonitor(G, 'v', record=True) # creating network net = br2.Network(G, M) # storing initial state net.store() # np array to contain data data = np.zeros(shape=(10, 10000, 4)) # producing four repetitions for trial in range(4): net.restore() # Restore the initial state net.run(2 * br2.second) # store the results data[:, :, trial] = M.v return data
def gaussian_input(num_neurons, features, width): neurons = np.arange(0, 360, 360 / num_neurons) stim = np.zeros(num_neurons) for feature in features: tuning = stats.norm.pdf(neurons, loc=feature, scale=width) tuning = np.sqrt(2 * np.pi) * width * tuning stim += tuning return stim
def get_2d_input_weights(): name = 'XeAe' weight_matrix = np.zeros((n_input, n_e)) n_e_sqrt = int(np.sqrt(n_e)) n_in_sqrt = int(np.sqrt(n_input)) num_values_col = n_e_sqrt * n_in_sqrt num_values_row = num_values_col rearranged_weights = np.zeros((num_values_col, num_values_row)) # connMatrix = connections[name][:] connMatrix = synapses[name].w[:] weight_matrix = np.copy(connMatrix.reshape(n_input, n_e)) for i in xrange(n_e_sqrt): for j in xrange(n_e_sqrt): rearranged_weights[i*n_in_sqrt : (i+1)*n_in_sqrt, j*n_in_sqrt : (j+1)*n_in_sqrt] = \ weight_matrix[:, i + j*n_e_sqrt].reshape((n_in_sqrt, n_in_sqrt)) return rearranged_weights
def convert_lin_to_matrix_state(lin_state): """Convert binary linear state vector to state matrix.""" n = int(np.cbrt(len(lin_state))) ijk_idxs = [mat_idx(idx, n) for idx in np.argwhere(lin_state)] mat_idxs = [list(v) for v in zip(*ijk_idxs)] M = np.zeros((n, n, n), dtype=int) M[mat_idxs] = 1 return M
def get_labeled_data(picklename, bTrain=True): """Read input-vector (image) and target class (label, 0-9) and return it as list of tuples. """ if os.path.isfile('%s.pickle' % picklename): data = pickle.load(open('%s.pickle' % picklename)) else: # Open the images with gzip in read binary mode if bTrain: images = open(MNIST_data_path + 'train-images.idx3-ubyte', 'rb') labels = open(MNIST_data_path + 'train-labels.idx1-ubyte', 'rb') else: images = open(MNIST_data_path + 't10k-images.idx3-ubyte', 'rb') labels = open(MNIST_data_path + 't10k-labels.idx1-ubyte', 'rb') # Get metadata for images images.read(4) # skip the magic_number number_of_images = unpack('>I', images.read(4))[0] rows = unpack('>I', images.read(4))[0] cols = unpack('>I', images.read(4))[0] # Get metadata for labels labels.read(4) # skip the magic_number N = unpack('>I', labels.read(4))[0] if number_of_images != N: raise Exception( 'number of labels did not match the number of images') # Get the data x = np.zeros((N, rows, cols), dtype=np.uint8) # Initialize numpy array y = np.zeros((N, 1), dtype=np.uint8) # Initialize numpy array for i in xrange(N): if i % 1000 == 0: print("i: %i" % i) x[i] = [[ unpack('>B', images.read(1))[0] for unused_col in xrange(cols) ] for unused_row in xrange(rows)] y[i] = unpack('>B', labels.read(1))[0] data = {'x': x, 'y': y, 'rows': rows, 'cols': cols} pickle.dump(data, open("%s.pickle" % picklename, "wb")) return data
def get_new_assignments(result_monitor, input_numbers): assignments = np.zeros(n_e) input_nums = np.asarray(input_numbers) maximum_rate = [0] * n_e for j in xrange(10): num_assignments = len(np.where(input_nums == j)[0]) if num_assignments > 0: rate = np.sum(result_monitor[input_nums == j], axis=0) / num_assignments for i in xrange(n_e): if rate[i] > maximum_rate[i]: maximum_rate[i] = rate[i] assignments[i] = j return assignments
def get_matrix_from_file(fileName): offset = 4 if fileName[-4-offset] == 'X': n_src = n_input else: if fileName[-3-offset]=='e': n_src = n_e else: n_src = n_i if fileName[-1-offset]=='e': n_tgt = n_e else: n_tgt = n_i readout = np.load(fileName) print readout.shape, fileName value_arr = np.zeros((n_src, n_tgt)) if not readout.shape == (0,): value_arr[np.int32(readout[:,0]), np.int32(readout[:,1])] = readout[:,2] return value_arr
# mon = StateMonitor(neurons, 'V', record=0) spike_mon = SpikeMonitor(neurons) run(sim_time, report='stdout') output_indices = spike_mon.i output_times = spike_mon.t / second f = h5py.File(INFERENCE_OUTPUT_FILE) f["indices"] = output_indices f["times"] = output_times f.close() sum_spikes = np.zeros(shape=[10, 100], dtype=np.int32) end_time = 0.25 current_index = 0 for i in range(len(output_times)): if (output_times[i] < end_time): if (output_times[i] >= end_time - 0.25): sum_spikes[current_index][output_indices[i]] += 1 else: end_time += 50.0 current_index += 1 print(" Progress : %f " % (i / len(output_times))) f = h5py.File(MNIST_TRAIN_HDF5_FILE) train_label = f["label"][:] f.close()
f = h5py.File(MNIST_TRAIN_HDF5_FILE, 'r') train_img = f["img"][:] train_label = f["label"][:] f.close() N = 100 global_indices = np.array([]) global_times = np.array([]) start_time = time.time() for i in range(N): spikes = np.random.rand(IMG_SIZE, int(total / bin_size)) < p # create zero pattern first for we only fill nonzero position after pattern = np.zeros([IMG_SIZE, int(pattern_length / bin_size)]) img_flatten = np.array(train_img[i]).flatten() # This parameter is gotten using several experiments rates = img_flatten / 255 * 125 * Hz inp = PoissonGroup(IMG_SIZE, rates) spikeMonitor = SpikeMonitor(inp) run(250 * ms, report="text") indices, times = spikeMonitor.it for j in range(np.array(indices).shape[0]): pattern[indices[j]][int(times[j] / bin_size)] = True for rep in np.arange(n_repetitions): spikes[:, rep * int(repeat_every / bin_size):rep * int(repeat_every / bin_size) +