-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalyze.py
More file actions
337 lines (255 loc) · 8.34 KB
/
analyze.py
File metadata and controls
337 lines (255 loc) · 8.34 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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import os
import json
import h5py
import matplotlib
import numpy as np
from matplotlib.axes import Axes
from pandas import DataFrame as DF
from matplotlib.figure import Figure
from matplotlib import pyplot as plt
ROOT = os.path.dirname(
os.path.abspath(__file__)
)
# 设置matplotlib正常显示中文与负号
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False
# 分析ResNet网络训练准确率函数
# 参数1:net_depth:网络深度(18, 50)
def analyze_train_log(net_depth: int):
figure = Figure(figsize=(25, 9), dpi=100)
ax_train = figure.add_subplot(121)
ax_test = figure.add_subplot(122)
type_list = ['FULL', 'Nbn', 'Nres', 'Nboth']
color_list = ['r', 'g', 'b', 'y']
for net_type, color in zip(type_list, color_list):
log_name = f'ResNet{net_depth}_{net_type}.json'
with open(
file = f'./model_data/{log_name}',
mode = 'r'
) as log_file:
log: dict = json.load(log_file)
epochs = list(
range(
1,
log['n_epochs'] + 1,
)
)
train_acc = log['train_acc_list']
test_acc = log['test_acc_list']
ax_train.plot(
epochs,
train_acc,
f'{color}o--',
label = f'ResNet{net_depth}_{net_type}'
)
ax_test.plot(
epochs,
test_acc,
f'{color}o-',
label = f'ResNet{net_depth}_{net_type}'
)
ax_train.set_ylim(0, 1.05)
ax_test.set_ylim(0, 1.05)
ax_train.set_xticks(epochs)
ax_test.set_xticks(epochs)
ax_train.set_xlabel('Epochs')
ax_test.set_xlabel('Epochs')
ax_train.set_ylabel('Train Accuracy')
ax_test.set_ylabel('Test Accuracy')
ax_train.set_title(f'ResNet{net_depth} 训练准确率')
ax_test.set_title(f'ResNet{net_depth} 测试准确率')
ax_train.legend()
ax_test.legend()
figure.savefig(
f'{ROOT}/result/' +
f'ResNet{net_depth}_acc.png'
)
# 分析 ResNet 网络训练梯度
def analyze_gradient(net_depth: int):
figure = Figure(figsize=(25, 9))
ax_shallow = figure.add_subplot(121)
ax_deep = figure.add_subplot(122)
type_list = ['FULL', 'Nbn', 'Nres', 'Nboth']
color_list = ['r', 'g', 'b', 'y']
for net_type, color in zip(type_list, color_list):
log_name = f'ResNet{net_depth}_{net_type}.json'
with open(
file = f'./model_data/{log_name}',
mode = 'r'
) as log_file:
log: dict = json.load(log_file)
shallow_grad = log['shallow_grad_info_list']
deep_grad = log['deep_grad_info_list']
shallow_grad = np.array(shallow_grad)
deep_grad = np.array(deep_grad)
shallow_grad = np.log10(shallow_grad)
deep_grad = np.log10(deep_grad)
backwards_num = list(
range(
len(shallow_grad)
)
)
ax_shallow.scatter(
backwards_num,
shallow_grad,
c = color,
label = net_type
)
ax_deep.scatter(
backwards_num,
deep_grad,
c = color,
label = net_type
)
ax_shallow.set_xticks(
range(1,len(backwards_num) - 1,500)
)
ax_deep.set_xticks(
range(1,len(backwards_num) - 1,500)
)
ax_shallow.set_ylim(-30, 0)
ax_deep.set_ylim(-30, 0)
ax_shallow.set_xlabel('反向传播次数')
ax_deep.set_xlabel('反向传播次数')
ax_shallow.set_ylabel('阶段1梯度平均绝对值')
ax_deep.set_ylabel('阶段4梯度平均绝对值')
ax_shallow.set_title(
f'ResNet{net_depth} ' +
'阶段1梯度平均绝对值与反向传播次数关系'
)
ax_deep.set_title(
f'ResNet{net_depth} ' +
'阶段4梯度平均绝对值与反向传播次数关系'
)
ax_shallow.legend()
ax_deep.legend()
figure.savefig(
f'{ROOT}/result/' +
f'ResNet{net_depth}_grad.png'
)
# 分析深层与浅层输出特征图的可分性
def analyze_fisher(net_depth):
type_list = ['FULL', 'Nres']
stage_list = ['stage1', 'stage4']
result_df = DF(
{
f'{net_depth}_FULL_stage1': [],
f'{net_depth}_FULL_stage4': [],
f'{net_depth}_Nres_stage1': [],
f'{net_depth}_Nres_stage4': [],
}
)
for net_type in type_list:
for stage in stage_list:
# 获取数据
with h5py.File(
f'{ROOT}/model_data/' +
f'mid_output.h5',
'r'
) as file:
# stage 输出的特征图
data = np.array(
file[
f'{net_depth}_{net_type}'
][stage]
)
# 特征图对应的类别标签
labels = np.array(
file[
f'{net_depth}_{net_type}'
][f'labels']
)
# 将数据按类别标签分类
label_dict = {}
for i in range(10):
label_dict[i] = data[
labels == i
].copy()
# 此处为了便于计算离散度矩阵,将数据展平
# 维度1:样本量 * 通道数
# 维度2:特征图面积
label_dict[i] = np.reshape(
label_dict[i],
(
label_dict[i].shape[0] * label_dict[i].shape[1],
-1
)
)
# 计算总体均值
mean = np.mean(
# 同上,将数据展平
np.reshape(
data,
(
data.shape[0] * data.shape[1],
-1
)
),
axis=0
)
# 计算各类别均值
mean_dict = {}
for i in range(10):
mean_dict[i] = np.mean(
label_dict[i],
axis=0
)
# 计算各类类内离散度矩阵
sw_dict = {}
for i in range(10):
sw_dict[i] = np.dot(
(label_dict[i] - mean_dict[i]).T,
(label_dict[i] - mean_dict[i])
)
sw = np.sum(
list(sw_dict.values()),
axis=0
)
# 计算类间离散度矩阵
sb_dict = {}
for i in range(10):
sb_dict[i] = len(label_dict[i]) * np.dot(
# numpy一维数组无法转置为列向量
# 这里增加一个维度
np.expand_dims(
mean_dict[i] - mean,
axis = 0
).T,
np.expand_dims(
mean_dict[i] - mean,
axis = 0
),
)
sb = np.sum(
list(sb_dict.values()),
axis=0
)
# 求 sw 与 sb 的迹
sw_trace = np.trace(sw)
sb_trace = np.trace(sb)
# 计算可分性判据
fisher = sb_trace / sw_trace
result_df[
f'{net_depth}_{net_type}_{stage}'
] = [fisher]
figure = Figure()
ax = figure.add_subplot(111)
ax.bar(
x = result_df.columns,
height = result_df.values[0]
)
ax.set_title(
f'ResNet{net_depth} ' +
'fisher可分性 柱状图'
)
ax.set_xlabel('stage')
ax.set_ylabel('fisher')
ax.set_ylim(
0, 0.015
)
figure.savefig(
f'{ROOT}/result/ResNet{net_depth}_fisher.png'
)
if __name__ == "__main__":
analyze_fisher(18)
analyze_fisher(50)