forked from sunprinceS/ML-Assignment3
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathp5.html
199 lines (162 loc) · 13.1 KB
/
p5.html
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
<!DOCTYPE html>
<html>
<link rel="shortcut icon" href="favicon.ico">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="highlight.css">
<meta name="author" content="ntumlta" >
<meta property="og:image" content="joy.png"/>
<title>Machine Learning (2017, Fall)</title>
<xmp theme="cerulean" style="display:none;">
# Problem 5: Analyze the Model by Visualizing Filters
Problem Description:
* use **Gradient Ascent** method mentioned in class to find the image that activates the selected filter the most and plot them (start from white noise).
* Feed an image in your validation set to the model, and plot the output of that filter
* Describe what you observed, and explain it
Hint:
* you can use other model with poor performance to see what is the difference
* you can also try to find which image will activate the specific class the most
* you can start from natural image (not white noise), and try to create the <a href="https://arxiv.org/pdf/1412.6572.pdf" target="_blank">**adversial image**</a>
## Lecture
<img src="lec.png" alt="Drawing" style="width: 1000px;"/>
## 範例
* **[Note] 請不要直接使用助教的圖來當成作業交上來**
* **[Note] 請不要使用這張範例圖**
<img src="17.png" alt="Drawing" style="width: 200px;"/>
* **[Note] colormap 請不要使用 Purples**
<img src="http://i.imgur.com/HdQ9oQU.png" alt="Drawing" style="width: 1300px;"/>
<img src="http://i.imgur.com/xEvPeW8.png" alt="Drawing" style="width: 1300px;"/>
## TA hour
<i class="fa fa-diamond"></i> Keywords: `keras.backend`, `gradients`
<div id="doc" class="markdown-body container-fluid" style="position: relative;"><h1 id="hw3-手把手-q5"><a class="anchor hidden-xs" href="#hw3-手把手-q5" title="hw3-手把手-q5"><span class="octicon octicon-link"></span></a>HW3 手把手 Q5</h1><pre><code class="python=3.6 hljs"><span class="hljs-comment">#!/usr/bin/env python</span>
<span class="hljs-comment"># -*- coding: utf-8 -*-</span>
<span class="hljs-keyword">import</span> os
<span class="hljs-keyword">import</span> sys
<span class="hljs-keyword">import</span> argparse
<span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt
<span class="hljs-keyword">from</span> keras.models <span class="hljs-keyword">import</span> load_model
<span class="hljs-keyword">from</span> keras <span class="hljs-keyword">import</span> backend <span class="hljs-keyword">as</span> K
<span class="hljs-keyword">from</span> termcolor <span class="hljs-keyword">import</span> colored,cprint
<span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">from</span> utils <span class="hljs-keyword">import</span> *
base_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
exp_dir = <span class="hljs-string">'exp'</span>
<span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> os.path.exists(exp_dir):
os.makedirs(exp_dir)
vis_dir = os.path.join(<span class="hljs-string">'image'</span>,<span class="hljs-string">'vis_layer'</span>)
<span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> os.path.exists(vis_dir):
os.makedirs(vis_dir)
filter_dir = os.path.join(<span class="hljs-string">'image'</span>,<span class="hljs-string">'vis_filter'</span>)
<span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> os.path.exists(filter_dir):
os.makedirs(filter_dir)
nb_class = <span class="hljs-number">7</span>
LR_RATE = <span class="hljs-number">2</span> * <span class="hljs-number">1e-2</span>
NUM_STEPS = <span class="hljs-number">200</span>
RECORD_FREQ = <span class="hljs-number">10</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">deprocess_image</span><span class="hljs-params">(x)</span>:</span>
<span class="hljs-string">"""
As same as that in problem 4.
"""</span>
<span class="hljs-keyword">return</span> x
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>:</span>
parser = argparse.ArgumentParser(prog=<span class="hljs-string">'visFilter.py'</span>,
description=<span class="hljs-string">'Visualize CNN filter.'</span>)
parser.add_argument(<span class="hljs-string">'--model'</span>,type=str,default=<span class="hljs-string">'simple'</span>,choices=[<span class="hljs-string">'simple'</span>,<span class="hljs-string">'NTUEE'</span>],
metavar=<span class="hljs-string">'<model>'</span>)
parser.add_argument(<span class="hljs-string">'--epoch'</span>,type=int,metavar=<span class="hljs-string">'<#epoch>'</span>,default=<span class="hljs-number">20</span>)
parser.add_argument(<span class="hljs-string">'--mode'</span>,type=int,metavar=<span class="hljs-string">'<visMode>'</span>,default=<span class="hljs-number">1</span>,choices=[<span class="hljs-number">1</span>,<span class="hljs-number">2</span>])
parser.add_argument(<span class="hljs-string">'--batch'</span>,type=int,metavar=<span class="hljs-string">'<batch_size>'</span>,default=<span class="hljs-number">64</span>)
parser.add_argument(<span class="hljs-string">'--idx'</span>,type=int,metavar=<span class="hljs-string">'<suffix>'</span>,required=<span class="hljs-keyword">True</span>)
args = parser.parse_args()
store_path = <span class="hljs-string">"{}_epoch{}_{}"</span>.format(args.model,args.epoch,args.idx)
print(colored(<span class="hljs-string">"Loading model from {}"</span>.format(store_path),<span class="hljs-string">'yellow'</span>,attrs=[<span class="hljs-string">'bold'</span>]))
model_path = os.path.join(exp_dir,store_path,<span class="hljs-string">'model.h5'</span>)
emotion_classifier = load_model(<span class="hljs-string">'model/model-{}.h5'</span>.format(args.epoch))
layer_dict = dict([layer.name, layer] <span class="hljs-keyword">for</span> layer <span class="hljs-keyword">in</span> emotion_classifier.layers[<span class="hljs-number">1</span>:])
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">normalize</span><span class="hljs-params">(x)</span>:</span>
<span class="hljs-comment"># utility function to normalize a tensor by its L2 norm</span>
<span class="hljs-keyword">return</span> x / (K.sqrt(K.mean(K.square(x))) + <span class="hljs-number">1e-5</span>)
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">grad_ascent</span><span class="hljs-params">(num_step,input_image_data,iter_func)</span>:</span>
<span class="hljs-string">"""
Implement this function!
"""</span>
<span class="hljs-keyword">return</span> filter_images
input_img = emotion_classifier.input
<span class="hljs-comment"># visualize the area CNN see</span>
<span class="hljs-keyword">if</span> args.mode == <span class="hljs-number">1</span>:
collect_layers = list()
collect_layers.append(K.function([input_img,K.learning_phase()],[layer_dict[<span class="hljs-string">'zero_padding2d_1'</span>].output]))
dev_feat = load_pickle(<span class="hljs-string">'fer2013/test_with_ans_pixels.pkl'</span>)
dev_label = load_pickle(<span class="hljs-string">'fer2013/test_with_ans_labels.pkl'</span>)
choose_id = <span class="hljs-number">17</span>
photo = dev_feat[choose_id]
photo = photo.split()
<span class="hljs-keyword">for</span> p <span class="hljs-keyword">in</span> photo:
p = int(p)
photo = np.array(photo)
<span class="hljs-keyword">for</span> cnt, fn <span class="hljs-keyword">in</span> enumerate(collect_layers):
im = fn([photo.reshape(<span class="hljs-number">1</span>,<span class="hljs-number">48</span>,<span class="hljs-number">48</span>,<span class="hljs-number">1</span>),<span class="hljs-number">0</span>])
fig = plt.figure(figsize=(<span class="hljs-number">14</span>,<span class="hljs-number">8</span>))
nb_filter = im[<span class="hljs-number">0</span>].shape[<span class="hljs-number">3</span>]
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(nb_filter):
ax = fig.add_subplot(nb_filter/<span class="hljs-number">16</span>,<span class="hljs-number">16</span>,i+<span class="hljs-number">1</span>)
ax.imshow(im[<span class="hljs-number">0</span>][<span class="hljs-number">0</span>,:,:,i],cmap=<span class="hljs-string">'Purples'</span>)
plt.xticks(np.array([]))
plt.yticks(np.array([]))
plt.tight_layout()
fig.suptitle(<span class="hljs-string">'Output of layer{} (Given image{})'</span>.format(cnt,choose_id))
img_path = os.path.join(vis_dir,store_path)
<span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> os.path.isdir(img_path):
os.mkdir(img_path)
fig.savefig(os.path.join(img_path,<span class="hljs-string">'layer{}'</span>.format(cnt)))
<span class="hljs-keyword">else</span>:
name_ls = [<span class="hljs-string">'zero_padding2d_4'</span>]
collect_layers = list()
collect_layers.append(layer_dict[name_ls[<span class="hljs-number">0</span>]].output)
<span class="hljs-keyword">for</span> cnt, c <span class="hljs-keyword">in</span> enumerate(collect_layers):
filter_imgs = [[] <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(NUM_STEPS//RECORD_FREQ)]
nb_filter = c.shape[<span class="hljs-number">-1</span>]
<span class="hljs-keyword">for</span> filter_idx <span class="hljs-keyword">in</span> range(nb_filter):
input_img_data = np.random.random((<span class="hljs-number">1</span>, <span class="hljs-number">48</span>, <span class="hljs-number">48</span>, <span class="hljs-number">1</span>))
loss = K.mean(c[:,:,:,filter_idx])
grads = normalize(K.gradients(loss,input_img)[<span class="hljs-number">0</span>])
iterate = K.function([input_img],[loss,grads])
<span class="hljs-string">"""
"You need to implement it."
filter_imgs = grad_ascent(num_step, input_img_data, iterate)
"""</span>
<span class="hljs-keyword">for</span> it <span class="hljs-keyword">in</span> range(NUM_STEPS//RECORD_FREQ):
fig = plt.figure(figsize=(<span class="hljs-number">14</span>,<span class="hljs-number">8</span>))
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(nb_filter):
ax = fig.add_subplot(int(nb_filter)/<span class="hljs-number">16</span>,<span class="hljs-number">16</span>,i+<span class="hljs-number">1</span>)
ax.imshow(filter_imgs[it][i][<span class="hljs-number">0</span>],cmap=<span class="hljs-string">'Purples'</span>)
plt.xticks(np.array([]))
plt.yticks(np.array([]))
plt.xlabel(<span class="hljs-string">'{:.3f}'</span>.format(filter_imgs[it][i][<span class="hljs-number">1</span>]))
plt.tight_layout()
fig.suptitle(<span class="hljs-string">'Filters of layer {} (# Ascent Epoch {} )'</span>.format(name_ls[<span class="hljs-number">0</span>],it*RECORD_FREQ))
img_path = os.path.join(filter_dir,<span class="hljs-string">'{}-{}'</span>.format(store_path,name_ls[<span class="hljs-number">0</span>]))
<span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> os.path.isdir(img_path):
os.mkdir(img_path)
fig.savefig(os.path.join(img_path,<span class="hljs-string">'e{}'</span>.format(it*RECORD_FREQ)))
<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
main()
</code></pre></div>
## Reference
→ [Visualize your convolution neural network](https://blog.keras.io/how-convolutional-neural-networks-see-the-world.html)
</xmp>
</xmp> <script src="strapdown.js"></script> </html>
<footer>
<center><a href="./index.html"><i class="fa fa-home"></i></a></center>
<center><i class="fa fa-github"></i></a> Posted by: <a href="https://github.com/ntumlta/" target="_blank">ntumlta</a> </center>
<center><i class="fa fa-envelope"></i> Contact information: <a href="mailto:"> [email protected] </a>.</center>
<center><i class="fa fa-mortar-board"></i> Course information: <a href="http://speech.ee.ntu.edu.tw/~tlkagk/courses_ML17_2.html", target="_blank">Machine Learning (2017, Fall) @ National Taiwan University</a>.</center>
</footer>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-59748795-2', 'auto');
ga('send', 'pageview');
</script>
</html>