-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalysis.py~
More file actions
285 lines (217 loc) · 9.07 KB
/
Copy pathanalysis.py~
File metadata and controls
285 lines (217 loc) · 9.07 KB
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from chainer import Variable, cuda
import scipy.stats as ss
class Analysis(object):
def __init__(self, model, fname=None, gpu=-1):
self.fname = fname
self.model = model
self.xp = np if gpu == -1 else cuda.cupy
def regression_analysis(self, X, T):
self.model.predictor.reset_state()
# check if we are in train or test mode (e.g. for dropout)
self.model.predictor.test = True
self.model.predictor.train = False
Y = []
for step in xrange(X.shape[0]):
x = Variable(self.xp.asarray(X[step][None]), True)
Y.append(self.model.predict(x))
if step == 0:
H = [[self.model.predictor.h[i].data[0]] for i in xrange(len(self.model.predictor.h))]
else:
_ = [H[i].append(self.model.predictor.h[i].data[0]) for i in xrange(len(self.model.predictor.h))]
H = [self.xp.asarray(H[i]) for i in xrange(len(H))]
Y = np.squeeze(self.xp.asarray(Y))
[nexamples, nregressors] = Y.shape
plt.clf()
plt.subplot(121)
colors = cm.rainbow(np.linspace(0, 1, nregressors))
for i in range(nregressors):
plt.scatter(T[:, i], Y[:, i], c=colors[i,:])
plt.hold('on')
plt.axis('equal')
plt.grid(True)
plt.xlabel('Observed value')
plt.ylabel('Predicted value')
plt.title('Scatterplot')
plt.subplot(122)
R = np.zeros([nregressors,1])
for i in range(nregressors):
R[i] = ss.pearsonr(np.squeeze(T[:,i]),np.squeeze(Y[:,i]))[0]
plt.hist(R, np.min([nregressors, 50]), normed=1, facecolor='black')
plt.grid(True)
plt.xlabel('Pearson correlation')
plt.title('Histogram of Pearson correlations')
print 'Correlation between predicted and observed outputs: {0}'.format(np.mean(R))
if self.fname:
plt.savefig(self.fname + '_regression_analysis.png')
else:
plt.show()
def classification_analysis(self, X, T,trial_length=None):
self.model.predictor.reset_state()
# check if we are in train or test mode (e.g. for dropout)
self.model.predictor.test = True
self.model.predictor.train = False
Y = []
for step in xrange(X.shape[0]):
x = Variable(self.xp.asarray(X[step][None]), True)
Y.append(self.model.predict(x))
if step == 0:
H = [[self.model.predictor.h[i].data[0]] for i in xrange(len(self.model.predictor.h))]
else:
_ = [H[i].append(self.model.predictor.h[i].data[0]) for i in xrange(len(self.model.predictor.h))]
if step % trial_length == 0:
self.model.predictor.reset_state()
H = [self.xp.asarray(H[i]) for i in xrange(len(H))]
Y = np.squeeze(self.xp.asarray(Y))
[nexamples, nregressors] = Y.shape
# compute count matrix
count_mat = np.zeros([nregressors, nregressors])
conf_mat = np.zeros([nregressors, nregressors])
for i in range(nregressors):
# get predictions for trials with real class equal to i
clf = np.argmax(Y[T==i],axis=1)
for j in range(nregressors):
count_mat[i,j] = np.sum(clf == j)
conf_mat[i] = count_mat[i]/np.sum(count_mat[i])
# print accuracy
clf = np.argmax(Y, axis=1)
print 'Classification accuracy: {0}'.format(np.mean(clf==T))
plt.clf()
plt.subplot(121)
plt.imshow(count_mat,interpolation=None)
plt.xlabel('Predicted class')
plt.ylabel('True class')
plt.xticks(np.arange(nregressors))
plt.gca().set_xticklabels([str(item) for item in 1+np.arange(nregressors)])
plt.yticks(np.arange(nregressors))
plt.gca().set_yticklabels([str(item) for item in 1+np.arange(nregressors)])
plt.colorbar()
plt.title('Count matrix')
plt.subplot(122)
plt.imshow(conf_mat,interpolation=None)
plt.xlabel('Predicted class')
plt.ylabel('True class')
plt.xticks(np.arange(nregressors))
plt.gca().set_xticklabels([str(item) for item in 1 + np.arange(nregressors)])
plt.yticks(np.arange(nregressors))
plt.gca().set_yticklabels([str(item) for item in 1 + np.arange(nregressors)])
plt.colorbar()
plt.title('Confusion matrix')
if self.fname:
plt.savefig(self.fname + '_classification_analysis.png')
else:
plt.show()
def accuracy(self, supervised_data):
"""
Return overall accuracy, calculated in batches (much faster).
:param supervised_data: SupervisedData object
"""
self.model.predictor.reset_state()
# check if we are in train or test mode (e.g. for dropout)
self.model.predictor.test = True
self.model.predictor.train = False
Y = []
T = []
for data in supervised_data:
x = Variable(self.xp.asarray(data[0]), True)
Y.append(np.argmax(self.model.predict(x),axis=1))
T.append(data[1])
Y = np.squeeze(np.asarray(Y))
T = np.squeeze(np.asarray(T))
acc = np.mean(Y==T)
return acc
def weight_matrix(self, W):
"""
Plot weight matrix
:param fname: file name
:param W: N x M weight matrix
"""
plt.clf()
plt.pcolor(W)
plt.title('Weight matrix')
if self.fname:
plt.savefig(self.fname + '_weight_matrix.png')
else:
plt.show()
def functional_connectivity(self,data):
"""
Plot functional connectivity matrix (full correlation)
# perform an analysis on the optimal model
z = [validation_data.X]
[z.append(H[i]) for i in range(len(H))]
z.append(Y)
ana.functional_connectivity(z)
:param data: list containing T x Mi timeseries data
"""
x = np.hstack(data)
M = np.corrcoef(x.transpose())
plt.clf()
plt.pcolor(M)
plt.title('Functional connectivity')
if self.fname:
plt.savefig(self.fname + '_functional_connectivity.png')
else:
plt.show()
def classification_analysis_Cifar(self, X, T, trial_length=None):
self.model.predictor.reset_state()
# check if we are in train or test mode (e.g. for dropout)
self.model.predictor.test = True
self.model.predictor.train = False
Y = []
for step in xrange(X.shape[0]):
x = Variable(self.xp.asarray(X[step][None]), True)
Y.append(self.model.predict(x))
if step == 0:
H = [[self.model.predictor.h[i].data[0]] for i in xrange(len(self.model.predictor.h))]
else:
_ = [H[i].append(self.model.predictor.h[i].data[0]) for i in xrange(len(self.model.predictor.h))]
if step % trial_length == 0:
self.model.predictor.reset_state()
H = [self.xp.asarray(H[i]) for i in xrange(len(H))]
Y = np.squeeze(self.xp.asarray(Y))
[nexamples, nregressors] = Y.shape
plt.clf()
# compute count matrix
count_mat = np.zeros([nregressors, nregressors])
conf_mat = np.zeros([nregressors, nregressors])
for i in range(nregressors):
# get predictions for trials with real class equal to i
clf = np.argmax(Y[T == i], axis=1)
for j in range(nregressors):
count_mat[i, j] = np.sum(clf == j)
conf_mat[i] = count_mat[i] / np.sum(count_mat[i])
# print accuracy
clf = np.argmax(Y, axis=1)
clft=np.mean(np.reshape(clf,(200,trial_length)) == np.reshape(T,(200,trial_length)),axis=0)
if self.fname:
np.savetxt(self.fname + '_class_accuracy',clft,fmt='%.4f', delimiter=',')
else:
print 'Classification accuracy: {0}'.format(clft)
plt.subplot(121)
plt.imshow(count_mat, interpolation=None)
plt.xlabel('Predicted class')
plt.ylabel('True class')
plt.xticks(np.arange(nregressors))
plt.gca().set_xticklabels([str(item) for item in 1 + np.arange(nregressors)])
plt.yticks(np.arange(nregressors))
plt.gca().set_yticklabels([str(item) for item in 1 + np.arange(nregressors)])
plt.colorbar()
plt.title('Count matrix')
plt.subplot(122)
plt.imshow(conf_mat, interpolation=None)
plt.xlabel('Predicted class')
plt.ylabel('True class')
plt.xticks(np.arange(nregressors))
plt.gca().set_xticklabels([str(item) for item in 1 + np.arange(nregressors)])
plt.yticks(np.arange(nregressors))
plt.gca().set_yticklabels([str(item) for item in 1 + np.arange(nregressors)])
plt.colorbar()
plt.title('Confusion matrix')
if self.fname:
plt.savefig(self.fname + '_classification_analysis.png')
else:
plt.show()