/
analysis.py
153 lines (124 loc) · 5.01 KB
/
analysis.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# -*- coding: utf-8 -*-
""" Analysis. """
import os
import argparse
import chainer
from chainer import serializers
from chainer import cuda
#import chainer.functions as F
xp = cuda.cupy
from model import network
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
def load_data(N=1, dt=5e-3, num_time=20, max_fr=60):
""" geneate input data. """
_, test = chainer.datasets.get_mnist()
x = np.zeros((N, 784, num_time)) # 784=28x28
y = np.zeros(N)
for i in tqdm(range(N)):
fr = max_fr * np.repeat(np.expand_dims(np.heaviside(test[i][0],0), 1), num_time, axis=1)
x[i] = np.where(np.random.rand(784, num_time) < fr*dt, 1, 0)
y[i] = test[i][1]
return x.astype(np.float32), y.astype(np.int8)
def plot_activation(model, N, dt, num_time, n_mid,
n_out, max_fr, gpu, savefigname):
x, y = load_data(N=N, dt=dt, num_time=num_time, max_fr=max_fr)
idx = 0
check_x = np.sum(x[idx], axis=1)
fig = plt.figure(figsize=(6, 4))
ax1 = fig.add_subplot(1, 2, 1)
ax1.set_title("Sum of all input spikes\n label : "+str(y[idx]))
ax1.imshow(np.reshape(check_x, (28, 28)))
if gpu >= 0:
cuda.get_device_from_id(0).use()
model.to_gpu()
x = cuda.cupy.array(x)
y = cuda.cupy.array(y)
with chainer.using_config('train', False):
loss, accuracy, h1_list, h2_list, h3_list, out_list = model(x, y)
h1_all = np.zeros((num_time, N, n_mid))
h2_all = np.zeros((num_time, N, n_mid))
out_all = np.zeros((num_time, N, n_out))
for i in tqdm(range(num_time), desc="Getting activation"):
h1_all[i] = cuda.to_cpu(h1_list[i].data)
h2_all[i] = cuda.to_cpu(h2_list[i].data)
out_all[i] = cuda.to_cpu(out_list[i].data)
t = np.arange(1, num_time+1)*dt*1000
"""
plt.figure(figsize=(4,4))
plt.ylim(-0.5, n_mid-0.5)
plt.ylabel("# Unit")
plt.xlabel("Simulation Time(ms)")
for i in range(n_mid):
spk = np.where(h1_all[:, idx, i]==1, i, -1)
plt.scatter(t, spk, color="r",
s=0.1)
plt.savefig("h1.png")
plt.figure(figsize=(4,4))
plt.ylim(-0.5, n_mid-0.5)
plt.ylabel("# Unit")
plt.xlabel("Simulation Time(ms)")
for i in range(n_mid):
spk = np.where(h2_all[:, idx, i]==1, i, -1)
plt.scatter(t, spk, color="r",
s=0.1)
plt.savefig("h2.png")
"""
ax2 = fig.add_subplot(1, 2, 2)
ax2.set_title("Spikes of the output units")
ax2.set_ylabel("Output unit #")
ax2.set_xlabel("Simulation Time(ms)")
ax2.set_ylim(-0.5, n_out-0.5)
ax2.set_xlim(0, num_time+1)
ax2.set_yticks(np.arange(0, n_out).tolist())
for i in range(n_out):
spk = np.where(out_all[:, idx, i]==1, i, -1)
ax2.scatter(t, spk, color="r", marker="|")
plt.tight_layout()
plt.savefig(savefigname)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--gpu', '-g', type=int, default=-1,
help='GPU number to training.')
parser.add_argument('--model', '-m', type=str, default='./results/model',
help='Load saved model (model filename).')
parser.add_argument('--batch', '-b', type=int, default=32,
help='Mini batch size.')
parser.add_argument('--epoch', '-e', type=int, default=100,
help='Total training epoch.')
parser.add_argument('--dt', '-dt', type=int, default=1e-3,
help='Simulation time step size (sec).')
parser.add_argument('--ndata', '-nd', type=int, default=1,
help='The number of analysis trials.')
parser.add_argument('--freq', '-f', type=float, default=100,
help='Input signal maximum frequency (Hz).')
parser.add_argument('--time', '-t', type=int, default=100,
help='Total simulation time steps.')
args = parser.parse_args()
img_save_dir = "./imgs/"
os.makedirs(img_save_dir, exist_ok=True)
n_mid = 256
n_out = 10
chainer.global_config.autotune = True
if args.gpu >= 0:
# Make a specified GPU current
model = network.SNU_Network(n_in=784, n_mid=n_mid, n_out=n_out,
num_time=args.time, gpu=True,
test_mode=True)
chainer.backends.cuda.get_device_from_id(args.gpu).use()
model.to_gpu() # Copy the model to the GPU
else:
model = network.SNU_Network(n_in=784, n_mid=n_mid, n_out=n_out,
num_time=args.time, gpu=False,
test_mode=True)
if args.model != None:
print( "Loading model from " + args.model)
serializers.load_npz(args.model, model)
plot_activation(model=model, N=args.ndata, dt=args.dt,
num_time=args.time, n_mid=n_mid,
n_out=n_out,
max_fr=args.freq, gpu=args.gpu,
savefigname=img_save_dir+"results.png")
if __name__ == '__main__':
main()