1
+ print ('vizualize filters' )
2
+
3
+ from hack import hack
4
+ hack ()
5
+
6
+ from keras .applications import VGG16
7
+ from keras import backend as K
8
+
9
+ model = VGG16 (weights = 'imagenet' , include_top = False )
10
+
11
+ # model.summary()
12
+
13
+ layer_name = 'block3_conv1'
14
+
15
+ filter_index = 0
16
+
17
+ layer_output = model .get_layer (layer_name ).output
18
+ loss = K .mean (layer_output [:, :, :, filter_index ])
19
+
20
+ grads = K .gradients (loss , model .input )[0 ]
21
+
22
+ grads /= (K .sqrt (K .mean (K .square (grads )))) + 1e-5
23
+
24
+ iterate = K .function ([model .input ], [loss , grads ])
25
+
26
+ import numpy as np
27
+
28
+ loss_value , grads_value = iterate ([np .zeros ((1 , 150 , 150 , 3 ))])
29
+
30
+ input_img_data = np .random .random ((1 , 150 , 150 , 0 )) * 20 + 128.
31
+
32
+ def deprocess_image (x ):
33
+ x -= x .mean ()
34
+ x /= (x .std () + 1e-5 )
35
+ x *= 0.1
36
+ x += 0.5
37
+ x = np .clip (x , 0 , 1 )
38
+ x *= 255
39
+ x = np .clip (x , 0 , 255 ).astype ('uint8' )
40
+ return x
41
+
42
+ def generate_pattern (layer_name , filter_index , size = 150 ):
43
+ layer_output = model .get_layer (layer_name ).output
44
+ loss = K .mean (layer_output [:, :, :, filter_index ])
45
+
46
+ grads = K .gradients (loss , model .input )[0 ]
47
+
48
+ grads /= (K .sqrt (K .mean (K .square (grads ))) + 1e-5 )
49
+
50
+ iterate = K .function ([model .input ], [loss , grads ])
51
+
52
+ input_img_data = np .random .random ((1 , size , size , 3 )) * 25 + 128.
53
+
54
+ step = 1.
55
+ for i in range (40 ):
56
+ loss_value , grads_value = iterate ([input_img_data ])
57
+
58
+ input_img_data += grads_value * step
59
+
60
+ img = input_img_data [0 ]
61
+ return deprocess_image (img )
62
+
63
+ import matplotlib .pyplot as plt
64
+
65
+ # plt.imshow(generate_pattern('block3_conv1', 0))
66
+
67
+ # plt.show()
68
+
69
+ # layer_name = 'block1_conv1'
70
+ layer_name = 'block4_conv1'
71
+ size = 64
72
+ margin = 5
73
+
74
+ results = np .zeros ((8 * size + 7 * margin , 8 * size + 7 * margin , 3 ))
75
+
76
+ for i in range (8 ):
77
+ for j in range (8 ):
78
+ filter_img = generate_pattern (layer_name , i + (j * 8 ), size = size )
79
+
80
+ horizontal_start = i * size + i * margin
81
+ horizontal_end = horizontal_start + size
82
+ vertical_start = j * size + j * margin
83
+ vertical_end = vertical_start + size
84
+ results [horizontal_start : horizontal_end , vertical_start : vertical_end , :] = filter_img
85
+
86
+ plt .figure (figsize = (20 , 20 ))
87
+ plt .imshow (results )
88
+
89
+ plt .show ()
0 commit comments