Repository navigation
Expand file tree
/
Copy pathfeasel.py
More file actions
542 lines (423 loc) · 14.5 KB
/
Copy pathfeasel.py
File metadata and controls
542 lines (423 loc) · 14.5 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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
"""
feasel.plot.feasel
==================
"""
# external packages
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm, colors
from matplotlib.lines import Line2D
# internal packages
from .neural_network import NeuralNetworkVisualizer
class FeaselVisualizer(NeuralNetworkVisualizer):
def __init__(self, model_container):
super().__init__(model_container)
@property
def _pruned(self):
return self._is_pruned()
@property
def data(self):
return self.container.data
@property
def log(self):
return self.container.callback.log
@property
def params(self):
return self.container.params.callback
def _is_pruned(self):
"""
Checks whether feature selection algorithm already pruned a feature or not.
If not, the class will not plot anything, since the necessary information
is not provided.
Returns
-------
_pruned : bool
True, if network specified in the container is pruned at least once.
Raises
------
NotImplementedError
If the feature selection algorithm did not prune anything.
"""
_pruned = self.log._pruned
if not _pruned:
raise NotImplementedError("The feature selection did not return "
"anything printworthy.")
return _pruned
def pruning_history(self):
"""
Plots the evaluation history of the feature selection algorithm and marks
the epochs where features have been pruned with vertical lines.
Returns
-------
fig : matplotlib.pyplot.figure
The current figure.
"""
if not self._pruned:
return
fig = plt.figure('Pruning History')
plt.clf()
ax = fig.add_subplot(111)
ax = self._pruning_history(ax)
return fig
def _pruning_history(self, ax):
"""
Plots the pruning history of the feature selection algorithm where the
number of features is plotted over the epochs.
Parameters
----------
ax : axes
The axes where the pruning history is plotted.
Returns
-------
ax : axes
The axes where the pruning history is plotted.
"""
# plot content and informative variables
n_prunes, n_features = self.log.m_k.shape
F = self.log.f_n.astype(int)
E = self.log.e_prune
# plotting settings for the pruning history
ax.plot(E, F, color = "k", marker = ".")
ax.set_xlabel("epoch")
ax.set_ylabel("number of features")
y_max = int(F[0]) * 1.05
if self.log.e_stop:
np.append(E, self.log.e_stop)
if E.size > 2:
# first prune
first = int(E[1])
ax.axvline(first, color = "k", ls = "-.")
ax.text(E[1], y_max/2,
f"first prune: $e={first}$",
rotation = "vertical",
horizontalalignment = "center",
verticalalignment = "center", color = "k",
bbox=dict(facecolor='w'))
# last prune
last = int(E[-2])
ax.axvline(last, color = "k", ls = "-.")
ax.text(last, y_max / 2,
f"last prune: $e={last}$",
rotation = "vertical",
horizontalalignment = "center",
verticalalignment = "center", color = "k",
bbox=dict(facecolor='w'))
elif E.size == 2:
# only prune
only = int(E[1])
ax.axvline(only, color = "k", ls = "-.")
ax.text(only, y_max / 2,
f"only prune: $e={only}$",
rotation = "vertical",
horizontalalignment = "center",
verticalalignment = "center", color = "k",
bbox=dict(facecolor='w'))
ax.set_ylim(0, F[0] * 1.05)
ax.set_xlim(0, E[-1])
ax.grid(True)
return ax
def mask_history(self, highlight=False):
"""
Provides a colorized history of the masks where brighter colors indicate
features that were pruned earlier in the training and darker colors
features pruned later.
Parameters
----------
highlight : bool
If True, it will highlight the remaining features. The default is False.
Returns
-------
fig : matplotlib.pyplot.figure
The current figure.
"""
if not self._pruned:
return
fig = plt.figure('Mask History')
plt.clf()
gs = fig.add_gridspec(1, 2, width_ratios=[1, 20])
# mask history:
ax1 = fig.add_subplot(gs[0, 1])
self._mask_history(ax1, highlight)
# colorbar:
ax2 = fig.add_subplot(gs[0, 0])
self._colorbar(fig, ax2)
return fig
def _mask_history(self, ax, highlight):
"""
Provides a colorized history of the masks where brighter colors indicate
features that were pruned earlier in the training and darker colors
features pruned later.
Parameters
----------
ax : axes
The axes where the mask history is plotted.
highlight : bool
If True, it will highlight the remaining features.
Returns
-------
ax : axes
The axes where the mask history is plotted.
"""
cmap = plt.get_cmap('Blues').reversed()
highlight_cmap = colors.ListedColormap([(0,0,0,0), 'orange'])
norm = colors.BoundaryNorm([0,1], highlight_cmap.N)
weights = self.log.m_k
n_prunes, n_features = weights.shape
# plotting settings for the mask history
masks = np.sum(weights, axis=0, keepdims=True)
masks = np.amax(masks) - masks
last = np.array(weights[-1], ndmin=2)
features = self.data.features
# pcolormesh is used to plot mask history if features are linearly
# distributed, i.e. equally distributed numbers that can be rescaled:
if self._check_linearity(features):
ax.imshow(masks, extent=[features[0], features[-1], -0.5, 0.5],
cmap=cmap, aspect='auto')
# plot of the remaining features
if highlight:
ax.imshow(last, cmap=highlight_cmap, norm=norm,
extent=[features[0], features[-1], -0.5, 0.5], aspect='auto')
line = [Line2D([0], [0], color='orange')]
label = ['remaining']
ax.legend(line, label)
else:
# plots an image with summed up weight matrices:
ax.imshow(masks, cmap=cmap, aspect="auto")
# enables 10 ticks in x-axis with strings
ratio = int(n_features / 10)
ax.set_xticks(np.arange(len(features))[::ratio])
ax.set_xticklabels(features[::ratio],
rotation=-45, ha='left')
if highlight:
ax.imshow(last, cmap=highlight_cmap, norm=norm, aspect='auto')
line = [Line2D([0], [0], color='orange')]
label = ['remaining']
ax.legend(line, label)
# y-axis
ax.set_yticks([])
ax.set_ylim(-0.5, 0.5)
ax.set_title('features', fontsize='medium')
ax.grid(False)
return ax
def _check_linearity(self, array):
"""
Checks the linearity of an array, to ensure correct xtick labels.
Parameters
----------
array : nd-array
The xtick-array.
Returns
-------
bool
True if xticks array is linear.
"""
try:
if len(np.unique(np.diff(array)) == 1):
return True
else:
return False
except:
return False
def _colorbar(self, fig, ax):
"""
Generates a colorbar that maps the feature masks onto the epoch that the
specific feature has been pruned.
Parameters
----------
fig : figure
The figure where the colorbar is plotted.
ax : axes
The axes where the colorbar is plotted.
Returns
-------
colorbar : colorbar
The colorbar representing the epochs where features have been pruned.
"""
cmap = self.default.im_cmap.reversed()
n_prunes, n_features = self.log.m_k.shape
weight_sum = np.sum(self.log.m_k, axis=0)
if n_prunes > 6:
n_ticks = 6
elif n_prunes < 2:
n_ticks = 2
else:
n_ticks = n_prunes
ticks = np.linspace(0, 1, n_ticks, endpoint=True)
n_masked = np.round(np.linspace(0, np.amax(weight_sum), n_ticks), 1)
colorbar = fig.colorbar(cm.ScalarMappable(cmap=cmap),
ticks=ticks, cax=ax, aspect=20)
# y axis:
colorbar.ax.set_yticklabels(n_masked)
colorbar.ax.yaxis.set_ticks_position("left")
colorbar.ax.yaxis.set_label_position("left")
colorbar.ax.invert_yaxis()
colorbar.set_label("times masked $[\mathrm{I/O}]$")
return colorbar
def input_reduction(self, plot='both', highlight=False):
"""
Plots the reduction of the input nodes over the epoch and a color gradient
that indicates the importance of features regarding their mask history.
Darker colors indicate more important features whereas brighter colors
stand for features that have been pruned early and are not that important.
Parameters
----------
plot : str, optional
Defines which plot is shown. Possible arguments are 'mask', 'prune' or
'both'. The default is 'both'.
highlight : bool, optional
Is only needed for the mask history. If True, it highlights the remaining
features. The default is False.
Raises
------
NameError
If argument in 'plot' is not valid.
Returns
-------
fig : matplotlib.pyplot.figure
The current figure.
"""
if not self._pruned:
return
fig = plt.figure("Input Reduction")
plt.clf()
if plot == "both":
gs = fig.add_gridspec(2, 2, width_ratios = [1, 20])
ax1 = fig.add_subplot(gs[0, :])
ax1 = self._pruning_history(ax1)
ax2 = fig.add_subplot(gs[1, 0])
ax2 = self._colorbar(fig, ax2)
ax3 = fig.add_subplot(gs[1, 1])
ax3 = self._mask_history(ax3, highlight)
elif plot == 'mask':
plt.close()
self.mask_history()
fig = plt.gcf()
fig.canvas.set_window_title("Input Reduction")
elif plot == 'prune':
plt.close()
self.pruning_history()
fig = plt.gcf()
fig.canvas.set_window_title("Input Reduction")
else:
raise NameError(f"'{plot}' is not a valid argument for 'plot'. "
"Try 'mask', 'prune' or 'both' instead.")
return fig
def evaluation_history(self):
"""
Plots the history of the evaluation metric used for the feature selection.
Each pruning epoch is marked by a vertical line.
Returns
-------
fig : matplotlib.pyplot.figure
The current figure.
"""
if not self._pruned:
return
log = self.log
trigger = self.container.callback.trigger
params = self.params
colors = [self.default.c_cmap(0), # used for accuracy-based FS
self.default.c_cmap(4), # used for loss-based FS
self.default.c_cmap(8), # used for the gradient of the loss
self.default.c_cmap(16)] # used for the threshold
if params.eval_metric in ['loss', 'val_loss']:
fig = plt.figure('Pruning History')
plt.clf()
# two subplots are needed since the evaluation is based on the gradient
# of the loss and not on the loss itself
ax1 = fig.add_subplot(211)
ax1.plot(trigger.value_l, color=colors[1], label='loss')
ax1.tick_params(labelbottom=False)
ax2 = fig.add_subplot(212, sharex=ax1)
ax2.plot(trigger.gradient_l, color=colors[2], label='gradient')
ax2.plot(trigger.thresh_l, color=colors[3], label='threshold')
ax2.set_ylabel('gradient')
ax2.set_xlabel('epoch')
ax2.legend(loc='lower right')
for ax in [ax1, ax2]:
for i in log.pruning_epochs:
ax.axvline(i, c='k', lw=0.5)
else:
fig = plt.figure('Evaluation History')
plt.clf()
# only one axis is needed for the history
ax1 = fig.add_subplot(111)
ax1.plot(trigger.value_l, color=colors[0], label='accuracy')
ax1.plot(trigger.thresh_l, color=colors[3], label='threshold')
ax1.legend(loc='lower right')
ax1.set_xlabel('epoch')
for i in log.e_prune:
ax1.axvline(i, c='k', lw=0.5)
x = np.arange(len(trigger.value_l))
ax1.set_xlim(x[0], x[-1])
ax1.set_ylabel(f'{params.eval_metric}')
return fig
def FOI(self, pruning_step=0, show_loss=False):
"""
Generates a bar and box plot where the decision metrics for the feature
pruning are shown.
Parameters
----------
pruning_step : int or list, optional
The pruning step(s) that shall be investigated. A list of integers is
also allowed. If None, it will show all feature pruning steps. The
default is 0, which implies displaying the last pruning step.
show_loss : bool, optional
If True, it will show a box plot for all evaluated samples during the
pruning procedure. The default is False.
Returns
-------
fig : matplotlib.pyplot.figure
The current figure.
"""
if not self._pruned:
return
pruning_steps = np.array(pruning_step, ndmin=1)
for i in pruning_steps:
# the masks for each pruning step (applied on second subplot):
try:
# data
features = self.data.features
mask_k = self.log.m_k[1:-1][i-1]
mask_p = self.log.m_p[1:-1][i-1]
f_loss = self.log.f_loss[i-1]
f_eval = self.log.f_eval[i-1]
except:
n_p_max = len(self.log.m_k)
raise ValueError(f'Step {i-1} is out of range 1-{n_p_max} steps.')
colors = [self.default.c_cmap(0), self.default.c_cmap(6)]
fig = plt.figure(f'Feature evaluation losses at {i}. Prune')
plt.clf()
# first subplot: box plot for the entropy of all samples and features
if show_loss:
ax1 = fig.add_subplot(211)
ax1.boxplot(f_loss.T, labels=np.arange(self.container.n_in),
flierprops=dict(marker='+', markersize=4))
# y-axis
ax1.set_ylabel(r'loss $\mathcal{L}_{f,s}$')
# x-axis
ax1.set_xlim(0.5, self.container.n_in+0.5)
ax1.tick_params(labelbottom=False)
ax2 = fig.add_subplot(212, sharex=ax1)
else:
ax2 = fig.add_subplot(111)
# second subplot: bar plot with feature selection metric and masks
ax2.bar(np.argwhere(mask_k).squeeze()+1,
f_eval[mask_k],
color=colors[0], label='keep')
ax2.bar(np.argwhere(mask_p).squeeze()+1,
f_eval[mask_p],
color=colors[1], label='prune')
ax2.set_xlim(0.5, self.container.n_in + 0.5)
# enables 10 ticks in x-axis with strings
ratio = int(len(features) / 10)
ax2.set_xticks(np.arange(len(features))[::ratio]+1)
ax2.set_xticklabels(features[::ratio], rotation=-45, ha='left')
ax2.set_axisbelow(True)
ax2.grid(True, axis='y')
# labels:
label = r'$\mathcal{I}_f$'
ax2.set_ylabel(f'featuresOI {label}')
ax2.set_xlabel('feature $f$')
ax2.legend(loc='upper right')
return fig