Debian Codegraph @

examples/frompapers/Diehl_Cook_2015.py

raw
1 """
2 Unsupervised learning using STDP
3 --------------------------------
4 Diehl, P. U., & Cook, M. (2015). Unsupervised learning of digit
5 recognition using spike-timing-dependent plasticity. Frontiers in
6 computational neuroscience, 9, 99.
7
8 This script replicates the small 2x400-model. It has no command line
9 parameters. Instead, you control it by changing the constants below
10 the imports. Run the script with MODE set to "train" which
11 (eventually) creates the files theta.npy and weights.npy in the
12 DATA_PATH directory. Rerun it with MODE set to "observe" to create the
13 assign.npy file in the same directory. Then, run "test" to create a
14 confusion matrix in confusion.npy. Finally, you can use "plot" to
15 plot the confusion matrix. The script also creates a few auxilliary
16 .npy files useful for analysis. The script requires the progressbar2
17 library.
18
19 MNIST_PATH should point to the directory storing the unzipped *-byte
20 MNIST files (e.g. from https://github.com/cvdfoundation/mnist).
21 For reasonable accuracy, N_TRAIN should be 50,000+ and N_OBSERVE 1,000+.
22
23 Written in 2024 by Björn A. Lindqvist <[email protected]>
24 """
25 from brian2 import *
26 from collections import defaultdict
27 from pathlib import Path
28 from progressbar import progressbar
29 from random import randrange, seed as rseed
30 from struct import unpack
31 import numpy as np
32
33 # Switch between "train", "observe", and "test" to tune parameters,
34 # observe excitatory spiking, and test accuracy, respectively.
35 # Use "plot" to plot the confusion matrix.
36 MODE = 'test'
37
38 # Number of training, observation, and testing samples
39 N_TRAIN = 25_000
40 N_OBSERVE = 2_000
41 N_TEST = 1_000
42
43 # Random seed value
44 SEED = 42
45
46 # Storage paths
47 MNIST_PATH = Path('../mnist')
48 DATA_PATH = Path('data')
49
50 # Number of weight save points
51 N_SAVE_POINTS = 100
52
53 # Don't change these values unless you know what you're doing.
54 N_INP = 784
55 N_NEURONS = 400
56 V_EXC_REST = -65 * mV
57 V_INH_REST = -60 * mV
58 INTENSITY = 2
59
60 # Weights of exc->inh and inh->exc synapses
61 W_EXC_INH = 10.4
62 W_INH_EXC = 17.0
63
64 def save_npy(arr, path):
65 arr = np.array(arr)
66 print('%-9s %-15s => %-30s' % ('Saving', arr.shape, path))
67 np.save(path, arr)
68
69 def load_npy(path):
70 arr = np.load(path)
71 print('%-9s %-30s => %-15s' % ('Loading', path, arr.shape))
72 return arr
73
74 def read_mnist(training):
75 tag = 'train' if training else 't10k'
76 images = open(MNIST_PATH / ('%s-images-idx3-ubyte' % tag), 'rb')
77 images.read(4)
78 n_images = unpack('>I', images.read(4))[0]
79 n_rows = unpack(">I", images.read(4))[0]
80 n_cols = unpack(">I", images.read(4))[0]
81
82 labels = open(MNIST_PATH / ('%s-labels-idx1-ubyte' % tag), 'rb')
83 labels.read(4)
84 x = np.frombuffer(images.read(), dtype = np.uint8)
85 x = x.reshape(n_images, -1) / 8.0
86 y = np.frombuffer(labels.read(), dtype = np.uint8)
87 return x, y
88
89 def build_network(training):
90 eqs = '''
91 dv/dt = (v_rest - v + i_exc + i_inh) / tau_mem : volt (unless refractory)
92 i_exc = ge * -v : volt
93 i_inh = gi * (v_inh_base - v) : volt
94 dge/dt = -ge/(1 * ms) : 1
95 dgi/dt = -gi/(2 * ms) : 1
96 dtimer/dt = 1 : second
97 '''
98 reset = 'v = %r; timer = 0 * ms' % V_EXC_REST
99 if training:
100 exc_eqs = eqs + '''
101 dtheta/dt = -theta / (1e7 * ms) : volt
102 '''
103 arr_theta = np.ones(N_NEURONS) * 20 * mV
104 reset += '; theta += 0.05 * mV'
105 else:
106 exc_eqs = eqs + '''
107 theta : volt
108 '''
109 arr_theta = load_npy(DATA_PATH / 'theta.npy') * volt
110 exc_eqs = Equations(exc_eqs,
111 tau_mem = 100 * ms,
112 v_rest = V_EXC_REST,
113 v_inh_base = -100 * mV)
114 # Note that this neuron has a bit of un unusual refractoriness mechanism:
115 # The membrane potential is clamped for 5ms, but spikes are prevented for 50ms
116 # This has been taken from the original code.
117 ng_exc = NeuronGroup(
118 N_NEURONS, exc_eqs,
119 threshold = 'v > (theta - 72 * mV) and (timer > 50 * ms)',
120 refractory = 5 * ms,
121 reset = reset,
122 method = 'euler',
123 name = 'exc')
124 ng_exc.v = V_EXC_REST
125 ng_exc.theta = arr_theta
126
127 inh_eqs = Equations(eqs,
128 tau_mem = 10 * ms,
129 v_rest = V_INH_REST,
130 v_inh_base = -85 * mV)
131 ng_inh = NeuronGroup(N_NEURONS, inh_eqs,
132 threshold = 'v > -40 * mV',
133 refractory = 2 * ms,
134 reset = 'v = -45 * mV',
135 method = 'euler',
136 name = 'inh')
137 ng_inh.v = V_INH_REST
138
139 syns_exc_inh = Synapses(ng_exc, ng_inh,
140 on_pre = 'ge_post += %f' % W_EXC_INH)
141 syns_exc_inh.connect(j = 'i')
142
143 syns_inh_exc = Synapses(ng_inh, ng_exc,
144 on_pre = 'gi_post += %f' % W_INH_EXC)
145 syns_inh_exc.connect("i != j")
146
147 pg_inp = PoissonGroup(N_INP, 0 * Hz, name = 'inp')
148
149 # During training, inp->exc synapse weights are plastic.
150 model = 'w : 1'
151 on_post = ''
152 on_pre = 'ge_post += w'
153 if training:
154 on_pre += '; pre = 1.; w = clip(w - 0.0001 * post1, 0, 1.0)'
155 on_post += 'post2bef = post2; w = clip(w + 0.01 * pre * post2bef, 0, 1.0); post1 = 1.; post2 = 1.'
156 model += '''
157 post2bef : 1
158 dpre/dt = -pre/(20 * ms) : 1 (event-driven)
159 dpost1/dt = -post1/(20 * ms) : 1 (event-driven)
160 dpost2/dt = -post2/(40 * ms) : 1 (event-driven)
161 '''
162 weights = (np.random.random(N_INP * N_NEURONS) + 0.01) * 0.3
163 else:
164 weights = load_npy(DATA_PATH / 'weights.npy')
165
166 syns_inp_exc = Synapses(
167 pg_inp, ng_exc,
168 model = model,
169 on_pre = on_pre,
170 on_post = on_post,
171 name = 'inp_exc'
172 )
173 syns_inp_exc.connect(True)
174 syns_inp_exc.delay = 'rand() * 10 * ms'
175 syns_inp_exc.w = weights
176
177 exc_mon = SpikeMonitor(ng_exc, name = 'sp_exc')
178 net = Network([pg_inp, ng_exc, ng_inh,
179 syns_inp_exc, syns_exc_inh, syns_inh_exc,
180 exc_mon])
181 # Initialize
182 net.run(0 * ms)
183 return net
184
185 def show_sample(net, sample, intensity):
186 exc_mon = net['sp_exc']
187 prev = exc_mon.count[:]
188 net['inp'].rates = sample * intensity * Hz
189 net.run(350 * ms)
190 # Don't count spikes occuring during the 150 ms rest.
191 next = exc_mon.count[:]
192 net['inp'].rates = 0 * Hz
193 net.run(150 * ms)
194 pat = next - prev
195 cnt = np.sum(pat)
196 if cnt < 5:
197 return show_sample(net, sample, intensity + 1)
198 return pat
199
200 def predict(groups, rates):
201 return np.argmax([rates[grp].mean() for grp in groups])
202
203 def test():
204 conf = np.zeros((10, 10))
205 assign = np.load(DATA_PATH / 'assign.npy')
206 groups = [np.where(assign == i)[0] for i in range(10)]
207
208 X, Y = read_mnist(False)
209 net = build_network(False)
210 for i in progressbar(range(N_TEST)):
211 ix = randrange(len(X))
212 exc = show_sample(net, X[ix], INTENSITY)
213 guess = predict(groups, exc)
214 real = Y[ix]
215 conf[real, guess] += 1
216
217 print('Accuracy: %6.3f' % (np.trace(conf) / np.sum(conf)))
218 conf = conf/conf.sum(axis=1)[:,None]
219 print(np.around(conf, 2))
220 save_npy(conf, DATA_PATH / 'confusion.npy')
221
222 def normalize_plastic_weights(syns):
223 conns = np.reshape(syns.w, (N_INP, N_NEURONS))
224 col_sums = np.sum(conns, axis = 0)
225 factors = 78./ col_sums
226 conns *= factors
227 syns.w = conns.reshape(-1)
228
229 def stats(net):
230 tick = defaultclock.timestep[:]
231 cnt = np.sum(net['sp_exc'].count[:])
232
233 inp_exc = net['inp_exc']
234 w_mu = np.mean(inp_exc.w)
235 w_std = np.std(inp_exc.w)
236
237 exc = net['exc']
238 theta = exc.theta / mV
239 theta_mu = np.mean(theta)
240 theta_sig = np.std(theta)
241 return [tick, cnt, w_mu, w_std, theta_mu, theta_sig]
242
243 def train():
244 X, Y = read_mnist(True)
245 n_samples = X.shape[0]
246 net = build_network(True)
247 rows = [stats(net) + [-1]]
248 w_hist = [np.array(net['inp_exc'].w)]
249
250 ratio = max(N_TRAIN // N_SAVE_POINTS, 1)
251 for i in progressbar(range(N_TRAIN)):
252 ix = i % n_samples
253 normalize_plastic_weights(net['inp_exc'])
254 show_sample(net, X[ix], INTENSITY)
255 rows.append(stats(net) + [Y[ix]])
256 if i % ratio == 0:
257 w_hist.append(np.array(net['inp_exc'].w))
258
259 save_npy(rows, DATA_PATH / 'train_stats.npy')
260 save_npy(w_hist, DATA_PATH / 'train_w_hist.npy')
261 save_npy(net['inp_exc'].w, DATA_PATH / 'weights.npy')
262 save_npy(net['exc'].theta, DATA_PATH / 'theta.npy')
263
264 def observe():
265 X, Y = read_mnist(True)
266 n_samples = X.shape[0]
267 net = build_network(False)
268 rows = [stats(net) + [-1]]
269 responses = defaultdict(list)
270
271 for i in progressbar(range(N_OBSERVE)):
272 ix = i % n_samples
273 sample = X[ix]
274 cls = Y[ix]
275 exc = show_sample(net, sample, INTENSITY)
276 rows.append(stats(net) + [Y[ix]])
277 responses[cls].append(exc)
278
279 res = np.zeros((10, N_NEURONS))
280 for cls, vals in responses.items():
281 res[cls] = np.array(vals).mean(axis = 0)
282
283 assign = np.argmax(res, axis = 0)
284 save_npy(assign, DATA_PATH / 'assign.npy')
285 save_npy(rows, DATA_PATH / 'observe_stats.npy')
286
287 def plot():
288 conf = np.load(DATA_PATH / "confusion.npy")
289
290 import matplotlib.pyplot as plt
291
292 plt.imshow(100*conf, interpolation="nearest", cmap=plt.cm.Blues)
293 for i, j in itertools.product(range(conf.shape[0]), range(conf.shape[1])):
294 if conf[i, j] == 0:
295 continue
296 plt.text(
297 j,
298 i,
299 f"{round(100*conf[i, j])}%",
300 horizontalalignment="center",
301 verticalalignment="center",
302 color="white" if conf[i, j] > 0.5 else "black",
303 )
304 plt.colorbar()
305 plt.xticks(range(10))
306 plt.yticks(range(10))
307 plt.xlabel("Predicted label")
308 plt.ylabel("True label")
309 plt.show()
310
311
312 if __name__ == '__main__':
313 seed(SEED)
314 rseed(SEED)
315 DATA_PATH.mkdir(parents = True, exist_ok = True)
316 cmds = dict(train=train, observe=observe, test=test, plot=plot)
317 cmds[MODE]()