-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
1611 lines (1271 loc) · 60.5 KB
/
index.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
<?xml version = "1.0" encoding = "UTF-8"?>
<xsl:stylesheet version = "1.0" xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">
<xsl:template match = "/">
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Memristec Hands-On Tutorial</title>
<meta name="description" content="NNML">
<meta name="author" content="Emre Neftci">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<link rel="stylesheet" href="dist/reset.css">
<link rel="stylesheet" href="dist/reveal.css">
<link rel="stylesheet" href="nmilab.css">
<!-- Theme used for syntax highlighted code -->
<link rel="stylesheet" href="plugin/highlight/monokai.css">
<script src="jquery.js"></script>
<script>
$(function(){
$("#sdlides").load("slides_1_inner.html");
});
</script>
</head>
<body>
<div class="reveal">
<div class="slides">
<section data-markdown data-vertical-align-top data-background-color=#B2BA67><textarea data-template>
<h1> Neuromorphic Computing and Algorithms<br/> </h1>
</textarea></section>
<section data-markdown data-vertical-align-top><textarea data-template>
<h2> Focus of this Lecture:<br/> Machine Learning and Neural Networks for Neuromorphic Engineering </h2>
<img src= img/pgi15_triangle.png class=large />
<p> What you'll learn: </p>
<ul>
<li/> Foundations of Neural Networks (Perceptrons, gradient descent)
<li/> Neural networks and their implementation in Python/PyTorch
<li/> Basic hardware-aware training using Pytorch and IBM AI hardware kit
</ul>
</textarea>
</section>
<script>
//function for evaluation
function solve()
{
let w0 = parseFloat(document.getElementById("w0").value)-50
let w1 = parseFloat(document.getElementById("w1").value)-50
let b = parseFloat(document.getElementById("b").value) -50
document.getElementById("a11").innerHTML = (eval(w0)*1+eval(w1)*1+eval(b)).toFixed(2)
document.getElementById("a10").innerHTML = (eval(w0)*1+eval(w1)*0+eval(b)).toFixed(2)
document.getElementById("a01").innerHTML = (eval(w0)*0+eval(w1)*1+eval(b)).toFixed(2)
document.getElementById("a00").innerHTML = (eval(w0)*0+eval(w1)*0+eval(b)).toFixed(2)
document.getElementById("y11").innerHTML = (((eval(w0)*1+eval(w1)*1+eval(b))>0)*1)
document.getElementById("y10").innerHTML = (((eval(w0)*1+eval(w1)*0+eval(b))>0)*1)
document.getElementById("y01").innerHTML = (((eval(w0)*0+eval(w1)*1+eval(b))>0)*1)
document.getElementById("y00").innerHTML = (((eval(w0)*0+eval(w1)*0+eval(b))>0)*1)
document.getElementById('w0val').innerHTML=eval(w0).toFixed(2);
document.getElementById('w1val').innerHTML=eval(w1).toFixed(2);
document.getElementById('bval').innerHTML =eval(b).toFixed(2);
}
</script>
<section>
<h2>The First Artificial Neuron</h2><ul>
<li><p>In 1943, McCulloch and Walter Pitts propose the first artificial neuron, the Linear Threshold Unit. </p>
<img src="images/artificial_neuron.png" class="large"/>
</li>
<li>In the Linear Threshold Unit, $f$ is a step function: $f(x) = 1$ if $x>0$
</li>
<li>"Modern" artificial neurons are similar, but $f$ is typically a sigmoid or rectified linear function</li>
</ul>
</section>
<section>
<h2>Basic Mathematical Model of the Artificial Neuron</h2>
<div class=row>
<div class=column>
<img src="images/artificial_neuron.png"/>
</div>
<div class=column>
<ul>
<li>$x_i$ is the state of the input neurons</li>
<li>$w_i$ is the weight of the connection</li>
<li>$b$ is a bias</li>
<li>The total input to the neuron is: $ a = \sum_i w_i x_i +b $</li>
<li>The output of the neuron is: $ y = f(a) $</li>
<li>where $f$ is the activation function</li>
</ul>
</div>
</div>
</section>
<section data-markdown><textarea data-template>
<h2>The Perceptron</h2>
<img src="images/rosenblatt57_title.png" />
<blockquote>
<img src="images/rosenblatt57_quote1.png" class=small />
</blockquote>
<ul>
<li/> Further reading: <a href="https://news.cornell.edu/stories/2019/09/professors-perceptron-paved-way-ai-60-years-too-soon">Professor’s perceptron paved the way for AI – 60 years too soon </a>
</ul>
</textarea></section>
<section>
<h2>The Perceptron</h2>
<ul>
<li> The Perceptron is a special case of the artificial neuron where:
$$
\begin{eqnarray}
\mbox{y} & = & \begin{cases}
-1 & \mbox{if } a = \sum_j w_j x_j + b \leq 0 \\\\
1 & \mbox{if } a = \sum_j w_j x_j + b > 0
\end{cases}
\end{eqnarray}
$$</li>
<img src=images/single_perceptron.svg />
<li> Three inputs $x_1$, $x_2$, $x_3$ with weights $w_1$, $w_2$, $w_3$, and bias $b$</li>
</ul>
</section>
<section>
<h2> Perceptron Example</h2>
<ul>
<li/> Like McCulloch and Pitts neurons, Perceptrons can be hand-constructed to solve simple logical tasks
<li/> Let's build a "sprinkler" that activates only if it is dry and sunny.
<li/> Let's assume we have a dryness detector $x_0$ and a light detector $x_1$ (two inputs)
<li/> Find $w_0$, $w_1$ and $b$ such that output $y$ matches target $t$
</ul>
<div class=row>
<div class=column>
<img src="images/twonode_perceptron_template.svg" style="height:200px" />
</div>
<div class=column>
<table>
<thead>
<tr>
<th>Sunny</th>
<th>Dry</th>
<th>$a$</th>
<th>$y$</th>
<th>$t$</th>
</tr>
</thead>
<tbody>
<tr>
<td>1 (yes)</td>
<td>1 (yes)</td>
<td> <div id="a11"></div></td>
<td> <div id="y11"></div></td>
<td>1</td>
</tr>
<tr>
<td>1 (yes)</td>
<td>0 (no)</td>
<td> <div id="a10"></div></td>
<td> <div id="y10"></div></td>
<td>0</td>
</tr>
<tr>
<td>0 (no)</td>
<td>1 (yes)</td>
<td> <div id="a01"></div></td>
<td> <div id="y01"></div></td>
<td>0</td>
</tr>
<tr>
<td>0 (no)</td>
<td>0 (no)</td>
<td> <div id="a00"/></div></td>
<td> <div id="y00"/></div></td>
<td>0</td>
</tr>
</tbody>
</table>
</div>
</div>
<table border="1">
<tr>
<td>$w_0 =$ <span id=w0val>0</span></td>
<td>$w_1 =$ <span id=w1val>0</span></td>
<td>$b =$ <span id=bval>0</span></td>
</tr>
<tr>
<td colspan="1"><input type="range" min="-50." max="100." step=0.01 onchange="solve();" id="w0" /></td>
<td colspan="1"><input type="range" min="-50." max="100." step=0.01 onchange="solve();" id="w1" /></td>
<td colspan="1"><input type="range" min="-50." max="100." step=0.01 onchange="solve();" id="b" /></td>
</tr>
</table>
</section>
<section data-markdown><textarea data-template>
## The Perceptron Learning Rule
<img src=images/perceptron_convergence.png class=large />
<p class=ref>(Bishop, 2006 Pattern Recognition and Machine Learning)</p>
- Perceptron convergence theorem: if the training dataset is linearly separable, then the perceptron learning rule is guaranteed to find an exact solution
<p class=ref>(Rosenblatt, 1962, Principles of Neurodynamics: Perceptrons and the Theory of Brain Mechanisms)</p>
</textarea></section>
<section data-markdown><textarea data-template>
## Cost Functions
<ul>
<li/> The Cost (Error) function returns a number representing how well a model performed.
<li/> Perceptrons: Cost function = Number of Misclassified Samples
<li/> Other common cost functions are
<ul>
<li/> Mean Squared Error: $ C_\text{MSE} = \frac{1}{2N} \sum_{n \in \text{train}} (\mathbf{y}^n - \mathbf{t}^n) ^2 $
<li/> Cross-Entropy: $ C_{XENT} = - \frac1N \sum_{n \in \text{train}} \sum_k y_{k}^n \log t_{k}^n $
</ul>
<li /> The objective is to minimize the cost function.
<li /> Cost functions can be minimized using an optimization algorithm
</ul>
</textarea></section>
<section data-markdown><textarea data-template>
## Optimization Algorithm Gradient Descent
Example: Find $x$ that minimizes $C(x) = x^2$
<img src=images/quadratix_function.png class=small />
- Incremental change in $\Delta x$:
$$
\begin{eqnarray}
\Delta C \approx \underbrace{\frac{\partial C}{\partial x}}_{\text{=Slope of }C(x)} \Delta x
\end{eqnarray}
$$
With $\Delta x = - \eta \frac{\partial C}{\partial x}$, $\Delta C \approx - \eta \left( \frac{\partial C}{\partial x} \right)^2$
- Gradient Descent for finding the optimal $x$:
$
\begin{eqnarray}
x \leftarrow x - \eta \frac{\partial C}{\partial x}
\end{eqnarray}
$
</textarea></section>
<section data-markdown><textarea data-template>
## Linear separability
A perceptron is equivalent to a decision boundary.
- A straight line can separate blue vs. red
<img src=images/perceptron_rain_hyperplane.png class="small">
- There is no straight line that can separate blue vs. red <!-- .element: class="fragment" -->
<img src=images/perceptron_xor_hyperplane.png class="small">
<p class="pl">Problems where a straight line can separate two classes are called <em>Linearly Separable</em></p>
</textarea></section>
<section data-markdown><textarea data-template>
## Limitations of Perceptrons
The limitation of a Perceptron to linearly separable problems caused its downfall:
<img src="images/perceptrons_minsky_papert.png" class=stretch />
<p class=ref> Minsky and Papert, 1969 </p>
</textarea></section>
<section data-markdown><textarea data-template>
## XOR can be solved with an intermediate perceptron
<div class=row>
<div class=column>
<img src="images/perceptron_xor_hyperplane.svg" class="large" />
</div>
<div class=column>
<img src="images/perceptron_xor_hyperplane_extended.svg" class=large />
</div>
</div>
- We need an intermediate unit that is on only when $x_1$ and $x_2$ are both on.
</textarea></section>
<section data-markdown><textarea data-template>
## A Neural Network Solving XOR
- Find the parameters in the following network:
<div class=row>
<div class=column>
<img src="images/xor_template.svg" class="stretch" />
</div>
<div class=column>
<table>
<tbody><tr bgcolor="#ddeeff" align="center">
<td colspan="2"><b>INPUT</b></td>
<td><b>Y</b>
</td></tr>
<tr bgcolor="#ddeeff" align="center">
<td>A</td>
<td>B</td>
<td>A XOR B
</td></tr>
<tr bgcolor="#ddffdd" align="center">
<td>0</td>
<td>0</td>
<td>0
</td></tr>
<tr bgcolor="#ddffdd" align="center">
<td>0</td>
<td>1</td>
<td>1
</td></tr>
<tr bgcolor="#ddffdd" align="center">
<td>1</td>
<td>0</td>
<td>1
</td></tr>
<tr bgcolor="#ddffdd" align="center">
<td>1</td>
<td>1</td>
<td>0
</td></tr></tbody>
</table>
</div>
<div class=fragment><p class=pl> The strategy of automatically extending networks with intermediate units is the main idea of representation learning </p></div>
</textarea></section>
<section>
<section data-markdown><textarea data-template>
## Neural Network
- We can connect Perceptrons together to form a multi-layered network.
<img src=images/mlp.png />
<ul>
<li/> If a neuron produces an input, it is called an <em>input neuron</em>
<li/> If a neuron's output is used as a prediction, we will call it an <em>output neuron</em>
<li/> If a neuron is neither and input or an output neuron, it is a <em>hidden neuron</em>
</ul>
- Increased level of abstraction from layer to layer
- Also called Multilayer Perceptrons (although units are not always Perceptrons)
</textarea></section>
<section data-markdown><textarea data-template>
## Multiple Linear Layers are Equivalent to one Single Layer
<ul>
<li/> A linear transformation is of the type:
$$
\mathbf{y} = W \mathbf{x}
$$
<li/> Linear networks are mathematically tractable, so why not build multilayer linear networks?
$$
\mathbf{y}^{(2)} = {W}^{(2)} ({W}^{(1)} \mathbf{x}^{(1)} )
$$
<li class=fragment /> Such a network is equivalent to a wide single layer network
$$
\begin{split}
\mathbf{y}^{(2)} &= V \mathbf{x}^{(1)} \\
V &= W^{(2)} W^{(1)}
\end{split}
$$
<li class=fragment /> Non-linearities preserve the composition of layers, and thus have more representational power
$$
\begin{split}
\mathbf{y}^{(2)} &= \sigma(W^{(2)}\sigma(W^{(1)}\mathbf{x}^{(1)} ) )
\end{split}
$$
</ul>
</textarea></section>
<section data-markdown><textarea data-template>
## Deep neural networks
- Before:
<blockquote>
How many hidden layers and how many units per layer do we need? The answer is at most two
</blockquote>
<p class=ref> Hertz, <em>et al.</em> 1991</p>
- Now:
<blockquote>
<img src="images/gist_Szegedy_etal14_90deg.png" style="height:100px" />
</blockquote>
<p class=ref> Szegedy <em>et al.</em> 2014 </p>
<p class=pl> Deeper networks tend to have more representational power </p>
</textarea></section>
<section data-markdown><textarea data-template>
## Credit Assignment Problem
Multilayer (deep) networks are more powerful: how can one train multilayer networks?
<img src=images/mlp_gradient.png />
Two problems:
- Perceptrons' discontinuity
- Credit assignment: which hidden unit weight should we modify to reach a target output?
</textarea></section>
<section data-markdown><textarea data-template>
## Continuous Output Neurons (Sigmoid Neuron)
Neurons in deep neural networks are similar to Perceptrons, but with a continuous activation function
<div class="row">
<div class="column">
<p>Threshold unit (Perceptron)</p>
$$
y = \Theta(a) = \begin{cases} -1 & \mbox{if } a \leq 0 \\ 1 & \mbox{if } a > 0 \end{cases}
$$
</div>
<div class="column">
<p> Sigmoid unit</p>
$$
y = \sigma(\text{a}) = \frac{1}{1+e^{-a}}
$$
</div>
</div>
<div class="row">
<div class="column">
<img src="images/step_function.png" class=small />
</div>
<div class="column">
<img src="images/sigmoid_function.png" class=small />
</div>
</div>
$$
a = \sum_j w_j x_j + b
$$
- A function is continuous if the curve can be drawn "without lifting the pen"
</textarea></section>
<section data-markdown><textarea data-template>
## Single Layer Network with Sigmoid Units
Weight matrix: $W^{(1)} \in \mathbb{R}^{N\times M}$ (meaning $M$ inputs, $N$ outputs)
`$$
\begin{eqnarray}
y^{(1)}_i &=& \sigma(\underbrace{\sum_j W^{(1)}_{ij} x_j}_{a_i^{(1)}}) \\
\end{eqnarray}
$$`
- MSE cost function, assuming a single data sample $\mathbf{x}\in\mathbb{R}^{M} $, and target vector $\mathbf{t}\in\mathbb{R}^{N}$
`$$
C_{MSE} = \frac{1}{2} \sum_i(y^{(1)}_i - t_i)^2
$$`
- Gradient w.r.t. $W^{(1)}$ (in scalar form):
`$$
\frac{\partial }{\partial W^{(1)}_{ij}} C_\text{MSE}= \frac1N (y^{(1)}_i - t_i) \sigma'(a^{(1)}_i) x_j
$$`
</textarea></section>
<section data-markdown><textarea data-template>
## Single Layer Network with Sigmoid Units
<p> Neural networks operations are generally written in Matrix form</p>
<div class=row>
<div class=column>
<center>Scalar Form (one sample)</center>
$$
\begin{split}
a_i^{(1)} &= \sum_j W^{(1)}_{ij} x_j, \quad y^{(1)}_i = \sigma(a_i^{(1)}) \\
\delta_i^{(1)} &= \frac{1}{N^{s}} (y^{(1)}_i - t_i) \sigma'(a^{(1)}_i)\\
\Delta W_{ij} &= -\eta \delta_i x_j
\end{split}
$$
</div>
<div class=column>
<center>Matrix Form ($N^{s}$ samples)</center>
<div class=fragment>
$$
\begin{split}
A^{(1)} & = X W^{(1),T}, \quad
Y^{(1)} = \sigma(A^{(1)}) \\
\end{split}
$$
</div>
<div class=fragment>
$$
\begin{split}
\delta &= \frac{1}{N^{s}} (Y^{(1)} - T) \odot \sigma'(A^{(1)}) \\
\end{split}
$$
</div>
<div class=fragment>
$$
\begin{split}
\Delta W & = - \eta \delta^T \mathbf{X} \\
\end{split}
$$
</div>
</div>
</div>
$$
W \leftarrow W + \Delta W
$$
<ul>
<li /> $\delta$ $\in \mathbb{R}^{N^{s}\times N}$, $X$ $\in \mathbb{R}^{N^{s} \times M}$, and dimension of $\Delta W$ must be same as $W$!
<li /> Implement it here (Optional):
</ul>
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1xQiNcjf-O88vi_09R5Zntv_gK2zB7MMh?usp=sharing)
</textarea></section>
<section data-markdown><textarea data-template>
## Two Layer Network with Sigmoid Units
- Two layers means we have two weight matrices $W^{(1)}$ and $W^{(2)}$
- $W^{(1)} \in \mathbb{R}^{N^{(1)}\times M}$, $W^{(2)} \in \mathbb{R}^{N^{(2)}\times N^{(1)}}$
- The output is a composition of two functions:
$$
\begin{eqnarray}
\mathbf{y}^{(1)} &=& \sigma(W^{(1)} \mathbf{x} ) \\\\
\mathbf{y}^{(2)} &=& \sigma(W^{(2)} \mathbf{y}^{(1)} ) \\\\
\end{eqnarray}
$$
<ul>
<li class=fragment /> Cost function $ C_{MSE} = \frac{1}{2N^{s}} \sum_{i=1}^{N^{(2)}}(y^{(2)}_i - t_i)^2 $
<li class=fragment /> Gradient wrt $W^{(2)}$ is: $ \frac{\partial }{\partial W^{(2)}_{ij}} C_\text{MSE}= \underbrace{(y^{(2)}_i - t_i) \sigma'(a^{(2)}_i)}_{\delta^{(2)}_i} y^{(1)}_j $
<li class=fragment /> Gradient wrt $W^{(1)}$ is: $ \frac{\partial}{\partial { W_{jk}^{(1)}}} C_{\text{MSE}} = \underbrace{(\sum_i \delta_i^{(2)} W^{(2)}_{ij}) \sigma'(a^{(1)}_j)}_{backpropagated\, error\, \delta^{(1)}_{j}} x_k $
<li class=fragment /> This is a special case of the gradient backpropagation algorithm
</ul>
</textarea></section>
<section data-markdown><textarea data-template>
## The Gradient Back-Propagation Algorithm
![image.png](images/slides2_backprop.png)
1. Forward-propagate to compute $y^{(k)}$ for all layers $k$
2. Compute loss and error
3. Back-propagate error through network, *i.e* compute all $\mathbf{\delta}^{(k)}$
</textarea></section>
<section data-markdown data-background-color=#BBBBBB><textarea data-template>
## The Gradient BP algorithm (for your reference)
<div style='font-size:24px;text-align:left;' >
<p>The task of learning is to minimize a cost function $\mathcal{L}$ over the entire dataset.
In a neural network, this can be achieved by gradient descent, which modifies the network parameters $\mathbf{W}$ in the direction opposite to the gradient:
$$
\begin{split}
W_{ij} \leftarrow W_{ij} - \eta \Delta W_{ij}, & \text{where } \Delta W_{ij} =
\Dp{\mathcal{L}}{W_{ij}} =
\Dp{\mathcal{L}}{y_i}
\Dp{y_i}{ a_i }
\Dp{a_i}{W_{ij}}
\end{split}
$$
with $a_i = \sum_j W_{ij} x_j$ the total input to the neuron, $y_i$ is the output of neuron $i$, and $\eta$ a small learning rate.
The first term is the error of neuron $i$ and the second term reflects the sensitivity of the neuron output to changes in the parameter.
In multilayer networks, gradient descent is expressed as the BP of the errors starting from the prediction (output) layer to the inputs.
Using superscripts $l=0,...,L$ to denote the layer ($0$ is input, $L$ is output):
`$$
\frac{\mathrm{\partial}}{\mathrm{\partial} W^{(l)}_{ij}} \mathcal{L} =
\delta_{i}^{(l)} y^{(l-1)}_j,\text{ where }\delta_{i}^{(l)} = \sigma'\left(
a_i^{(l)} \right) \sum_k \delta_{k}^{(l+1)} W_{ik}^{\top,(l)},
$$`
where $\sigma'$ is the derivative of the activation function, and $\delta_{i}^{(L)}=\Dp{\mathcal{L}}{y_i^{(L)}}$ is the error of
output neuron $i$ and $y_{i}^{(0)}=x_i$ and $\top$ indicates the transpose.
Learning is typically carried out in forward passes (evaluation of the neural network activities) and backward passes (evaluation of $\delta$s).
</p>
</div>
</textarea></section>
</section>
<section>
<iframe data-src="http://playground.tensorflow.org/" width=95% style='max-height:720px;height:720px;max-width:100%;'></iframe>
</section>
<section>
<section data-markdown><textarea data-template>
## Neural Networks with PyTorch
- PyTorch is a machine learning framework that facilitates the implementation of Deep Learning
- Other tools such as Tensorflow or Theano have a similar purpose, but PyTorch is more versatile and easier to use.
- To use pytorch, remember to import it:
<pre><code class="Python" data-trim data-noescape> import torch </code></pre>
- Follow-along notebook
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://drive.google.com/open?id=1botgh24In3QFyMc9AmezPszgt2ntJ-OL)
- PyTorch is one out of several other ML frameworks (PyTorch, Tensorflow/Keras, Jax). PyTorch arguably the easiest to use and is <a href="https://pytorch.org/blog/PyTorchfoundation/?utm_source=twitter&utm_medium=organic_social&utm_campaign=foundation3a" >belongs to the linux foundation</a> (open source)
</textarea></section>
<section data-markdown><textarea data-template>
## Tensor
- The tensor is the basic data type of Pytorch (and many other tools likes tensorflow)
![image.png](images/tensor.png)
- A tensor is a multi-dimensional array
> For example, a color image could be encoded as a 3D tensor with dimensions of width, height, and color plane.
- Apart from dimensions, a tensor is characterized by the type of its elements (integer, float, double, byte, boolean etc.).
</textarea></section>
<section data-markdown><textarea data-template>
## Tensor Creation
Tensors can be created like numpy arrays
<ul>
<li > Numpy
</ul>
<pre><code class="Python" data-trim data-noescape>
a = np.array([[1,2,3],[3,2,1]])
</code></pre>
<div class=fragment >
<ul>
<li > PyTorch
</ul>
<pre><code class="Python" data-trim data-noescape>
b = torch.FloatTensor([[1,2,3],[3,2,1]])
b = torch.FloatTensor(a) #equivalent
</code></pre>
</div>
</textarea></section>
<section data-markdown><textarea data-template>
## Tensor Creation
- Tensors can also be converted from a numpy array
<pre><code class="Python" data-trim data-noescape>
n = np.zeros(shape=(3, 2))
c= torch.tensor(n)
</code></pre>
</textarea></section>
<section data-markdown><textarea data-template>
## Tensor Operations
There are many operations that can be performed on tensors. See http://pytorch.org/docs/. Some examples below
- Addition
<pre><code class="Python" data-trim data-noescape>
b + b
</code></pre>
- Multiplication
<pre><code class="Python" data-trim data-noescape>
b*b
</code></pre>
</textarea></section>
<section data-markdown><textarea data-template>
## Tensor Operations (continued)
There are many operations that can be performed on tensors. See http://pytorch.org/docs/. Some examples below
<ul>
<li/> Transpose
<pre><code class="Python" data-trim data-noescape>
b.transpose(0,1) #flips axes 0 and 1
</code></pre>
<li/> Matrix multiplication
<pre><code class="Python" data-trim data-noescape>
torch.mm(b,b.transpose(0,1))
[email protected](0,1)
</code></pre>
</ul>
</textarea></section>
<section data-markdown><textarea data-template>
## Graph Representation of an Expression
Pytorch and other frameworks represent a function using a graph
<img src="images/slides2_compgraph.png" id="fwimg" style="height:150px"/>
<pre><code class="Python" data-trim data-noescape>
v1 = torch.tensor([1.0, 1.0], requires_grad=True)
v2 = torch.tensor([2.0, 2.0])
v_sum = v1 + v2
v_res = (v_sum*2).sum()
</code></pre>
</textarea></section>
<section data-markdown><textarea data-template>
## Automatic Differentiation
<ul>
<li/> A key feature of machine learning frameworks is automatic differentiation
<li/> With automatic differentation, the gradients are computed automatically across a set of operations
<li/> Once a backward operation is called on a node, the gradients of all <i>leaf</i> nodes and parameters in the expression are numerically computed
<pre><code class="Python" data-trim data-noescape>
v_res.backward() #this command computes the gradient
v1.grad # returns tensor([2., 2.])
</code></pre>
<li class=fragment /> The gradient of v2 is None because we did not enable requires_grad
<pre><code class="Python" data-trim data-noescape>
v2.grad # returns None
</code></pre>
<pre><code class="Python" data-trim data-noescape>
v2.requires_grad #returns False
</code></pre>
</ul>
</textarea></section>
<section data-markdown><textarea data-template>
## GPUs and Tensors
<ul>
<li/> By default, tensors are stored in the CPU (main memory)
<pre><code class="Python" data-trim data-noescape>
b.device
</code></pre>
<li/> GPUs can be >100x faster on certain operations compared to CPUs
<li/> Tensors can be moved to the GPU using the cuda() function
<pre><code class="Python" data-trim data-noescape>
b_cuda = b.cuda(); b_cuda = b.to('cuda') #Both have the same effect
</code></pre>
<li/> If you get a runtime error, it means you didn't request for a gpu. go to Runtime> Change Runtime Type>Hardware accelerator and choose GPU, then SAVE
<img src=images/colab_runtime_cuda.png class=small />
<li/> All operations must occur on the same device. For example, you cannot add a cuda tensor to a cpu tensor (you need to cast it to cpu first).
</ul>
</textarea></section>
<section data-markdown><textarea data-template>
## Neural Network Building Blocks: Modules
<ul>
Up to now, nothing was specific for neural networks:
<li/> Machine learning frameworks can be used for all types of computations
PyTorch has predefined modules for constructing neural networks
<li/> All neural network building blocks are PyTorch modules
<pre><code class="Python" data-trim data-noescape>
torch.nn.Module
</code></pre>
<li/> Modules are containers for functions, tensors and parameters
<li/> Modules can be called like functions. (but to call them, you need to implement the forward function)
<pre><code class="Python" data-trim data-noescape>
my_module = torch.nn.Module()
my_module() #returns NotImplementedError
my_module.forward() #same as above
</code></pre>
</ul>
</textarea></section>
<section data-markdown><textarea data-template>
## Example: the linear module
- nn.Linear is a class that implements a module
- For example the nn.Linear module defines the linear transformation $$y = Wx + b$$
<pre><code class="Python" data-trim data-noescape>
lin = torch.nn.Linear(in_features = 2, out_features = 5)
x = torch.FloatTensor([1, 2])
y = lin(x)
</code></pre>
- The .parameters() function returns all parameters of the module
</textarea></section>
<section data-markdown><textarea data-template>
## Fully-connected Feedforward Networks (MLP)
<img src="images/mlp.png" id="fwimg" style="height:200px"/>
- Consists of fully connected (dense) layer.
- Implements the function: $$ \mathbf{y} = \sigma \left( W \mathbf{x} + \mathbf{b}\right) $$
- $W$ are trainable weights
- $\mathbf{b}$ are trainable biases
- $\sigma$ is an activation function
<pre><code class="Python" data-trim data-noescape>
a = torch.nn.Linear(in_channels=10, out_channels=5)
y = torch.sigmoid(a)
</code></pre>
</textarea></section>
<section data-markdown><textarea data-template>
## PyTorch Neural Network Bulding Block: Module
Modules can be composed to build a neural network.
The simplest method is the "sequential" mode that chains the operations
<pre><code class="py" data-trim data-noescape>
my_first_nn = torch.nn.Sequential(
torch.nn.Linear(2, 5),
torch.nn.Sigmoid(), #this is an activation function
torch.nn.Linear(5, 20),
torch.nn.Sigmoid(),
torch.nn.Linear(20, 2))
</code></pre>
Sequential returns a module, so it can be called as a function
<pre><code class="py" data-trim data-noescape>
my_first_nn(x)
</code></pre>
- Note that output dimensions of layer l-1 must match input dimensions of current layer l!
</textarea></section>
<section data-markdown><textarea data-template>
## Sequential Module
Modules can be composed to build a neural network.
The simplest method is the "sequential" mode that chains the operations
<pre><code class="py" data-trim data-noescape>
my_first_nn = torch.nn.Sequential(torch.nn.Linear(2, 5),
torch.nn.Sigmoid(), #this is an activation function
torch.nn.Linear(5, 20),
torch.nn.Sigmoid(),
torch.nn.Linear(20, 2))
</code></pre>
Sequential returns a module, so it can be called as a function
<pre><code class="py" data-trim data-noescape>
my_first_nn(x)
</code></pre>
- Note that output dimensions of layer l-1 must match input dimensions of current layer l!
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://drive.google.com/open?id=1botgh24In3QFyMc9AmezPszgt2ntJ-OL)
<pre><code class="py" data-trim data-noescape>
my_first_nn
Sequential(
(0): Linear(in_features=3, out_features=5, bias=True)
(1): Sigmoid()
(2): Linear(in_features=5, out_features=20, bias=True)
(3): Sigmoid()
(4): Linear(in_features=20, out_features=2, bias=True)
)
</code></pre>
</textarea></section>
<section data-markdown><textarea data-template>
## PyTorch Neural Network Building Block: Module
- Sequential works well for fully feedforward networks.
- In most cases, however, neural networks are implemented explicitely:
<pre><code class="Python" data-trim data-noescape>
class MySecondNetwork(torch.nn.Module):
def __init__(self, n1, n2, n3, num_classes):
super(MySecondNetwork, self).__init__()
self.layer1 = torch.nn.Linear(n1,n2)
self.layer2 = torch.nn.Linear(n2,n3)
self.layer3 = torch.nn.Linear(n3,num_classes)
self.sigmoid = torch.nn.Sigmoid()
def forward(self, data):
y1 = self.sigmoid(self.layer1(data))
y2 = self.sigmoid(self.layer2(y1))
y3 = self.sigmoid(self.layer3(y2))
return y3
my_second_net = MySecondNetwork(3,10,5,2)
my_second_net(x) # x has shape [M,3]
</code></pre>
</textarea></section>
<section data-markdown><textarea data-template>
## Loss functions and optimizers
- The loss function defines our objective. It is generally a **scalar** function.
- An optimizer defines the strategy to minimize the loss function
- Common loss functions for regression and classification:
- nn.MSELoss: Mean-Squared Error, default for regression tasks
$$ L_{MSE} = \frac1N \sum_{n} \sum_i (y_{ni}-t_{ni})^2 $$
- nn.CrossEntropyLoss: Default for classification tasks
$$L_{XENT} = - \frac1N \sum_n \sum_i t_{ni} \log y_{ni}$$
</textarea></section>
<section data-markdown><textarea data-template>
## Loss Function Example
- Mean-Squared Error (MSE)
<pre><code class="Python" data-trim data-noescape>
mse_loss = torch.nn.MSELoss()
target = torch.FloatTensor([[1.,0.,0.],[0.,0.,1.]])
loss = mse_loss(my_first_nn(data), target)
</code></pre>
- Cross Entropy
<pre><code class="Python" data-trim data-noescape>
xent_loss = torch.nn.CrossEntropyLoss()
target = torch.LongTensor([0,2])
loss = xent_loss(my_first_nn(data), target)
</code></pre>
</textarea></section>
<section data-markdown><textarea data-template>
## Loss functions and optimizers
- The loss function defines our objective
- An optimizer that defines the strategy to minimize the loss function (thus reach the objective)
- Common optimizers:
<ul>
<li /> SGD : A vanilla stochastic gradient descent algorithm
<pre><code class="Python" data-trim data-noescape> torch.optim.SGD </code></pre>
<li /> RMSprop : An optimizer that normalizes the gradients using moving root-mean-square averages
<pre><code class="Python" data-trim data-noescape> torch.optim.RMSProp </code></pre>
<li /> Adam : An adaptive gradients optimizer, works best in many cases
<pre><code class="Python" data-trim data-noescape> torch.optim.Adam </code></pre>
</ul>