-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathregularization-for-multi-layer-neural-networks-in-tensorflow.html
1201 lines (1001 loc) · 73.1 KB
/
regularization-for-multi-layer-neural-networks-in-tensorflow.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
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<!--[if lt IE 9 ]><html class="no-js oldie" lang="zh-hant-tw"> <![endif]-->
<!--[if IE 9 ]><html class="no-js oldie ie9" lang="zh-hant-tw"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!-->
<html class="no-js" lang="zh-hant-tw">
<!--<![endif]-->
<head>
<!--- basic page needs
================================================== -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="author" content="Lee Meng" />
<title>LeeMeng - Regularization for Multi-layer Neural Networks in Tensorflow</title>
<!--- article-specific meta data
================================================== -->
<meta name="description" content="The goal of this assignment is to explore regularization techniques." />
<meta name="keywords" content="Tensorflow, Python, Deep Learning, Regularization, Deep Learning by Google, Machine Learning Engineer by kaggle, Udacity" />
<meta name="tags" content="Tensorflow" />
<meta name="tags" content="Python" />
<meta name="tags" content="Deep Learning" />
<meta name="tags" content="Regularization" />
<meta name="tags" content="Deep Learning by Google" />
<meta name="tags" content="Machine Learning Engineer by kaggle" />
<meta name="tags" content="Udacity" />
<!--- Open Graph Object metas
================================================== -->
<meta property="og:image" content="https://leemeng.tw/theme/images/background/default.jpg" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://leemeng.tw/regularization-for-multi-layer-neural-networks-in-tensorflow.html" />
<meta property="og:title" content="Regularization for Multi-layer Neural Networks in Tensorflow" />
<meta property="og:description" content="The goal of this assignment is to explore regularization techniques." />
<!-- mobile specific metas
================================================== -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSS
================================================== -->
<!--for customized css in individual page-->
<link rel="stylesheet" type="text/css" href="https://leemeng.tw/theme/css/bootstrap.min.css">
<!--for showing toc navigation which slide in from left-->
<link rel="stylesheet" type="text/css" href="https://leemeng.tw/theme/css/toc-nav.css">
<!--for responsive embed youtube video-->
<link rel="stylesheet" type="text/css" href="https://leemeng.tw/theme/css/embed_youtube.css">
<!--for prettify dark-mode result-->
<link rel="stylesheet" type="text/css" href="https://leemeng.tw/theme/css/darkmode.css">
<link rel="stylesheet" type="text/css" href="https://leemeng.tw/theme/css/base.css">
<link rel="stylesheet" type="text/css" href="https://leemeng.tw/theme/css/vendor.css">
<link rel="stylesheet" type="text/css" href="https://leemeng.tw/theme/css/main.css">
<link rel="stylesheet" type="text/css" href="https://leemeng.tw/theme/css/ipython.css">
<link rel="stylesheet" type="text/css" href='https://leemeng.tw/theme/css/progress-bar.css' />
<!--TiqueSearch-->
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400">
<link rel="stylesheet" href="https://leemeng.tw/theme/tipuesearch/css/normalize.css">
<link rel="stylesheet" href="https://leemeng.tw/theme/tipuesearch/css/tipuesearch.css">
<!-- script
================================================== -->
<script src="https://leemeng.tw/theme/js/modernizr.js"></script>
<script src="https://leemeng.tw/theme/js/pace.min.js"></script>
<!-- favicons
================================================== -->
<link rel="shortcut icon" href="../theme/images/favicon.ico" type="image/x-icon"/>
<link rel="icon" href="../theme/images/favicon.ico" type="image/x-icon"/>
<!-- Global Site Tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-106559980-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments)};
gtag('js', new Date());
gtag('config', 'UA-106559980-1');
</script>
</head>
<body id="top">
<!-- header
================================================== -->
<header class="s-header">
<div class="header-logo">
<a class="site-logo" href="../index.html"><img src="https://leemeng.tw/theme/images/logo.png" alt="Homepage"></a>
</div>
<!--navigation bar ref: http://jinja.pocoo.org/docs/2.10/tricks/-->
<nav class="header-nav-wrap">
<ul class="header-nav">
<li>
<a href="../index.html#home">Home</a>
</li>
<li>
<a href="../index.html#about">About</a>
</li>
<li>
<a href="../index.html#projects">Projects</a>
</li>
<li class="current">
<a href="../blog.html">Blog</a>
</li>
<li>
<a href="https://demo.leemeng.tw">Demo</a>
</li>
<li>
<a href="../books.html">Books</a>
</li>
<li>
<a href="../index.html#contact">Contact</a>
</li>
</ul>
<!--<div class="search-container">-->
<!--<form action="../search.html">-->
<!--<input type="text" placeholder="Search.." name="search">-->
<!--<button type="submit"><i class="im im-magnifier" aria-hidden="true"></i></button>-->
<!--</form>-->
<!--</div>-->
</nav>
<a class="header-menu-toggle" href="#0"><span>Menu</span></a>
</header> <!-- end s-header -->
<!--TOC navigation displayed when clicked from left-navigation button-->
<div id="tocNav" class="overlay" onclick="closeTocNav()">
<div class="overlay-content">
<div id="toc"><ul><li><a class="toc-href" href="#" title="Regularization for Multi-layer Neural Networks in Tensorflow">Regularization for Multi-layer Neural Networks in Tensorflow</a><ul><li><a class="toc-href" href="#Import-libraries" title="Import libraries">Import libraries</a></li><li><a class="toc-href" href="#Load-NotMNIST-dataset" title="Load NotMNIST dataset">Load NotMNIST dataset</a></li><li><a class="toc-href" href="#Reformat-dataset" title="Reformat dataset">Reformat dataset</a><ul><li><a class="toc-href" href="#Using-Accuracy-as-Default-Metric" title="Using Accuracy as Default Metric">Using Accuracy as Default Metric</a></li></ul></li><li><a class="toc-href" href="#3-layer-NN-as-base-model_1" title="3-layer NN as base model">3-layer NN as base model</a><ul><li><a class="toc-href" href="#Hyper-parameters" title="Hyper parameters">Hyper parameters</a></li><li><a class="toc-href" href="#Build-model" title="Build model">Build model</a></li><li><a class="toc-href" href="#Train-model-without-regularization" title="Train model without regularization">Train model without regularization</a></li></ul></li><li><a class="toc-href" href="#L2-regularization_1" title="L2 regularization">L2 regularization</a></li><li><a class="toc-href" href="#Case-of-overfitting" title="Case of overfitting">Case of overfitting</a></li><li><a class="toc-href" href="#Dropout" title="Dropout">Dropout</a></li><li><a class="toc-href" href="#Boost-performance-by-using-Multi-layer-NN" title="Boost performance by using Multi-layer NN">Boost performance by using Multi-layer NN</a></li></ul></li></ul></div>
</div>
</div>
<!--custom images with icon shown on left nav-->
<!--the details are set in `pelicanconf.py` as `LEFT_NAV_IMAGES`-->
<article class="blog-single">
<!-- page header/blog hero, use custom cover image if available
================================================== -->
<div class="page-header page-header--single page-hero" style="background-image:url(https://leemeng.tw/theme/images/background/default.jpg)">
<div class="row page-header__content narrow">
<article class="col-full">
<div class="page-header__info">
<div class="page-header__cat">
<a href="https://leemeng.tw/tag/tensorflow.html" rel="tag">Tensorflow</a>
<a href="https://leemeng.tw/tag/python.html" rel="tag">Python</a>
<a href="https://leemeng.tw/tag/deep-learning.html" rel="tag">Deep Learning</a>
<a href="https://leemeng.tw/tag/regularization.html" rel="tag">Regularization</a>
<a href="https://leemeng.tw/tag/deep-learning-by-google.html" rel="tag">Deep Learning by Google</a>
</div>
</div>
<h1 class="page-header__title">
<a href="https://leemeng.tw/regularization-for-multi-layer-neural-networks-in-tensorflow.html" title="">
Regularization for Multi-layer Neural Networks in Tensorflow
</a>
</h1>
<ul class="page-header__meta">
<li class="date">2017-09-25 (Mon)</li>
<li class="page-view">
844 views
</li>
</ul>
</article>
</div>
</div> <!-- end page-header -->
<div class="KW_progressContainer">
<div class="KW_progressBar"></div>
</div>
<div class="row blog-content" style="position: relative">
<div id="left-navigation">
<div id="search-wrap">
<i class="im im-magnifier" aria-hidden="true"></i>
<div id="search">
<form action="../search.html">
<div class="tipue_search_right"><input type="text" name="q" id="tipue_search_input" pattern=".{2,}" title="想搜尋什麼呢?(請至少輸入兩個字)" required></div>
</form>
</div>
</div>
<div id="toc-wrap">
<a title="顯示/隱藏 文章章節">
<i class="im im-menu" aria-hidden="true" onclick="toggleTocNav()"></i>
</a>
</div>
<div id="social-wrap" style="cursor: pointer">
<a class="open-popup" title="訂閱最新文章">
<i class="im im-newspaper-o" aria-hidden="true"></i>
</a>
</div>
<div id="social-wrap">
<a href="https://www.facebook.com/sharer/sharer.php?u=https%3A//leemeng.tw/regularization-for-multi-layer-neural-networks-in-tensorflow.html" target="_blank" title="分享到 Facebook">
<i class="im im-facebook" aria-hidden="true"></i>
</a>
</div>
<div id="social-wrap">
<a href="https://www.linkedin.com/shareArticle?mini=true&url=https%3A//leemeng.tw/regularization-for-multi-layer-neural-networks-in-tensorflow.html&title=Regularization%20for%20Multi-layer%20Neural%20Networks%20in%20Tensorflow&summary=The%20goal%20of%20this%20assignment%20is%20to%20explore%20regularization%20techniques.&source=https%3A//leemeng.tw/regularization-for-multi-layer-neural-networks-in-tensorflow.html" target="_blank" title="分享到 LinkedIn">
<i class="im im-linkedin" aria-hidden="true"></i>
</a>
</div>
<div id="social-wrap">
<a href="https://twitter.com/intent/tweet?text=Regularization%20for%20Multi-layer%20Neural%20Networks%20in%20Tensorflow&url=https%3A//leemeng.tw/regularization-for-multi-layer-neural-networks-in-tensorflow.html&hashtags=tensorflow,python,deep-learning,regularization,deep-learning-by-google,machine-learning-engineer-by-kaggle,udacity" target="_blank" title="分享到 Twitter">
<i class="im im-twitter" aria-hidden="true"></i>
</a>
</div>
<!--custom images with icon shown on left nav-->
</div>
<div class="col-full blog-content__main">
<div class="cell border-box-sizing text_cell rendered"><div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>The goal of this assignment is to explore regularization techniques.
The original notebook can be found <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/3_regularization.ipynb">here</a></p>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered"><div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="Import-libraries">Import libraries<a class="anchor-link" href="#Import-libraries">¶</a></h2>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight hl-ipython3"><pre><span></span><span class="c1"># These are all the modules we'll be using later. Make sure you can import them</span>
<span class="c1"># before proceeding further.</span>
<span class="kn">from</span> <span class="nn">__future__</span> <span class="kn">import</span> <span class="n">print_function</span>
<span class="kn">from</span> <span class="nn">tqdm</span> <span class="kn">import</span> <span class="n">tnrange</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">tensorflow</span> <span class="k">as</span> <span class="nn">tf</span>
<span class="kn">from</span> <span class="nn">six.moves</span> <span class="kn">import</span> <span class="n">cPickle</span> <span class="k">as</span> <span class="n">pickle</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered"><div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="Load-NotMNIST-dataset">Load NotMNIST dataset<a class="anchor-link" href="#Load-NotMNIST-dataset">¶</a></h2>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered"><div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>First reload the data we generated in <code>1_notmnist.ipynb</code>.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight hl-ipython3"><pre><span></span><span class="n">pickle_file</span> <span class="o">=</span> <span class="s1">'datasets/notMNIST.pickle'</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">pickle_file</span><span class="p">,</span> <span class="s1">'rb'</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
<span class="n">save</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
<span class="n">X_train</span> <span class="o">=</span> <span class="n">save</span><span class="p">[</span><span class="s1">'train_dataset'</span><span class="p">]</span>
<span class="n">Y_train</span> <span class="o">=</span> <span class="n">save</span><span class="p">[</span><span class="s1">'train_labels'</span><span class="p">]</span>
<span class="n">X_valid</span> <span class="o">=</span> <span class="n">save</span><span class="p">[</span><span class="s1">'valid_dataset'</span><span class="p">]</span>
<span class="n">Y_valid</span> <span class="o">=</span> <span class="n">save</span><span class="p">[</span><span class="s1">'valid_labels'</span><span class="p">]</span>
<span class="n">X_test</span> <span class="o">=</span> <span class="n">save</span><span class="p">[</span><span class="s1">'test_dataset'</span><span class="p">]</span>
<span class="n">Y_test</span> <span class="o">=</span> <span class="n">save</span><span class="p">[</span><span class="s1">'test_labels'</span><span class="p">]</span>
<span class="k">del</span> <span class="n">save</span> <span class="c1"># hint to help gc free up memory</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Training set'</span><span class="p">,</span> <span class="n">X_train</span><span class="o">.</span><span class="n">shape</span><span class="p">,</span> <span class="n">Y_train</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Validation set'</span><span class="p">,</span> <span class="n">X_valid</span><span class="o">.</span><span class="n">shape</span><span class="p">,</span> <span class="n">Y_valid</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Test set'</span><span class="p">,</span> <span class="n">X_test</span><span class="o">.</span><span class="n">shape</span><span class="p">,</span> <span class="n">Y_test</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
<pre>Training set (200000, 28, 28) (200000,)
Validation set (10000, 28, 28) (10000,)
Test set (10000, 28, 28) (10000,)
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered"><div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="Reformat-dataset">Reformat dataset<a class="anchor-link" href="#Reformat-dataset">¶</a></h2>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered"><div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>Reformat into a shape that's more adapted to the models we're going to train:</p>
<ul>
<li>data as a flat matrix,</li>
<li>labels as float 1-hot encodings.</li>
</ul>
<p>As I did in previous notebook, this reformat operation will be different from the operation suggested by the original <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/3_regularization.ipynb">notebook</a>.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight hl-ipython3"><pre><span></span><span class="n">image_size</span> <span class="o">=</span> <span class="mi">28</span>
<span class="n">num_labels</span> <span class="o">=</span> <span class="mi">10</span>
<span class="k">def</span> <span class="nf">reformat</span><span class="p">(</span><span class="n">dataset</span><span class="p">,</span> <span class="n">labels</span><span class="p">):</span>
<span class="n">dataset</span> <span class="o">=</span> <span class="n">dataset</span><span class="o">.</span><span class="n">reshape</span><span class="p">((</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="n">image_size</span> <span class="o">*</span> <span class="n">image_size</span><span class="p">))</span><span class="o">.</span><span class="n">astype</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">float32</span><span class="p">)</span><span class="o">.</span><span class="n">T</span>
<span class="c1"># Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...]</span>
<span class="n">labels</span> <span class="o">=</span> <span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="n">num_labels</span><span class="p">)</span> <span class="o">==</span> <span class="n">labels</span><span class="p">[:,</span> <span class="kc">None</span><span class="p">])</span><span class="o">.</span><span class="n">astype</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">float32</span><span class="p">)</span><span class="o">.</span><span class="n">T</span>
<span class="k">return</span> <span class="n">dataset</span><span class="p">,</span> <span class="n">labels</span>
<span class="n">X_train</span><span class="p">,</span> <span class="n">Y_train</span> <span class="o">=</span> <span class="n">reformat</span><span class="p">(</span><span class="n">X_train</span><span class="p">,</span> <span class="n">Y_train</span><span class="p">)</span>
<span class="n">X_valid</span><span class="p">,</span> <span class="n">Y_valid</span> <span class="o">=</span> <span class="n">reformat</span><span class="p">(</span><span class="n">X_valid</span><span class="p">,</span> <span class="n">Y_valid</span><span class="p">)</span>
<span class="n">X_test</span><span class="p">,</span> <span class="n">Y_test</span> <span class="o">=</span> <span class="n">reformat</span><span class="p">(</span><span class="n">X_test</span><span class="p">,</span> <span class="n">Y_test</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Training set'</span><span class="p">,</span> <span class="n">X_train</span><span class="o">.</span><span class="n">shape</span><span class="p">,</span> <span class="n">Y_train</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Validation set'</span><span class="p">,</span> <span class="n">X_valid</span><span class="o">.</span><span class="n">shape</span><span class="p">,</span> <span class="n">Y_valid</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Test set'</span><span class="p">,</span> <span class="n">X_test</span><span class="o">.</span><span class="n">shape</span><span class="p">,</span> <span class="n">X_test</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
<pre>Training set (784, 200000) (10, 200000)
Validation set (784, 10000) (10, 10000)
Test set (784, 10000) (784, 10000)
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered"><div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="Using-Accuracy-as-Default-Metric">Using Accuracy as Default Metric<a class="anchor-link" href="#Using-Accuracy-as-Default-Metric">¶</a></h3><p>Because as we explored before, there exist no unbalanced problem in the dataset,<br/>
so accuracy alone will be sufficient for evaluating performance of our model on the classification task.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight hl-ipython3"><pre><span></span><span class="k">def</span> <span class="nf">accuracy</span><span class="p">(</span><span class="n">predictions</span><span class="p">,</span> <span class="n">labels</span><span class="p">):</span>
<span class="k">return</span> <span class="p">(</span>
<span class="n">np</span><span class="o">.</span><span class="n">sum</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">argmax</span><span class="p">(</span><span class="n">predictions</span><span class="p">,</span> <span class="n">axis</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="o">==</span> <span class="n">np</span><span class="o">.</span><span class="n">argmax</span><span class="p">(</span>
<span class="n">labels</span><span class="p">,</span> <span class="n">axis</span><span class="o">=</span><span class="mi">0</span><span class="p">))</span> <span class="o">/</span> <span class="n">labels</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">*</span> <span class="mi">100</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered"><div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="3-layer-NN-as-base-model_1">3-layer NN as base model<a class="anchor-link" href="#3-layer-NN-as-base-model">¶</a></h2><p>In order to test the effect with/without regularization, we will use a little more complex neural network with 2 hidden layers as our base model. And we will be using ReLU as our activation function.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered"><div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="Hyper-parameters">Hyper parameters<a class="anchor-link" href="#Hyper-parameters">¶</a></h3>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight hl-ipython3"><pre><span></span><span class="c1"># hyper parameters</span>
<span class="n">learning_rate</span> <span class="o">=</span> <span class="mf">1e-2</span>
<span class="n">lamba</span> <span class="o">=</span> <span class="mf">1e-3</span>
<span class="n">keep_prob</span> <span class="o">=</span> <span class="mf">0.5</span>
<span class="n">batch_size</span> <span class="o">=</span> <span class="mi">128</span>
<span class="n">num_steps</span> <span class="o">=</span> <span class="mi">501</span>
<span class="n">n0</span> <span class="o">=</span> <span class="n">image_size</span> <span class="o">*</span> <span class="n">image_size</span> <span class="c1"># input size</span>
<span class="n">n1</span> <span class="o">=</span> <span class="mi">1024</span> <span class="c1"># first hidden layer</span>
<span class="n">n2</span> <span class="o">=</span> <span class="mi">512</span> <span class="c1"># second hidden layer</span>
<span class="n">n3</span> <span class="o">=</span> <span class="mi">256</span> <span class="c1"># third hidden layer</span>
<span class="n">n4</span> <span class="o">=</span> <span class="n">num_labels</span> <span class="c1"># output size</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered"><div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="Build-model">Build model<a class="anchor-link" href="#Build-model">¶</a></h3>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight hl-ipython3"><pre><span></span><span class="c1"># build a model which let us able to choose different optimzation mechnism</span>
<span class="k">def</span> <span class="nf">model</span><span class="p">(</span><span class="n">lamba</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">learning_rate</span><span class="o">=</span><span class="n">learning_rate</span><span class="p">,</span>
<span class="n">keep_prob</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">learning_decay</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
<span class="n">batch_size</span><span class="o">=</span><span class="n">batch_size</span><span class="p">,</span> <span class="n">num_steps</span><span class="o">=</span><span class="n">num_steps</span><span class="p">,</span> <span class="n">n1</span><span class="o">=</span><span class="n">n1</span><span class="p">,</span> <span class="n">n2</span><span class="o">=</span><span class="n">n2</span><span class="p">,</span> <span class="n">n3</span><span class="o">=</span><span class="n">n3</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span>
<span class="w"> </span><span class="sd">"""</span>
<span class="sd"> Train 3-layer NN with following settings:</span>
<span class="sd"> Regularization lambda: {}</span>
<span class="sd"> Learning rate: {}</span>
<span class="sd"> learning_decay: {}</span>
<span class="sd"> keep_prob: {}</span>
<span class="sd"> Batch_size: {}</span>
<span class="sd"> Number of steps: {}</span>
<span class="sd"> n1, n2, n3: {}, {}, {}"""</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">lamba</span><span class="p">,</span> <span class="n">learning_rate</span><span class="p">,</span>
<span class="n">learning_decay</span><span class="p">,</span> <span class="n">keep_prob</span><span class="p">,</span>
<span class="n">batch_size</span><span class="p">,</span> <span class="n">num_steps</span><span class="p">,</span> <span class="n">n1</span><span class="p">,</span> <span class="n">n2</span><span class="p">,</span> <span class="n">n3</span><span class="p">))</span>
<span class="c1"># construct computation graph</span>
<span class="n">graph</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">Graph</span><span class="p">()</span>
<span class="k">with</span> <span class="n">graph</span><span class="o">.</span><span class="n">as_default</span><span class="p">():</span>
<span class="c1"># placeholder for mini-batch when training </span>
<span class="n">X</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">placeholder</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">float32</span><span class="p">,</span> <span class="n">shape</span><span class="o">=</span><span class="p">(</span><span class="n">n0</span><span class="p">,</span> <span class="n">batch_size</span><span class="p">))</span>
<span class="n">Y</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">placeholder</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">float32</span><span class="p">,</span> <span class="n">shape</span><span class="o">=</span><span class="p">(</span><span class="n">num_labels</span><span class="p">,</span> <span class="n">batch_size</span><span class="p">))</span>
<span class="n">global_step</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">Variable</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="c1"># use all valid/test set</span>
<span class="n">tf_X_valid</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">constant</span><span class="p">(</span><span class="n">X_valid</span><span class="p">)</span>
<span class="n">tf_X_test</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">constant</span><span class="p">(</span><span class="n">X_test</span><span class="p">)</span>
<span class="c1"># initialize weights, biases</span>
<span class="c1"># notice that we have two hidden </span>
<span class="c1"># layers so we now have W1, b1, W2, b2, W3, b3</span>
<span class="n">W1</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">Variable</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">truncated_normal</span><span class="p">([</span><span class="n">n1</span><span class="p">,</span> <span class="n">n0</span><span class="p">],</span> <span class="n">stddev</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="mf">2.0</span> <span class="o">/</span> <span class="n">n0</span><span class="p">)))</span>
<span class="n">W2</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">Variable</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">truncated_normal</span><span class="p">([</span><span class="n">n2</span><span class="p">,</span> <span class="n">n1</span><span class="p">],</span> <span class="n">stddev</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="mf">2.0</span> <span class="o">/</span> <span class="n">n1</span><span class="p">)))</span>
<span class="n">W3</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">Variable</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">truncated_normal</span><span class="p">([</span><span class="n">n3</span><span class="p">,</span> <span class="n">n2</span><span class="p">],</span> <span class="n">stddev</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="mf">2.0</span> <span class="o">/</span> <span class="n">n2</span><span class="p">)))</span>
<span class="n">W4</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">Variable</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">truncated_normal</span><span class="p">([</span><span class="n">n4</span><span class="p">,</span> <span class="n">n3</span><span class="p">],</span> <span class="n">stddev</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="mf">2.0</span> <span class="o">/</span> <span class="n">n3</span><span class="p">)))</span>
<span class="n">b1</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">Variable</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">zeros</span><span class="p">([</span><span class="n">n1</span><span class="p">,</span> <span class="mi">1</span><span class="p">]))</span>
<span class="n">b2</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">Variable</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">zeros</span><span class="p">([</span><span class="n">n2</span><span class="p">,</span> <span class="mi">1</span><span class="p">]))</span>
<span class="n">b3</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">Variable</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">zeros</span><span class="p">([</span><span class="n">n3</span><span class="p">,</span> <span class="mi">1</span><span class="p">]))</span>
<span class="n">b4</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">Variable</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">zeros</span><span class="p">([</span><span class="n">n4</span><span class="p">,</span> <span class="mi">1</span><span class="p">]))</span>
<span class="c1"># training computation</span>
<span class="n">Z1</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">matmul</span><span class="p">(</span><span class="n">W1</span><span class="p">,</span> <span class="n">X</span><span class="p">)</span> <span class="o">+</span> <span class="n">b1</span>
<span class="n">A1</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">relu</span><span class="p">(</span><span class="n">Z1</span><span class="p">)</span> <span class="k">if</span> <span class="n">keep_prob</span> <span class="o">==</span> <span class="mi">1</span> <span class="k">else</span> <span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">dropout</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">relu</span><span class="p">(</span><span class="n">Z1</span><span class="p">),</span> <span class="n">keep_prob</span><span class="p">)</span>
<span class="n">Z2</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">matmul</span><span class="p">(</span><span class="n">W2</span><span class="p">,</span> <span class="n">A1</span><span class="p">)</span> <span class="o">+</span> <span class="n">b2</span>
<span class="n">A2</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">relu</span><span class="p">(</span><span class="n">Z2</span><span class="p">)</span> <span class="k">if</span> <span class="n">keep_prob</span> <span class="o">==</span> <span class="mi">1</span> <span class="k">else</span> <span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">dropout</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">relu</span><span class="p">(</span><span class="n">Z2</span><span class="p">),</span> <span class="n">keep_prob</span><span class="p">)</span>
<span class="n">Z3</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">matmul</span><span class="p">(</span><span class="n">W3</span><span class="p">,</span> <span class="n">A2</span><span class="p">)</span> <span class="o">+</span> <span class="n">b3</span>
<span class="n">A3</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">relu</span><span class="p">(</span><span class="n">Z3</span><span class="p">)</span> <span class="k">if</span> <span class="n">keep_prob</span> <span class="o">==</span> <span class="mi">1</span> <span class="k">else</span> <span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">dropout</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">relu</span><span class="p">(</span><span class="n">Z3</span><span class="p">),</span> <span class="n">keep_prob</span><span class="p">)</span>
<span class="n">Z4</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">matmul</span><span class="p">(</span><span class="n">W4</span><span class="p">,</span> <span class="n">A3</span><span class="p">)</span> <span class="o">+</span> <span class="n">b4</span>
<span class="n">loss</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">reduce_mean</span><span class="p">(</span>
<span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">softmax_cross_entropy_with_logits</span><span class="p">(</span>
<span class="n">labels</span><span class="o">=</span><span class="n">tf</span><span class="o">.</span><span class="n">transpose</span><span class="p">(</span><span class="n">Y</span><span class="p">),</span> <span class="n">logits</span><span class="o">=</span><span class="n">tf</span><span class="o">.</span><span class="n">transpose</span><span class="p">(</span><span class="n">Z4</span><span class="p">)))</span>
<span class="k">if</span> <span class="n">lamba</span><span class="p">:</span>
<span class="n">loss</span> <span class="o">+=</span> <span class="n">lamba</span> <span class="o">*</span> \
<span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">l2_loss</span><span class="p">(</span><span class="n">W1</span><span class="p">)</span> <span class="o">+</span> <span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">l2_loss</span><span class="p">(</span><span class="n">W2</span><span class="p">)</span> <span class="o">+</span> <span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">l2_loss</span><span class="p">(</span><span class="n">W3</span><span class="p">)</span> <span class="o">+</span> <span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">l2_loss</span><span class="p">(</span><span class="n">W4</span><span class="p">))</span>
<span class="c1"># optimizer</span>
<span class="k">if</span> <span class="n">learning_decay</span><span class="p">:</span>
<span class="n">learning_rate</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">train</span><span class="o">.</span><span class="n">exponential_decay</span><span class="p">(</span><span class="mf">0.5</span><span class="p">,</span> <span class="n">global_step</span><span class="p">,</span> <span class="mi">5000</span><span class="p">,</span> <span class="mf">0.80</span><span class="p">,</span> <span class="n">staircase</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="n">optimizer</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">train</span><span class="o">.</span><span class="n">GradientDescentOptimizer</span><span class="p">(</span><span class="n">learning_rate</span><span class="p">)</span><span class="o">.</span><span class="n">minimize</span><span class="p">(</span><span class="n">loss</span><span class="p">,</span> <span class="n">global_step</span><span class="o">=</span><span class="n">global_step</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">optimizer</span> <span class="o">=</span> <span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">train</span>
<span class="o">.</span><span class="n">GradientDescentOptimizer</span><span class="p">(</span><span class="n">learning_rate</span><span class="p">)</span><span class="o">.</span><span class="n">minimize</span><span class="p">(</span><span class="n">loss</span><span class="p">))</span>
<span class="c1"># valid / test prediction</span>
<span class="n">Y_pred</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">softmax</span><span class="p">(</span><span class="n">Z4</span><span class="p">,</span> <span class="n">dim</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="n">Y_vaild_pred</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">softmax</span><span class="p">(</span>
<span class="n">tf</span><span class="o">.</span><span class="n">matmul</span><span class="p">(</span><span class="n">W4</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">relu</span><span class="p">(</span>
<span class="n">tf</span><span class="o">.</span><span class="n">matmul</span><span class="p">(</span><span class="n">W3</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">relu</span><span class="p">(</span>
<span class="n">tf</span><span class="o">.</span><span class="n">matmul</span><span class="p">(</span><span class="n">W2</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">relu</span><span class="p">(</span>
<span class="n">tf</span><span class="o">.</span><span class="n">matmul</span><span class="p">(</span><span class="n">W1</span><span class="p">,</span> <span class="n">tf_X_valid</span><span class="p">)</span> <span class="o">+</span> <span class="n">b1</span><span class="p">))</span> <span class="o">+</span> <span class="n">b2</span><span class="p">))</span> <span class="o">+</span> <span class="n">b3</span><span class="p">))</span> <span class="o">+</span> <span class="n">b4</span><span class="p">,</span> <span class="n">dim</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="n">Y_test_pred</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">softmax</span><span class="p">(</span>
<span class="n">tf</span><span class="o">.</span><span class="n">matmul</span><span class="p">(</span><span class="n">W4</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">relu</span><span class="p">(</span>
<span class="n">tf</span><span class="o">.</span><span class="n">matmul</span><span class="p">(</span><span class="n">W3</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">relu</span><span class="p">(</span>
<span class="n">tf</span><span class="o">.</span><span class="n">matmul</span><span class="p">(</span><span class="n">W2</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">relu</span><span class="p">(</span>
<span class="n">tf</span><span class="o">.</span><span class="n">matmul</span><span class="p">(</span><span class="n">W1</span><span class="p">,</span> <span class="n">tf_X_test</span><span class="p">)</span> <span class="o">+</span> <span class="n">b1</span><span class="p">))</span> <span class="o">+</span> <span class="n">b2</span><span class="p">))</span> <span class="o">+</span> <span class="n">b3</span><span class="p">))</span> <span class="o">+</span> <span class="n">b4</span><span class="p">,</span> <span class="n">dim</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="c1"># define training</span>
<span class="k">with</span> <span class="n">tf</span><span class="o">.</span><span class="n">Session</span><span class="p">(</span><span class="n">graph</span><span class="o">=</span><span class="n">graph</span><span class="p">)</span> <span class="k">as</span> <span class="n">sess</span><span class="p">:</span>
<span class="c1"># initialized parameters</span>
<span class="n">tf</span><span class="o">.</span><span class="n">global_variables_initializer</span><span class="p">()</span><span class="o">.</span><span class="n">run</span><span class="p">()</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Initialized"</span><span class="p">)</span>
<span class="k">for</span> <span class="n">step</span> <span class="ow">in</span> <span class="n">tnrange</span><span class="p">(</span><span class="n">num_steps</span><span class="p">):</span>
<span class="c1"># generate randomized mini-batches from training data</span>
<span class="n">offset</span> <span class="o">=</span> <span class="p">(</span><span class="n">step</span> <span class="o">*</span> <span class="n">batch_size</span><span class="p">)</span> <span class="o">%</span> <span class="p">(</span><span class="n">Y_train</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">-</span> <span class="n">batch_size</span><span class="p">)</span>
<span class="n">batch_X</span> <span class="o">=</span> <span class="n">X_train</span><span class="p">[:,</span> <span class="n">offset</span><span class="p">:(</span><span class="n">offset</span> <span class="o">+</span> <span class="n">batch_size</span><span class="p">)]</span>
<span class="n">batch_Y</span> <span class="o">=</span> <span class="n">Y_train</span><span class="p">[:,</span> <span class="n">offset</span><span class="p">:(</span><span class="n">offset</span> <span class="o">+</span> <span class="n">batch_size</span><span class="p">)]</span>
<span class="c1"># train model</span>
<span class="n">_</span><span class="p">,</span> <span class="n">l</span><span class="p">,</span> <span class="n">batch_Y_pred</span> <span class="o">=</span> <span class="n">sess</span><span class="o">.</span><span class="n">run</span><span class="p">(</span>
<span class="p">[</span><span class="n">optimizer</span><span class="p">,</span> <span class="n">loss</span><span class="p">,</span> <span class="n">Y_pred</span><span class="p">],</span> <span class="n">feed_dict</span><span class="o">=</span><span class="p">{</span><span class="n">X</span><span class="p">:</span> <span class="n">batch_X</span><span class="p">,</span> <span class="n">Y</span><span class="p">:</span> <span class="n">batch_Y</span><span class="p">})</span>
<span class="k">if</span> <span class="p">(</span><span class="n">step</span> <span class="o">%</span> <span class="mi">200</span> <span class="o">==</span> <span class="mi">0</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Minibatch loss at step </span><span class="si">{}</span><span class="s1">: </span><span class="si">{:.3f}</span><span class="s1">. batch acc: </span><span class="si">{:.1f}</span><span class="s1">%, Valid acc: </span><span class="si">{:.1f}</span><span class="s1">%.'</span>\
<span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">step</span><span class="p">,</span> <span class="n">l</span><span class="p">,</span>
<span class="n">accuracy</span><span class="p">(</span><span class="n">batch_Y_pred</span><span class="p">,</span> <span class="n">batch_Y</span><span class="p">),</span>
<span class="n">accuracy</span><span class="p">(</span><span class="n">Y_vaild_pred</span><span class="o">.</span><span class="n">eval</span><span class="p">(),</span> <span class="n">Y_valid</span><span class="p">)))</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Test acc: </span><span class="si">{:.1f}</span><span class="s1">%'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">accuracy</span><span class="p">(</span><span class="n">Y_test_pred</span><span class="o">.</span><span class="n">eval</span><span class="p">(),</span> <span class="n">Y_test</span><span class="p">)))</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered"><div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="Train-model-without-regularization">Train model without regularization<a class="anchor-link" href="#Train-model-without-regularization">¶</a></h3>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight hl-ipython3"><pre><span></span><span class="n">model</span><span class="p">(</span><span class="n">learning_rate</span><span class="o">=</span><span class="mf">0.5</span><span class="p">,</span> <span class="n">num_steps</span><span class="o">=</span><span class="mi">1601</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
<pre>
Train 3-layer NN with following settings:
Regularization lambda: 0
Learning rate: 0.5
learning_decay: False
keep_prob: 1
Batch_size: 128
Number of steps: 1601
n1, n2, n3: 1024, 512, 256
Initialized
</pre>
</div>
</div>
<div class="output_area">
<div id="cc45e11b-cf12-4322-b6ec-d82e1f2385e2"></div>
<div class="output_subarea output_widget_view">
<script type="text/javascript">
var element = $('#cc45e11b-cf12-4322-b6ec-d82e1f2385e2');
</script>
<script type="application/vnd.jupyter.widget-view+json">
{"model_id": "95a1e075513f4d02a8579c4fcd5b8509", "version_major": 2, "version_minor": 0}
</script>
</div>
</div>
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
<pre>Minibatch loss at step 0: 2.374. batch acc: 14.1%, Valid acc: 28.4%.
Minibatch loss at step 200: 0.600. batch acc: 82.0%, Valid acc: 84.9%.
Minibatch loss at step 400: 0.429. batch acc: 89.8%, Valid acc: 85.8%.
Minibatch loss at step 600: 0.372. batch acc: 87.5%, Valid acc: 85.7%.
Minibatch loss at step 800: 0.454. batch acc: 89.1%, Valid acc: 87.7%.
Minibatch loss at step 1000: 0.374. batch acc: 87.5%, Valid acc: 88.1%.
Minibatch loss at step 1200: 0.251. batch acc: 91.4%, Valid acc: 88.8%.
Minibatch loss at step 1400: 0.397. batch acc: 89.8%, Valid acc: 89.0%.
Minibatch loss at step 1600: 0.470. batch acc: 82.0%, Valid acc: 88.9%.
Test acc: 94.2%
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered"><div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="L2-regularization_1">L2 regularization<a class="anchor-link" href="#L2-regularization">¶</a></h2><p>Introduce and tune L2 regularization for the models. Remember that L2 amounts to adding a penalty on the norm of the weights to the loss. In TensorFlow, you can compute the L2 loss for a tensor <code>t</code> using <code>nn.l2_loss(t)</code>. The right amount of regularization should improve your validation / test accuracy.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight hl-ipython3"><pre><span></span><span class="c1"># for lamda in [1 / 10 ** i for i in list(np.arange(1, 4))]:</span>
<span class="c1"># model(lamba=lamda)</span>
<span class="n">model</span><span class="p">(</span><span class="n">lamba</span><span class="o">=</span><span class="mf">0.1</span><span class="p">,</span> <span class="n">learning_rate</span><span class="o">=</span><span class="mf">0.01</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
<pre>
Train 3-layer NN with following settings:
Regularization lambda: 0.1
Optimizer: sgd
Learning rate: 0.01
Batch_size: 128
Number of steps: 501
n1, n2: 512, 256
Initialized
</pre>
</div>
</div>
<div class="output_area">
<div id="d3df8dd9-387d-4ef5-8e35-d373ed853d5c"></div>
<div class="output_subarea output_widget_view">
<script type="text/javascript">
var element = $('#d3df8dd9-387d-4ef5-8e35-d373ed853d5c');
</script>
<script type="application/vnd.jupyter.widget-view+json">
{"model_id": "6b6986da296646b9aac2266326edcf21", "version_major": 2, "version_minor": 0}
</script>
</div>
</div>
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
<pre>Minibatch loss at step 0: 22969.777. batch acc: 9.4%, Valid acc: 19.3%.
Minibatch loss at step 200: 13876.185. batch acc: 74.2%, Valid acc: 75.2%.
Minibatch loss at step 400: 9266.566. batch acc: 78.1%, Valid acc: 74.3%.
Test acc: 81.4%
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered"><div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="Case-of-overfitting">Case of overfitting<a class="anchor-link" href="#Case-of-overfitting">¶</a></h2><p>Let's demonstrate an extreme case of overfitting. Restrict your training data to just a few batches. What happens?</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight hl-ipython3"><pre><span></span><span class="n">model</span><span class="p">(</span><span class="n">num_steps</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
<pre>
Train 3-layer NN with following settings:
Regularization lambda: 0
Learning rate: 0.01
learning_decay: False
keep_prob: 1
Batch_size: 128
Number of steps: 10
n1, n2, n3: 1024, 512, 256
Initialized
</pre>
</div>
</div>
<div class="output_area">
<div id="2ed6f140-4dc0-4001-9798-117c52a1a519"></div>
<div class="output_subarea output_widget_view">
<script type="text/javascript">
var element = $('#2ed6f140-4dc0-4001-9798-117c52a1a519');
</script>
<script type="application/vnd.jupyter.widget-view+json">
{"model_id": "312b63e26f364cec95540b452b4ec95c", "version_major": 2, "version_minor": 0}
</script>
</div>
</div>
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
<pre>Minibatch loss at step 0: 2.442. batch acc: 8.6%, Valid acc: 11.4%.
Test acc: 20.7%
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered"><div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="Dropout">Dropout<a class="anchor-link" href="#Dropout">¶</a></h2><p>Introduce Dropout on the hidden layer of the neural network. Remember: Dropout should only be introduced during training, not evaluation, otherwise your evaluation results would be stochastic as well. TensorFlow provides <code>nn.dropout()</code> for that, but you have to make sure it's only inserted during training.</p>
<p>What happens to our extreme overfitting case?</p>
<p><img src="images/dropout1_kiank.mp4"/></p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight hl-ipython3"><pre><span></span><span class="n">model</span><span class="p">(</span><span class="n">num_steps</span><span class="o">=</span><span class="mi">10</span><span class="p">,</span> <span class="n">keep_prob</span><span class="o">=</span><span class="mf">0.5</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
<pre>
Train 3-layer NN with following settings:
Regularization lambda: 0
Learning rate: 0.01
learning_decay: False
keep_prob: 0.5
Batch_size: 128
Number of steps: 10
n1, n2, n3: 1024, 512, 256
Initialized
</pre>
</div>
</div>
<div class="output_area">
<div id="6d79ddf7-a1df-4d13-8be7-4d10a8d11976"></div>
<div class="output_subarea output_widget_view">
<script type="text/javascript">
var element = $('#6d79ddf7-a1df-4d13-8be7-4d10a8d11976');
</script>
<script type="application/vnd.jupyter.widget-view+json">
{"model_id": "f5a5be47b2a14f488d9d302df5d5988d", "version_major": 2, "version_minor": 0}
</script>
</div>
</div>
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
<pre>Minibatch loss at step 0: 2.784. batch acc: 7.0%, Valid acc: 10.0%.
Test acc: 17.3%
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered"><div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="Boost-performance-by-using-Multi-layer-NN">Boost performance by using Multi-layer NN<a class="anchor-link" href="#Boost-performance-by-using-Multi-layer-NN">¶</a></h2><p>Try to get the best performance you can using a multi-layer model! The best reported test accuracy using a deep network is <a href="http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html?showComment=1391023266211#c8758720086795711595">97.1%</a>.</p>
<p>One avenue you can explore is to add multiple layers.</p>
<p>Another one is to use learning rate decay:</p>
<pre><code>global_step = tf.Variable(0) # count the number of steps taken.
learning_rate = tf.train.exponential_decay(0.5, global_step, ...)
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
</code></pre>
<hr/>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight hl-ipython3"><pre><span></span><span class="n">model</span><span class="p">(</span><span class="n">learning_decay</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">num_steps</span><span class="o">=</span><span class="mi">1501</span><span class="p">,</span> <span class="n">lamba</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">keep_prob</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
<pre>
Train 3-layer NN with following settings:
Regularization lambda: 0
Learning rate: 0.01
learning_decay: True
keep_prob: 1
Batch_size: 128
Number of steps: 1501
n1, n2, n3: 1024, 512, 256
Initialized
</pre>
</div>
</div>
<div class="output_area">
<div id="c0f8af43-cd3e-48b5-8152-156efc1e2c67"></div>
<div class="output_subarea output_widget_view">
<script type="text/javascript">
var element = $('#c0f8af43-cd3e-48b5-8152-156efc1e2c67');
</script>
<script type="application/vnd.jupyter.widget-view+json">
{"model_id": "ee2b75cf5f6542f99a17c5ad02bc49fd", "version_major": 2, "version_minor": 0}
</script>
</div>
</div>
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
<pre>Minibatch loss at step 0: 2.395. batch acc: 12.5%, Valid acc: 37.0%.
Minibatch loss at step 200: 0.589. batch acc: 82.0%, Valid acc: 84.7%.
Minibatch loss at step 400: 0.409. batch acc: 89.1%, Valid acc: 86.2%.
Minibatch loss at step 600: 0.396. batch acc: 88.3%, Valid acc: 86.5%.
Minibatch loss at step 800: 0.435. batch acc: 88.3%, Valid acc: 87.6%.
Minibatch loss at step 1000: 0.407. batch acc: 85.2%, Valid acc: 88.5%.
Minibatch loss at step 1200: 0.262. batch acc: 91.4%, Valid acc: 88.9%.
Minibatch loss at step 1400: 0.411. batch acc: 87.5%, Valid acc: 88.8%.
Test acc: 94.3%
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight hl-ipython3"><pre><span></span>
</pre></div>
</div>
</div>
</div>
</div>
<script type="text/javascript">if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {
var mathjaxscript = document.createElement('script');
mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';
mathjaxscript.type = 'text/javascript';
mathjaxscript.src = '//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
mathjaxscript[(window.opera ? "innerHTML" : "text")] =
"MathJax.Hub.Config({" +
" config: ['MMLorHTML.js']," +
" TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' } }," +
" jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
" extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
" displayAlign: 'center'," +
" displayIndent: '0em'," +
" showMathMenu: true," +
" tex2jax: { " +
" inlineMath: [ ['$','$'] ], " +
" displayMath: [ ['$$','$$'] ]," +
" processEscapes: true," +
" preview: 'TeX'," +
" }, " +
" 'HTML-CSS': { " +
" linebreaks: { automatic: true, width: '95% container' }, " +
" styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'black ! important'} }" +
" } " +
"}); ";
(document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);
}
</script>
<!-- Tags -->
<p class="blog-content__tags">
<span>Post Tags</span>
<span class="blog-content__tag-list">
<a href="https://leemeng.tw/tag/tensorflow.html" rel="tag">Tensorflow</a>
<a href="https://leemeng.tw/tag/python.html" rel="tag">Python</a>
<a href="https://leemeng.tw/tag/deep-learning.html" rel="tag">Deep Learning</a>
<a href="https://leemeng.tw/tag/regularization.html" rel="tag">Regularization</a>
<a href="https://leemeng.tw/tag/deep-learning-by-google.html" rel="tag">Deep Learning by Google</a>
<a href="https://leemeng.tw/tag/machine-learning-engineer-by-kaggle.html" rel="tag">Machine Learning Engineer by kaggle</a>
<a href="https://leemeng.tw/tag/udacity.html" rel="tag">Udacity</a>
</span>
</p>
<!-- end Tags -->
<!-- Mail-list-subscribe -->
<div id="article-inner-subscribe" class="blog-content__pagenav">
<div class="blog-content__nav">
<div class="blog-content__prev">
<a class="open-popup" rel="subscribe">
<span>Get Latest Arrivals</span>
訂閱最新文章
</a>
</div>
<div class="blog-content__next">
<p>
跟資料科學相關的最新文章直接送到家。</br>
只要加入訂閱名單,當新文章出爐時,</br>
你將能馬上收到通知 <i class="im im-newspaper-o" aria-hidden="true"></i>
</p>
</div>