-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathC3.1-Introduction_to_ANN-Slides.qmd
More file actions
1463 lines (896 loc) · 45.4 KB
/
C3.1-Introduction_to_ANN-Slides.qmd
File metadata and controls
1463 lines (896 loc) · 45.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
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
---
title: "ARTIFICIAL NEURAL NETWORKS"
subtitle: 'Neural Networks, Deep Learning and<br> Artificial Intelligence'
format:
revealjs:
incremental: false
transition: slide
background-transition: fade
transition-speed: slow
scrollable: true
menu:
side: left
width: half
numbers: true
slide-number: c/t
show-slide-number: all
progress: true
css: "css4CU.css"
theme: sky
knit:
quarto:
chunk_options:
echo: true
cache: false
prompt: false
tidy: true
comment: NA
message: false
warning: false
knit_options:
width: 75
bibliography: "DeepLearning.bib"
editor_options:
chunk_output_type: console
---
# From Artificial Neural Networks to Artifial Intelligence
## Historical Background (1)
- In the post-pandemic world, a lightning rise of AI, with a mess of realities and promises is impacting society.
- Since the emergence -and rapid growth- of Large Language Models and Generative AI everybody has an experience, an opinion, or a fear on the topic.
{fig-align="center" width="100%"}
## Is it just machine learning?
- Many tasks performed by AI can be described as **Predictive** as seen in *Recommendation systems, Image recognition or Natural language processing*.
- However, AI is broader than just prediction systems
- **Generative AI** is also able to generate new content.
- Both, predictive and generative capabilities of AI have far-reaching implications beyond technologies, including ethical or social aspects.
## AI, ANNs and Deep learning
- In many contexts, talking about AI means talking about
*Deep Learning (DL)*.
- DL is the dominant paradigm in modern (2026) AI and is behind applications such as *self-driving cars, voice assistants, and medical diagnosis systems*.
- DL originates in the field of *Artificial Neural Networks*
- DL extends the basic principles of ANNs by:
- Adding complex architectures and algorithms and
- Enabling scalable learning from large data
## The early history of AI (1)
```{r, out.width="90%", fig.cap= "[A Quick History of AI, ML and DL](https://nerdyelectronics.com/a-quick-history-of-ai-ml-and-dl/)"}
knitr::include_graphics("images/AIHistory1.jpg")
```
<!-- ## Milestones in the history of DL -->
<!-- We can see several hints worth to account for: -->
<!-- - The **Perceptron** and the first **Artificial Neural Network**: the basic building blocks. -->
<!-- - The **Multilayered perceptron** and back-propagation: complex architectures to improve the capabilities. -->
<!-- - **Deep Neural Networks**, with many hidden layers, and auto-tunability capabilities. -->
## From ANN to Deep learning
{fig-align="center" width="100%"}
:::{.font90}
Source: [Alex Amini's MIT Introduction to Deep Learning' course](introtodeeplearning.com)
:::
<!-- ## Success stories -->
<!-- Success stories such as -->
<!-- - the development of self-driving cars, -->
<!-- - the use of AI in medical diagnosis, and -->
<!-- - online shopping personalized recommendations -->
<!-- have also contributed to the widespread adoption of AI. -->
<!-- ## Not to talk abou the fears -->
<!-- :::: {.columns} -->
<!-- ::: {.column width='60%'} -->
<!-- - AI also comes with fears from multiple sources from science fiction to religion -->
<!-- - Mass unemployment -->
<!-- - Loss of privacity -->
<!-- - AI bias -->
<!-- - AI fakes -->
<!-- - Or, simply, AI takeover -->
<!-- ::: -->
<!-- ::: {.column width='40%'} -->
<!-- <br> -->
<!-- ```{r, fig.align='center'} -->
<!-- knitr::include_graphics("images/2.1-Introduction_to_ANN-Slides_insertimage_2.png") -->
<!-- ``` -->
<!-- ::: -->
<!-- :::: -->
## How does it all fit?
```{r, fig.align='center', out.width="100%"}
knitr::include_graphics("images/AI-ML-DL-1new.png")
```
## Size does matter!
{fig-align="center" width="100%"}
<!-- ## The impact of Deep learning {.smaller} -->
<!-- - Near-human-level image classification -->
<!-- - Near-human-level speech transcription -->
<!-- - Near-human-level handwriting transcription -->
<!-- - Dramatically improved machine translation -->
<!-- - Dramatically improved text-to-speech conversion -->
<!-- - Digital assistants such as Google Assistant and Amazon Alexa -->
<!-- - Near-human-level autonomous driving -->
<!-- - Improved ad targeting, as used by Google, Baidu, or Bing -->
<!-- - Improved search results on the web -->
<!-- - Ability to answer natural language questions -->
<!-- - Superhuman Go playing -->
<!-- ## Not all that glitters is gold ... -->
<!-- - According to F. Chollet, the developer of Keras, -->
<!-- - "*we shouldn't believe the short-term hype, but should believe in the long-term vision*. -->
<!-- - *It may take a while for AI to be deployed to its true potential---a potential the full extent of which no one has yet dared to dream* -->
<!-- - *but AI is coming, and it will transform our world in a fantastic way*". -->
# The **A**rtificial **N**eurone
## Emulating biological neurons
:::: {.columns}
::: {.column width='50%'}
```{r, fig.align='center', out.width="100%", fig.cap="[A biological Neuron]()"}
knitr::include_graphics("images/NaturalNeuron.png")
```
:::
::: {.column width='50%'}
```{r, fig.align='center', out.width="100%", fig.cap="[MuCulloch & Pitts proposal]()"}
knitr::include_graphics("images/MacCulloghPitts-Neuron.png")
```
:::
::::
:::{.font70}
- First model of an artifial neurone proposed by Mc Cullough & Pitts in 1943
- They aimed at building a mathematical model of a neurone.
:::
## Mc Cullough's neuron
- The neuron can be divided into two parts:
- $g$: combines the input signals,
- $f$: yields final output from the aggregated value.
- The neuron computes:
$$
y = f(g(x_1,\dots,x_n)).
$$
:::{.font80}
- The neuron first aggregates, $g()$, the inputs, $\mathbb(x)$, and then
- Applies decision rule $f()$ to produce a binary output $y \in \{0,1\}$.
:::
## From the AN to the perceptron
Mc Cullogh's neuron has important limitations:
- Inputs are binary: $x_i \in \{0,1\}$
- All inputs are treated in a fixed way
- The decision rule is rigid (fixed threshold)
To build more flexible the perceptron was introduced.
## The Perceptron
- To overcome Mc Cullogh's neuron limitations Rosenblatt, proposed the perceptron model, or *artificial neuron*, in 1958.
- It generalizes previous one in that *weights and thresholds can be learnt over time*.
- It takes a weighted sum of the inputs and
- It sets the output to 1 if the weighted sum exceeds a threshold $\theta$, and to 0 otherwise.
## Rosenblatt's perceptron
[{width="100%"}](https://towardsdatascience.com/perceptron-the-artificial-neuron-4d8c70d5cc8d)
## Rosenblatt's perceptron
:::{.font80}
- Instead of hand coding the thresholding parameter $\theta$,
- It is added as one of the inputs, with the weight $w_0=-\theta$.
:::
[{width="100%"}](https://towardsdatascience.com/perceptron-the-artificial-neuron-4d8c70d5cc8d)
## Limitations of the perceptron
The perceptron represents an improvement:
- It admits real-valued inputs.
- Both weights and the bias can be learned.
However, it still has important limitations:
- It defines a **linear decision boundary**.
- Therefore, it can only classify **linearly separable data**.
## ANs and Activation Functions
- The Perceptron can be generalized by *Artificial Neurones* which use functions, called *Activation Functions (AFs)* to produce their output.
- AFs are built in a way that they allow neurons to produce *continuous* and *non-linear outputs*.
- It must be noted however that a single AN, even with a different AF, still cannot model non-linear separable problems: *Non-linearity is in the output, no in the input*
## Biological vs Artificial Neurons
- Biological neurons are specialized cells that transmit signals to communicate with each other.
- Neuron's activation is based on releasing *neuro-transmitters*, chemicals that flow between nerve cells.
- When the signal reaching the neuron exceeds a certain threshold, it releases neurotransmitters to continue the communication process.
- Artificial Neurons rely on Activation Functions to emulate the activation process of biological neurons
## Activation function
```{r, fig.align='center', out.width="100%"}
knitr::include_graphics("images/ActivationFunction0.png")
```
## Artificial Neuron
With all these ideas in mind we can now define an Artificial Neuron as a *computational unit* that :
- takes as input $x=(x_0,x_1,x_2,x_3),\ (x_0 = +1 \equiv bias)$,
- outputs $h_{\theta}(x) = f(\theta^\intercal x) = f(\sum_i \theta_ix_i)$,
- where $f:\mathbb{R}\mapsto \mathbb{R}$ is called the **activation function**.
## Activation functions
:::{.font90}
- Goal of activation function is to provide the neuron with *the capability of producing the required outputs*.
- Flexible enough to produce
- Either linear or non-linear transformations.
- Output in the desired range (\[0,1\], {-1,1}, $\mathbb{R}^+$...)
- Usually chosen from a (small) set of possibilities.
- Sigmoid function
- Hyperbolic tangent, or `tanh`, function
- ReLU
:::
## The sigmoid function {.smaller}
::: columns
::: {.column width="50%"}
$$
f(z)=\frac{1}{1+e^{-z}}
$$
- Output real values $\in (0,1)$.
- Natural interpretations as *probability*
```{r, fig.align='center', out.width="100%"}
knitr::include_graphics("images/sigmoidFunction.png")
```
:::
::: {.column width="50%"}
```{r, fig.align='center', out.width="100%"}
knitr::include_graphics("images/sigmoidFunctionDerivative.png")
```
:::
:::
## the hyperbolic tangent {.smaller}
::: columns
::: {.column width="50%"}
Also called `tanh`, function:
$$
f(z)=\frac{e^{z}-e^{-z}}{e^{z}+e^{-z}}
$$
- outputs are zero-centered and bounded in −1,1
- scaled and shifted Sigmoid
- stronger gradient but still has vanishing gradient problem
- Its derivative is $f'(z)=1-(f(z))^2$.
:::
::: {.column width="50%"}
```{r, fig.align='center', out.width="100%"}
knitr::include_graphics("images/TanhFunction.png")
```
:::
:::
## The ReLU {.smaller}
::: columns
::: {.column width="55%"}
- *rectified linear unit*: $f(z)=\max\{0,z\}$.
- Close to a linear: piece-wise *linear* function with two linear pieces.
- Outputs are in $(0,\infty)$ , thus not bounded
- Half rectified: activation threshold at 0
- No vanishing gradient problem
:::
::: {.column width="45%"}
```{r, fig.align='center', out.width="100%"}
knitr::include_graphics("images/ReLUFunction.png")
```
:::
:::
## More activation functions
{width="100%"}.
## Softmax Activation Function {.smaller}
- **Softmax** is an activation function used in the **output layer** of classification models, especially for **multi-class problems**.
- It converts raw scores (logits) into **probabilities**, ensuring that $\sum_{i=1}^{N} P(y_i) = 1$
where $P(y_i)$ is the predicted probability for class $i$.
- Given an input vector $z$, *Softmax* transforms it as:
$$
\sigma(z_i) = \frac{e^{z_i}}{\sum_{j=1}^{N} e^{z_j}}
$$
- The exponentiation **amplifies differences**, making the highest value more dominant.
- The normalization **ensures that probabilities sum to 1**.
<!-- - It is thoroughfully used in classification problems because -->
<!-- - It allows interpreting outputs as **class probabilities**. -->
<!-- - It ensures a **clear decision boundary** between classes. -->
<!-- - It works well for **multi-class classification** problems. -->
## The Artificial Neuron in Short
```{r, fig.align='center', out.width="100%"}
knitr::include_graphics("images/ArtificialNeuron.png")
```
## The Artificial Neuron in Short {.smaller}
- An AN takes a vector of input values $x_{1}, \ldots, x_{d}$ and combines it with some weights that are local to the neuron $\left(w_{0}, w_{1}, . ., w_{d}\right)$ to compute a net input $w_{0}+\sum_{i=1}^{d} w_{i} \cdot x_{i}$.
- To compute its output, it then passes the net input through a possibly non-linear univariate activation function $g(\cdot)$, usually chosen from a set of options such as *Sigmoid*, *Tanh* or *ReLU* functions
- To deal with the *bias*, we create an extra input variable $x_{0}$ with value always equal to 1 , and so the function computed by a single artificial neuron (parameterized by its weights $\mathbf{w}$ ) is:
$$
y(\mathbf{x})=g\left(w_{0}+\sum_{i=1}^{d} w_{i} x_{i}\right)=g\left(\sum_{i=0}^{d} w_{i} x_{i}\right)=g\left(\mathbf{w}^{\mathbf{T}} \mathbf{x}\right)
$$
# From neurons to neural networks
## The basic neural network
::: font90
- Continuing with the brain analogy one can combine (artificial) neurons to create better learners.
- A simple artificial neural network is created by two types of modifications to the basic Artificial Neuron.
- *Stacking several neurons* insteads of just one.
- Adding an additional layer of neurons, which is call a *hidden* layer,
- This yields a system where *the output of a neuron can be the input of another* in many different ways.
:::
## An Artificial Neural network
```{r, fig.align='center', out.width="90%"}
knitr::include_graphics("images/nn.jpg")
```
## The architecture of ANN {.smaller}
In this figure, we have used circles to also denote the inputs to the
network.
- Circles labeled +1 are *bias units*, and correspond to the intercept term.
- The leftmost layer of the network is called the *input layer*.
- The rightmost layer of the network is called the *output* layer.
- The middle layer of nodes is called the *hidden layer*, because its values are not observed in the training set.
Bias nodes are not counted when stating the neuron size.
With all this in mind our example neural network has three layers with:
- 3 input units (not counting the bias unit),
- 3 hidden units,
- 1 output unit.
## How an ANN works
::: font90
An ANN is a predictive model (a *learner*) whose properties and behaviour can be well characterized.
<!-- In practice this means: -->
- It operates through a process known as *forward propagation*, which encompasses the information flow from the input layer to the output layer.
- Forward propagation is performed by composing a series of linear and non-linear (activation) functions.
- These are characterized (parametrized) by their *weights* and *biases*, that need to be *learned from data*.
- This is done by *training the ANN*.
:::
<!-- ## Training the ANN -->
<!-- ::: font80 -->
<!-- - The training process aims at finding *the best possible parameter values* for the learning task defined by the fnctions. This is done by -->
<!-- - Selecting an appropriate (convex) loss function, -->
<!-- - Finding weights that minimize the total *cost* function (avg. loss). -->
<!-- - This is usually done using some iterative optimization procedure such as *gradient descent*. -->
<!-- - This requires evaluating derivatives in a huge number of points. -->
<!-- - Such high number may be reduced by *Stochastic Gradient Descent*. -->
<!-- - The evaluation of derivatives is simplified thanks to *Backpropagation*. -->
<!-- ::: -->
## Forward propagation (1) {.smaller}
The process that encompasses the computations required to go from the input values to the final output is known as *forward propagation*.
For the ANN with 3 input values and 3 neurons in the hidden layer we have:
1. Each node $a_i^{(2)}$ of the hidden layer operates on all input values:
::: font90
\begin{eqnarray}
a_1^{(2)}&=&f(\theta_{10}^{(1)}+\theta_{11}^{(1)}x_1+\theta_{12}^{(1)}x_2+\theta_{13}^{(1)}x_3)\\
a_2^{(2)}&=&f(\theta_{20}^{(1)}+\theta_{21}^{(1)}x_1+\theta_{22}^{(1)}x_2+\theta_{23}^{(1)}x_3)\\
a_3^{(2)}&=&f(\theta_{30}^{(1)}+\theta_{31}^{(1)}x_1+\theta_{32}^{(1)}x_2+\theta_{33}^{(1)}x_3)
\end{eqnarray}
:::
2. Output layer:
$$
h_{\Theta}(x)=a_1^{(3)}=f(\theta_{10}^{(2)}+\theta_{11}^{(2)}a_1^{(2)}+\theta_{12}^{(2)}a_2^{(2)}+\theta_{13}^{(2)}a_3^{(2)})
$$
The terms $\theta_{i0}^{(l)}$ act as bias parameters.
## Forward Propagation (2) {.smaller}
Forward propagation can be written compactly as:
$$
z^{(l+1)} = W^{(l)} a^{(l)} + b^{(l)}
$$
$$
a^{(l+1)} = f(z^{(l+1)})
$$
where:
- $W^{(l)}$ contains the weights,
- $b^{(l)}$ contains the bias terms,
- $f(\cdot)$ is applied elementwise.
- This form is used in most implementations.
## Forward Propagation (3) {.smaller}
An alternative compact notation incorporates the bias into the weight matrix.
:::: columns
::: {.column width="50%"}
**Standard form (explicit bias)**
$$
z^{(l+1)} = W^{(l)} a^{(l)} + b^{(l)}
$$
$$
a^{(l+1)} = f(z^{(l+1)})
$$
- $W^{(l)}$: weights
- $b^{(l)}$: bias
- $f(\cdot)$: elementwise
:::
::: {.column width="50%"}
**Augmented form (bias included)**
$$
z^{(l+1)} = \Theta^{(l)} \tilde{a}^{(l)}
$$
$$
\tilde{a}^{(l)} =
\begin{bmatrix}
1 \\
a^{(l)}
\end{bmatrix}
$$
$$
a^{(l+1)} = f(z^{(l+1)})
$$
- $\Theta^{(l)} = [\, b^{(l)} \;\; W^{(l)} \,]$
:::
::::
## ANNs as Compositions {.smaller}
In short, a neural network defines a parametric function:
$$
\hat{y} = f(x; \theta)
$$
where $f(\cdot)$ is obtained by *composing a sequence of transformations*:
$$
f(x) = f^{(L)} \circ f^{(L-1)} \circ \cdots \circ f^{(1)}(x)
$$
Each layer defines a transformation of the form:
$$
f^{(l)}(a) = f\big(W^{(l)} a + b^{(l)}\big)
$$
so that the activations propagate as:
$$
a^{(l+1)} = f^{(l)}(a^{(l)})
$$
with: $a^{(1)} = x$ (input layer) and $a^{(L)} = \hat{y}$ (output layer).
<!-- - The parameters of the model are:$ -->
<!-- \theta = \{W^{(l)}, b^{(l)}\}_{l=1}^{L} -->
<!-- $ -->
## A simple Neural Network
```{r, fig.cap="[Example from youtube: A simple Neural network in 3 minutes](https://www.youtube.com/watch?v=iyrmwErURJs)", out.width="90%", fig.align='center'}
knitr::include_graphics("images/ANN-Example-1.png")
```
## Feed Forward NNs
- The type of NN described is called feed-forward *neural network (FFNN)*, since
- All computations are done by Forward propagation
- The connectivity graph does not have any directed loops or cycles.
## Eficient Forward propagation
- The way input data is transformed, through a series of weightings and transformations, until the ouput layer is called *forward propagation*.
- By organizing parameters in matrices, and using matrix-vector operations, fast linear algebra routines can be used to perform the required calculations in a fast efficent way.
## Multiple architectures for ANN
- We have so far focused on a single hidden layer neural network of the example.
- One can. however build neural networks with many distinct architectures (meaning patterns of connectivity between neurons),
including ones with multiple hidden layers.
- See [here the Neural Network
Zoo](https://www.asimovinstitute.org/neural-network-zoo/).
# Training Neural Networks
## Training an ANN
An ANN is a predictive model whose properties and behaviour can be mathematically characterized.
- The ANN acts by composing a series of linear and non-linear (activation) functions.
- These transformations are characterized by their weights and biases, which need to be learned from data.
*Training the network* consists in adjusting these parameters so that predictions match -as best as possible- the observed outputs.
## Training an ANN
```{r, fig.align='center'}
knitr::include_graphics("images/ANN-Training.png")
```
::: font80
Source: [Overview of a Neural Network’s Learning Process](https://medium.com/data-science-365/overview-of-a-neural-networks-learning-process-61690a502fa)
:::
## Measuring Prediction Error {.smaller}
- To learn the parameters, we need to measure how good the predictions are.
- For a given observation $(x, y)$, we use a loss function, $\ell(y, \hat{y})$ to compare:
- the true output $y$
- the predicted output $\hat{y} = f(x;\theta)$
- Given a dataset $\{(x_i,y_i)\}_{i=1}^n$, we define the average loss:
$$
J(\theta) = \frac{1}{n} \sum_{i=1}^n \ell(y_i, \hat{y}_i)
$$
- This quantity measures *how well the network fits the data*.
- $J(\theta)$ is called the **cost (or objective)** function.
## Typical Loss Functions {.smaller}
- The choice of loss function depends on the type of problem.
- For *regression problems* a common choice is the **squared error**:
$$
\ell(y, \hat{y}) = (y - \hat{y})^2
$$
- For *classification problems*, we often use loss functions based on probabilities. In particular:
- For binary classification: **cross-entropy**
- multiclass classification: **softmax + cross-entropy**
The loss function should reflect how we measure prediction quality.
## Cross-entropy loss function {.smaller}
- A common loss function to use with ANNs is Cross-entropy defined as:
::: font80
$$
l(h_\theta(x),y)=\big{\{}\begin{array}{ll}
-\log h_\theta(x) & \textrm{if }y=1\\
-\log(1-h_\theta(x))& \textrm{if }y=0
\end{array}
$$
:::
- This function can also be written as:
$$
l(h_\theta(x),y)=-y\log h_\theta(x) - (1-y)\log(1-h_\theta(x))
$$
- Using cross-entropy loss, the cost function is of the form:
::: font80
$$
J(\theta)=-\frac{1}{n}\left[\sum_{i=1}^n (y^{(i)}\log h_\theta(x^{(i)})+ (1-y^{(i)})\log(1-h_\theta(x^{(i)}))\right]
$$
:::
- Now, this is a convex optimization problem.
## A probabilistic interpretation {.smaller}
- In binary classification, the network output can be interpreted as a probability:
$$
\hat{y} \approx P(y = 1 \mid x)
$$
- Under this interpretation, we associate the model:
$$
P(y \mid x) = \hat{y}^y (1 - \hat{y})^{1-y}
$$
- If $y = 1$, the model assigns probability $\hat{y}$
- If $y = 0$, the model assigns probability $1 - \hat{y}$
This probabilistic view is not required, but provides a useful way to motivate the choice of loss function.
## A probabilistic interpretation {.smaller}
- Given a dataset $\{(x_i, y_i)\}_{i=1}^n$, we can measure how well the model fits the data (*how likely is the model given the data*) through the likelihood:
$$
L(\theta) = \prod_{i=1}^n \hat{y}_i^{y_i} (1 - \hat{y}_i)^{1-y_i}
$$
- Maximizing this likelihood is equivalent to minimizing $- \log L(\theta)$, which leads to the cross-entropy loss:
$$
\ell(y, \hat{y}) = -y \log(\hat{y}) - (1 - y)\log(1 - \hat{y})
$$
Which should provide a better intuition for this loss function.
<!-- ## Regularized cross entropy -->
<!-- In practice we often work with a *regularized version* of the cost function (we don't regularize the bias units) -->
<!-- ```{=tex} -->
<!-- \begin{eqnarray*} -->
<!-- J(\Theta)&=&-\frac{1}{n}\big[\sum_{i=1}^n \sum_{k=1}^K y_k^{(i)}\log( h_\theta(x^{(i)}))_k\\ -->
<!-- &+&(1-y_k^{(i)})\log(1-(h_\theta(x^{(i)}))_k)\big]\\ -->
<!-- &+&\lambda\sum_{l=1}^{L-1}\sum_{i=1}^{s_l}\sum_{j=1}^{s_{l+1}} -->
<!-- (\theta_{ji}^{(l)})^2 -->
<!-- \end{eqnarray*} -->
<!-- ``` -->
## From Cost to Optimization {.smaller}
- We have defined a cost function:
$$
J(\theta) = \frac{1}{n} \sum_{i=1}^n \ell(y_i, \hat{y}_i)
$$
which measures how well the network fits the data.
- The parameters of the model are:
$$
\theta = \{W^{(l)}, b^{(l)}\}_{l=1}^{L}
$$
- The key question is: *How should we adjust $\theta$ to reduce $J(\theta)$?*
- *Training a network* consists in finding the parameters (weights and biases) that minimize the cost function $J(\theta)$.
## Gradient of the Cost Function {.smaller}
- The cost function, $J(\theta)$, depends on all model parameters.
- To reduce it, we need to understand how it changes when we modify $\theta$.
- This is reflected by the derivative or gradient of the function.
- The **gradient** of $J$ is a vector of partial derivatives defined as:
$$
\nabla J(\theta) =
\left(
\frac{\partial J}{\partial \theta_1}, \dots, \frac{\partial J}{\partial \theta_p}
\right)
$$
- It indicates how $J(\theta)$ changes with each parameter.
- The gradient vector points in the direction of *steepest increase* so:
- To reduce the cost, we move in the direction of steepest decrease, given by $$-\nabla J(\theta)$$
## Gradient Descent Algorithm {.smaller}
To minimize a cost function $J(\theta)$, we proceeds as follows:
1. **Initialize** $\theta_0$ randomly or with some predetermined values
2. **Repeat until convergence:**
$$
\theta_{t+1} = \theta_{t} - \eta \nabla J(\theta_{t})
$$
3. **Stop when:** $|J(\theta_{t+1}) - J(\theta_{t})| < \epsilon$
- $\theta_0$ is the initial parameter vector,
- $\theta_t$ is the parameter vector at iteration $t$,
- $\eta$ is the learning rate, a step size controlling how large each update is.
- $\nabla J(\theta_{t})$ is the gradient of the loss function with respect to $\theta$ at iteration $t$,
- $\epsilon$ is a small positive value indicating the desired level of convergence.
## Gradient descent Illustration
<!-- ```{r } -->
<!-- if(!require(animation)) install.packages('animation') -->
<!-- library(animation) -->
<!-- ani.options(interval = 0.5, nmax = 10) -->
<!-- xx = grad.desc() -->
<!-- ``` -->
- Gradient descent is an intuitive approach that has been thoroughly illustrated in many different ways:
{fig-align="center" width="100%"}
## Computing Gradients: {.smaller}
- To apply gradient descent, we need to compute $\nabla J(\theta)$.
- The cost depends on the parameters through multiple layers:
$$
x \rightarrow a^{(2)} \rightarrow a^{(3)} \rightarrow \cdots \rightarrow \hat{y}
$$
- Therefore, we must compute derivatives through a composition of functions
- Backpropagation, an algorithm introduced in the 1970s in an MSc thesis applies the chain rule to compute these derivatives efficiently
- In 1986, [Rumelhart, Hinton, and Williams](https://www.nature.com/articles/323533a0) demonstrated that backpropagation significantly improves learning speed.
- This **enabled neural networks to solve previously intractable problems**.
## Backpropagation intuition {.smaller}
- The term originates from error backpropagation.
- An artificial neural network computes outputs through forward propagation:
- Input values pass through linear and non-linear transformations.
- The network produces a prediction.
- The error (difference between predicted and true value) is:
- Propagated backward to compute the error contribution of each neuron.
- Used to adjust weights iteratively.
## Backpropagation Notation {.smaller}
- For each layer, define:
$$
z^{(l)} = W^{(l-1)} a^{(l-1)} + b^{(l-1)}
$$
$$
a^{(l)} = f(z^{(l)})
$$
- Define:
$$
\delta^{(l)} = \frac{\partial J}{\partial z^{(l)}}
$$
- $\delta^{(l)}$ measures how the cost changes with respect to the pre-activation
## Output Layer {.smaller}
- Recall: $\delta^{(L)} = \frac{\partial J}{\partial z^{(L)}}$
- The cost depends on $z^{(L)}$ through the activation $a^{(L)}$
- Applying the chain rule:
$$
\delta^{(L)} =
\frac{\partial J}{\partial a^{(L)}} \odot f'(z^{(L)})
$$
- This term depends on:
- the loss function
- the activation function
## Hidden Layers {.smaller}
- The effect of $z^{(l)}$ on the cost is transmitted through the subsequent layers:
$$
z^{(l)} \rightarrow a^{(l)} \rightarrow z^{(l+1)} \rightarrow J
$$
- Applying the chain rule:
$$
\delta^{(l)} =
(W^{(l)})^T \delta^{(l+1)} \odot f'(z^{(l)})
$$
- The term $(W^{(l)})^T \delta^{(l+1)}$ propagates the effect of the cost backwards
- The term $f'(z^{(l)})$ accounts for the activation function
## Forward vs Backward {.smaller}
- Forward propagation:
- computes values
- propagates activations layer by layer
$$
x \rightarrow a^{(2)} \rightarrow a^{(3)} \rightarrow \cdots \rightarrow \hat{y}
$$