-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathnotes.tex
4088 lines (2966 loc) · 151 KB
/
notes.tex
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
\documentclass[a4, 12pt, english, USenglish]{scrreprt}
% \usepackage{venn}
\usepackage[latin1]{inputenc}
\usepackage{makeidx}
% \usepackage{pdftricks}
\usepackage{graphicx}
% \usepackage[final]{pdfpages}
\usepackage{geometry, upgreek, booktabs, babel}
\usepackage[journal=rsc,xspace=true]{chemstyle}
\usepackage[version=3]{mhchem}
% \usepackage[footnotes]{notes2bib}
\usepackage[final]{microtype}
\usepackage[final, inactive]{pst-pdf}
\usepackage[colorlinks]{hyperref}
% equals with a "set" on top
\newcommand{\defeq}{\ensuremath{\stackrel{\mbox{set}{=}}}}
\renewcommand{\topfraction}{.85}
\renewcommand{\bottomfraction}{.7}
\renewcommand{\textfraction}{.15}
\renewcommand{\floatpagefraction}{.66}
\renewcommand{\dbltopfraction}{.66}
\renewcommand{\dblfloatpagefraction}{.66}
\setcounter{topnumber}{9}
\setcounter{bottomnumber}{9}
\setcounter{totalnumber}{20}
\setcounter{dbltopnumber}{9}
\newcommand{\xscreenshot}[2]{
\begin{figure}[htb]
\begin{center}
\em Missing imagefile file #1
\end{center}
\label{#1}
\caption{#2}
\end{figure}}
\newcommand{\zcreenshot}[3]{
\begin{figure}[htb]
\includegraphics[width=#3]{screenshots/#1.jpg}
\label{#1}
\caption{#2}
\end{figure}}
\newcommand{\screenshot}[2]{
\begin{figure}[htb]
\includegraphics[width=150mm]{screenshots/#1.jpg}
\label{#1}
\caption{#2}
\end{figure}}
\newcommand{\sscreenshot}[3]{
\begin{figure}[htb]
\includegraphics[width=7500mm]{screenshots/#1.jpg}
\label{#2}
\caption{#3}
\end{figure}}
% XXX Should put a little arrow above its parameter.
\newcommand{\vectorXX}[1]{\ensuremath{#1}}
\newcommand{\fApartial}[1]{\ensuremath{\frac{\partial f}{\partial A_{#1}}}}
\newcommand{\jpartial}[1]{\ensuremath{\frac{\partial J}{\partial \theta_{#1}}}}
\newcommand{\thetaipartial}{\ensuremath{\frac{\partial}{\partial{\theta_i}}}}
\newcommand{\thetapartial}{\ensuremath{\frac{\partial}{\partial{\theta}}}}
\newcommand{\half}{\ensuremath{\frac{1}{2}}}
\newcommand{\sumim}{\ensuremath{\sum_{i=1}^{m}}}
\newcommand{\intinf}{\ensuremath{\int_{-\infty}^{\infty}}}
\newcommand{\Ft}{\ensuremath{{\cal{F}}}}
\newcommand{\ft}[1]{\ensuremath{{\cal{F}}({#1})}}
\newcommand{\sinc}[1]{\ensuremath{\mbox{sinc}{#1}}}
\newcommand{\bb}[1]{\ensuremath{{\bf{#1}}}} % XXX Should be blackboard bold
\newcommand{\proj}[2]{\ensuremath{{\bb {#1}}_{#2}}}
\newcommand{\braces}[1]{\ensuremath{\left\{{#1}\right\}}}
\newcommand{\brackets}[1]{\ensuremath{\left[{#1}\right]}}
\newcommand{\parens}[1]{\ensuremath{\left({#1}\right)}}
\newcommand{\absval}[1]{\ensuremath{\left|{#1}\right|}}
\newcommand{\sqbraces}[1]{\ensuremath{\left[{#1}\right]}}
\newcommand{\commutator}[2]{\sqbraces{{#1}, {#2}}}
\newcommand{\dyad}[1]{\ensuremath{\ket{{#1}}\bra{{#1}}}}
\newcommand{\trace}[1]{\ensuremath{\mbox{tr}\, {#1} }}
\newcommand{\erf}[1]{\mbox{erf}\left(#1\right)}
\newcommand{\erfc}[1]{\mbox{erfc}\left(#1\right)}
\newcommand{\mXXX}[1]{\marginpar{\tiny{\bf Rmz:} {\it #1}}}
\newcommand{\celcius}{\ensuremath{^\circ}C}
\newcommand{\ev}[1]{\ensuremath{\left\langle{}#1{}\right\rangle}}
\newcommand{\ket}[1]{\ensuremath{\mid{}#1{}\rangle}}
\newcommand{\bra}[1]{\ensuremath{\langle{}#1{}\mid}}
\newcommand{\braKet}[2]{\ensuremath{\left\langle{}#1{}\mid{#2}\right\rangle}}
\newcommand{\BraKet}[3]{\ensuremath{\left\langle{}#1{}\mid{#2}\mid{#3}\right\rangle}}
\newcommand{\evolvesto}[2]{\ensuremath{{#1}\mapsto{#2}}}
\newcommand{\inrange}[3]{\ensuremath{{#1} \in \braces{{#2}, \ldots,{#3}}}}
\newenvironment{wikipedia}[1]
{
{\bf From wikipedia: {\it #1}}
\begin{quote}
}
{
\end{quote}
}
\newcommand{\idx}[1]{{\em #1}\index{#1}}
\newcommand{\idX}[1]{{#1}\index{#1}}
\usepackage{url}
\newcommand{\tm}{\ensuremath{^{\mbox{tm}}}}
\newcommand{\aangstrom}{\AA{}ngstr\"{o}m{}\ }
%\newcommand{\aaunit}{\mbox{\AA}} % Just use A with ring, once encoding works properly
\newcommand{\aaunit}{\angstrom} % Just use A with ring, once encoding works properly
\newcommand{\munchen}{M\"unchen}
\newcommand{\zurich}{Z\"urich}
\newcommand{\schrodinger}{Schr\"odinger}
\newcommand{\ReneJustHauy}{Ren\'e-Just Ha\"uy}
%% Lavousier (with a lot fo weird spelling)
%% Crystallographic notation
%Coordinate
\newcommand{\crCoord}[3]{\mbox{\(#1,#2,#3\)}}
%Direction
\newcommand{\crDir}[3]{\mbox{\(\left[#1 #2 #3\right]\)}}
%Family of directions
\newcommand{\crDirfam}[3]{\mbox{\(\left<{}#1 #2 #3\right>\)}}
%Plane
\newcommand{\crPlane}[3]{\mbox{\(\left(#1 #2 #3\right)\)}}
%Family of planes
\newcommand{\crPlanefam}[3]{\left\{#1 #2 #3\right\}}
\newcommand{\oneCol}[2]{
\ensuremath{\left(\begin{array}{r}{#1}\\{#2}\end{array}\right)}
}
\newcommand{\twoCol}[4]{
\ensuremath{\left(\begin{array}{rr}{#1}&{#2}\\{#3}&{#4}\end{array}\right)}
}
%Negative number
\newcommand{\crNeg}[1]{\bar{#1}}
\makeindex
\begin{document}
\title{Lecture notes from the \\
online machine learning\\
taught by Andrew Ng \\
fall 2011}
\author{Bj\o{}rn Remseth \\ [email protected]}
\date{Jan. 10 2012 \\ (last revised Feb, 23 2013)}
\maketitle
\tableofcontents
% Comment out this in final version!
% \parskip=\bigskipamount
% \parindent=0pt.
\begin{abstract}
\end{abstract}
\chapter*{Introduction}
These are my notes for the course in machine learning based on Andrew
Ng's lectures, the autumn 2011.
I usually watched the videos while typing notes in \LaTeX. I have
experimented with various note-taking techniques including free text,
mindmaps and handwritten notes, but I've ended up using \LaTeX, since
it's not too hard, it gives great readability for the math that
inevitably pops up in the things I like to take notes about, and it's
easy to include various types of graphics. The graphics in this video
is exclusively screenshots copied directly out of the videos, and to a
large extent, but not completely, the text is based on Ng's
narrative. I haven't been very creative, that wasn't my purpose. I
did take more screenshots than are actually available in this text.
Some of them are indicated in figures stating that a screenshot is
missing. I may or may not get back to putting these missing
screenshots back in, but for now the are just not there. Deal with
it .-)
This document will every now and then be made available on
\url{http://dl.dropbox.com/u/187726/machine-learning-notes.pdf}. The
source code can be cloned on git on \url{https://github.com/la3lma/mlclassnotes}.
A word of warning: These are just my notes. They should't be
interpreted as anything else. I take notes as an aid for myself.
When I take notes I find myself spending more time with the subject at
hand, and that alone lets me remember it better. I can also refer to
the notes, and since I've written them myself, I usually find them
quite useful. I state this clearly since the use of \LaTeX\ will
give some typographical cues that may lead the unwary reader to
believe that this is a textbook or something more ambitious. It's
not. This is a learning tool for me. If anyone else reads this and
find it useful, that's nice. I'm happy, for you, but I didn't have
that, or you in mind when writing this. That said, if you have any
suggestions to make the text or presentation better, please let me
know. My email address is [email protected].
\chapter{Linear regression}
Normal Equation Noninvertability.:
ocateve: pinv(X'*X) * X' * y is the normal equation \(X^TX)^{-1} X' y\) implemented Octaves pseudoinverse function.
If there are linearly depenent features (e.g. feet/meter features, that are linear equtions)
If there are too many features. Could cause noninvertability. Deleting features or using
\idx{regularization} could do the trick.
If X'X singular then look for redundant features, then delete one of them. Otherwise nuke some features or regularization.
\chapter{Octave:}
Prototyping in Octave is very efficient. Only for very large scale
implementations do we need lower leve language implementations.
Programmer time is incredibly valuable so optimizing that is the first
optimization that should always be done.
Prototyping langues: numPy, R, Octave, Matlab, Python. ALl of them slightly clunky than octave.
\begin{verbatim}
Setting the prompt "PS1('>> ')". A==B => a matrix of results of the logical thing.
Printing:
disp(sprintf(' 2 decimals: %0.2f', a))
format long -> print with lots of digits
format short -> print with few digits
v = 1:0.1:2 -> all elements from one to two in steps 0.1 (default stepsize 1)
ones(2,3) -> 2x3 matrix of only ones.
zeros(1,3) -> 1x3 matrix of zeros
rand(3,3) -> 3x3 andom numbers (uniform)
randn(3,3) -> 3x3 random numbers (gaussian distribution)
hist(w) is a histogram function. Really nice.
eye(4) -> 4x4 identity matrix (diagonal)
help(eye)
the "size" command returns a 1x2 matrix that is the size of a matrix.
size(A,1) gives the first element (rows), 2 gives column.
length(A) gives the length of the longest dimension. Usually we use this only for vectors.
pwd shows current directory
cd changes directory
ls lists files on desktop
load('feturesX.dat') loads files with space separated rows and sets a variable from the filename
the "who" command shows which matrics are available.
whos shows the sizes etc. for the variables.
the clear command removes variable.
saving data.
v=priceY(1:10) the first ten elements of priceY.
save hallo.mat v;
saves the variable v into the file hallo.mat
clear without parameters will remove everything.
save hello.txt v --ascii
will save as a text (not binary which is the default)
A(3,2) get the A_3^{(2)} element
A(2,:) gets the second row
A([1 3], :) get everything from the first and third rows.
stopped at 8:30
\end{verbatim}
\chapter{Logistic regression: Classification}
The variable y we want to classify into classes: Spam/not spam.
Fraudulent(not raudulent online transactions. Classifying tumors
malign/benign.
In all these cases \(y \in \braces{0, 1}\). The zero being called the
\idx{negative class} and the one being called the \idx{positive
class}. The assignemtn of the two classes to positive and negative
class is somewhat arbitrary, but the negative is often the absence of
something and the positive presence.
We'll start with a classification problem with only two possible
values, called \idx{two-class} or \idx{binary} classification problem.
Late we'll also look at \idx{multiclass} classification problems.
How do we develop a classification problem. One thing could do is to
use linear regression
\screenshot{linear-regression-classifier}{Linear regression classifier}
and then threshold the hypothesis at some value e.g. 0.5. We then
have a classifier algorithm. In the exmple above this looks
reasonable, but adding an outlier to the right will tilt the
regression line and that makes the prediction very bad as shown in
the example \ref{tilted-regression}.
\screenshot{tilted-regression}{Tilted regression classifier}
Applying linear regression to a classification problem usually isn't a
good example. Also, \(h(x)\) can output values much larger than 1 or
smaller than 0, and that seems ind of weird.
Logistic regression is nicer than that, among other things since \(0
\leq h_\theta \leq 1 \). The term regression in ``logistic
regression''is the name the algorithm was given for historical
reasons, even though it is really a classification algorithm.
The \idx{hypothesis representation} in logistic regression is:
\[
h(x) = g(\theta^T x) = \frac{1}{1 + e^{\theta^T x}}
\]
\(g\) is called the \idx{sigmoid function} or the \idx{logistic
function}, and the latter is what gives logistic regression its name.
The two names are synonyms and can be used interchangably (is that a
word?.
\screenshot{sigmoidfunction}{Sigmoid function}
What we need to do is to fit the parameters to the \(\theta\), and
we'll get an algorithm for this soon enough.
\screenshot{logisticinterpretation}{Interpretation of results from
logistic regression}
\subsection*{Decision boundary}
More Intuition for the hypothesis function for logistic regression (24
secs into the video).
When should we predict one and when should we predict zero? One way
is just to select a threshold.
\zcreenshot{sigmoid-selection-criterion}{Sigmoid selection criterion}{7cm}
In essence, our choice will flip when \(\theta^T \geq 0 \).
We can use this fact to better unnerstand how logistic regression
makes decisions. Assume \(h_\theta(x) = g(\theta_0 + \theta_1 x_1 +
\theta_2 x_2) \). We'll lok at how to fit the parameters later, but
let's just assume that we've done so and have \(\theta =
\braces{-3,1,1}^T\).
The trick is to find the line that most with the smallest wrong
classification (error) divides the classes in the feature plane.
\screenshot{boundaryplot}{The decision boundary for a linear
regression classifier}
The dividing line is called the \idx{decision boundary}. The decision
boundary is the property of the parameters, not the data set. We can
use the data to determine the theta, but after that we don't need the
training set.
\subsection*{Non-linear boundaries}
We can add higher order polynomials to model non-linear features.
\screenshot{circularboundary}{A circular decision boundary}
The boundary is again property of the hypothesis function.
We can use even higher order polynomials. The boundaries can be then
be very complex. Ellipsis, strange shapes. It's a question of
\screenshot{irregularboundary}{An irregular decision boundary}
\subsubsection*{Choosing parametmers to fit the data}
\screenshot{supervised-logistic-regression}{Supervised logistic regression}
The \idx{cost function} defined for the supervised learning problem.
In the linear regression case we used the cost function:
\[
J(\theta) = \frac{1}{m} \sum_{i_1}^m \frac{1}{2} \parens{h_{\theta}(x^{(i)}) - y^{(i)}}^2
\]
We won't use that now. Instead we'll define it as:
\[
J(\theta) = \frac{1}{m} \sum_{i_1}^m \mbox{Cost}\parens{h_{\theta}(x^{(i)}) - y^{(i)}}^2
\]
where
\[
\mbox{Cost}\parens{h_\theta (x^{(i)}), y^{(i)}} = \frac{1}{2} \parens{h_\theta(x^{(i)}) - y^{(i)}}^2
\]
which can be simplified even more:
\[
\mbox{Cost}\parens{h_\theta (x, y)} = \frac{1}{2} \parens{h_\theta(x) - y}^2
\]
It's just the square difference. That worked fine for linear
regressjon, but for logistic regression that isn't so good since it's
a \idx{non-convex} error function. It has many minima and it's hard
to run a gradient descent function on it since it won't find a global minimum
\screenshot{nonconvex}{Convex v.s. non-convex cost functions}
We would like a different, convex, cost function so we can use
gradient descent. One such cost function is:
\[
\mbox{Cost}(h_\theta(x), y)) = \left\{
\begin{array}{rcclcl}
-\log(h_\theta(x)) &\mbox{if} &y&=& 1 \\
-\log(1-h_\theta(x)) &\mbox{if} &y&=& 0 \\
\end{array}\right.
\]
\screenshot{logregcost}{Half the cost function for logistic regression}
\screenshot{logregcost1}{The other half of the cost function for
logistic regression}
Convexity analysis is not within the scope of this course, but convex
cost functions are nice. Next we'll simplify the notation for the
cost function and based on that work out a gradient descent algorithm.
\subsection{Simplified cost function}
The cost function is \[
\mbox{Cost}(h_\theta(x), y)) = \left\{
\begin{array}{rcclcl}
-\log(h_\theta(x)) &\mbox{if} &y&=& 1 \\
-\log(1-h_\theta(x)) &\mbox{if} &y&=& 0 \\
\end{array}\right.
\]
y is either zero or one. Because of this we can simplify the cost
function. In particular we can compress the two lines as
\[
\mbox{Cost}(h_\theta(x), y)) = -y \log(h_\theta(x)) - (1-y) \log(1 - h_\theta(x))
\]
You can prove this by plugging in one for y in the equation above,
that makes the second part disappear. Putting zero in will let the
first term go to zero, and that's the same as the function above.
\screenshot{simplifiedcost}{A simplified cost function for logistic regression}
\newcommand{\ivar}[1]{{#1}^{(i)}}
this gives us the actual cost function:
\[
\begin{array}{lcl}
J(\theta) &=&
\frac{1}{m}\sum_{i=1}^m\mbox{Cost}\parens{h_\theta(x^{(i)}),
y^{(i)}} \\
&=& \frac{1}{m}
%\brackets{
\sum_{i=1}^m \log(h_\theta(\ivar{x}) + (1 -\ivar{y})\log\parens{1 - h_\theta(\ivar{x})}
%}
\end{array}
\]
Now why tis particular function? It's derived from \idx{maximum
likelyhood estimation} which is nice, it's also \idx{convex}.
Given this cost function, what we'll do is:
\[
\mbox{min}_\theta J(\theta)
\]
\screenshot{logisticregcostfunction}{A cust function for logistic
regression that is actually useful for something :-)}
now all we need to do is how to find the thetas. We will use gradient
descent.
The standard template is to use a step within the gradient descent
algorithm:
\[
\theta_j := \theta_j - \alpha\frac{\partial}{\partial\theta_j} J(\theta)
\]
In our case this means that:
\[
\theta_j := \theta_j - \alpha\sum_{i=1}^m \parens{h_\theta(x^{(i)})x_j^{(i)}}
\]
(simultaneously update for all \(\theta_j\). This looks identical to
lienar regression!
\screenshot{graddesclogreg}{Gradient descent with logistic regression}
We can use the same techniques for monitoring to make sure that this
regression is progressing nicely. Slow descent of the error J is what
we are looking for.
we should try to use vectorized implementations if we can.
\screenshot{vecorizedlogisticregression}{A vectorized implementation
of logistic regression}
feature scaling can help both linear regresson and logistic
regression to run faster.
Logistic regression is very powerful and perhaps the most used
classification algorithm in the world and now I know how to work with
it myself :-)
\subsection{Advanced optimization}
With these techniques we'll get logistic regression to have better
performance: Better running times, more features. We have a cost
function, but we need to have code that can produce partial
derivatives
Strictly speaking we don't need the actual J function, but we'll
consider that case anyway since it is very useful for monitoring
progress and convergence.
When we've got code for J and the partials, we can use many algorithms
to compute a minimum:
\begin{itemize}
\item \idx{Gradient descent}
\item \idx{Conjugate gradient}
\item \idx{BFGS}
\item \idx{L-BFGS}
\end{itemize}
The details of these functions are beyond the scope of this voruse.
Don't need to manually pick \(\alpha\).
They have a clever inner loop called a \idx{line search algorithm}
that picks an efficient \(\alpha\) for us. Often faster than
gradient descent, but more complex. In essence, they put a little
regulator on the optimization algorithm to keep it within the sweet
spot. Can choose a different learning rate for each iteration.
Ng used these algorithms for a long while (over a decade), but only
recently did he figure out the details of what they do.
These algorithms are so complex that you probably shouldn't write
these algorithms yourself. Use a library instead. Fortunately octave
has a very good library implementing some of these algorithms, so just
use those libraries and you'll get a decent result.
\subsubsection{An example}
\screenshot{exampleforadvancedoptimization}{An example function for
illustrating how the advanced optimization algorithms can be used}
\screenshot{example2}{example2}
\idx{fminunc} is the octave function for ``function minimization
unconstrained''. initialtheta is the initial guess, and options is a
set of options. the atsign is a pointer in octave syntax.
\screenshot{optimizingfuncparam}{Using the advanced optimization functions}
In logistic regression we use this like this that gives us the cost
function for logistic regression.
\screenshot{logisicregressionfunc}{An implementation of logistic regression}
Using advanced algorithms is a bit more opaque, but for big problems,
they are bettrer for big problems.
\subsection{Logistic regression on multiclass clasification
one-vs-all}
This is about the \idx{one v.s. all algorithm}. Assume we have a mail
classification problem, the classes are work,friends, family hobby.
In a medical system we may diagnose patients not ill, cold flu, or
weather sunny, cloudy, rain, snow.
\screenshot{multiclass-datasets}{A datset containing entries of many classes}
One-vs-al classification works like this: Assume three classes.
Turn it into three binary classification problems. class one v.s. the
rest, class two v.s. the rest and class three v.s. the rest.
\screenshot{one-vs-all-in-action}{Using the ``one v.s. all''
classification method}
for each classifiser we fit a classifier:
\[
h_\theta^{(i)}(x) = P(y=i | x; \theta)\, (i \in \braces{1,2,3}
\]
We estimate ``what is the probability that x is in class i
parameterized by theta''
To make a prediction, we run all the classifiers and select the one
with the highest probability:
\[
\max_i h_\theta^{(i)}(x)
\]
``Pick the classifier with the most enthusiasm :-)''
\chapter{Regularization}
\section{The problem of overfitting}
\screenshot{overfitting}{Ovefitting -- The nemesis of curve fitters}
Linear regression and logistic regression can run into \idx{overfitting}
which. One way of ameliorating the problem is \idx{regularization}.
We'll now look at overfitting and later the fix.
If we get a poorer fit from linear regression, we get a model that is
\idx{underfit} or has \idx{high bias}. The term bias ``bias'' is
historical, an indicates that the model has a strong preconception
that the data will be linear, and despite the data it will still fit
linear data. We can then add more factors
and for instance try using higher order polynomials to match the
data. That will reduce the error to the point that will not have any
error. However the curve will be wiggely, and that curve will be
\idx{overfitted}, or have \idx{high variance}. The term ``high
variance'' is another technical one. The space of possible
hypothesis is just too large, to variant, and we don't have enough
data to give a good hypothesis. In the middle there is the \idx{just
right} case :-) The problem with overfitting is that it gives bad
predictors, even if it gives good fit for the training set. It fails
to generalize.
\screenshot{logisticregressionoverfit}{Overfitting a logistic
regression classifier}
The problem applies both to linear regression and to logistic
regression.
\subsection{Adressing overfitting}
Overfitting can be recognized by tools we'll learn more about later.
However, there are two mi options for adressing the problem.
\begin{enumerate}
\item reduce number of features
\begin{enumerate}
\item Manually select which features to keep.
\item Model selction algorithm (later in the course)
\end{enumerate}
\item Regularization
\begin{enumerate}
\item Keep all the features, but reduce magnitudes/alues of parameters \(\theta_j\)
\item Works well when we have a lot of features, each of which
contributes a little bit to predicting \(y\).
\end{enumerate}
\end{enumerate}
\section{Cost function}
Implementing regularization is a good way to learn regularization.
\screenshot{penlaltyforcost}{How adding a penalty for higher order
terms reduces overfitting}
Add penalty for higher order factors, meaning that they are only
included in the model if they are really worth it. The idea is to
have smal values for parameters in \(\theta\). This gives us
smoother and simpler
hypothesis which are less prone to overfitting.
If we have a bunch of features it is difficult to pick the ones that
are relevant. So what we'll do is to modify the cost function to
penalize all parameters by adding a regularization term:
\[
J(\theta) = \frac{1}{2m} \brackets{\sum_{i=1}^m \parens{h_\theta(x^{(i)}) -
y^{(i)}}^2 + \lambda \sum_{i=1}^n \theta_j^2}
\]
\screenshot{regularizedgradientdescent}{Regularized gradient descent:
Gradient descent with penalty for higher order terms.}
It's convention to not penalize \(\theta_0\). \(\lambda\) is the
\idx{regularization parameter} it regulates the tradeoff between the
two objectives of fitting the data well and keeping the parameters
smal.
A too high value of \(\lambda\) is equivalent to fitting a straight
horizontal line. It will result i severe \idx{underfitting} due to a
too strong bias that the function is straight horizontal line.
\section{Regularized Linear Regression}
We found this error function.
\[
J(\theta) = \frac{1}{2m}
\brackets{\sum_{i=1}^m \parens{h_\theta(x^{(i)}) - y^{(i)}}^2} + \lambda \sum_{i=1}^n \theta_j^2
\]
When using this in gradient descent, we need a new error function and
gradient. The gradient is very similar to the original, but it has an
extra step:
\[
\theta_j := \theta_j - \alpha
\brackets{\sum_{i=1}^m \parens{h_\theta(x^{(i)})x_j^{(i)}} - \frac{\lambda}{m}\theta_j}
\]
Weirdly it's must be true that \(1-\alpha\frac{\lambda}{m}\le 1\)
\screenshot{regularizedgradientdescent}{Gradient descent taking
regularization into account}
By grouping the \(\theta_j\) factors together, we get:
\[
\theta_j := \theta_j (1 - \alpha \frac{\lambda}{m}
\sum_{i=1}^m \parens{h_\theta(x^{(i)})x_j^{(i)}}
\]
We also have the normal equation that can be used to find a
minimization.
\screenshot{normalequationforgradientdescentwithregularization}{The
normal equation for gradient descent with regularization}
\subsubsection{Non invertibility}
\screenshot{noninvertibleregularized}{A noninvertible/singular
covariance matrix in the normal equation}
The regular inverse will fail if you have a noninvertible matrix, so
the pinv method is necessary.
Fortuntately, regularization takes care of that problem too, so we
won't have a degenerate (singular) matrix.
\section{Regularized Logistic Regression}
We have both advanced optimization method and gradient descent, and
we'll now learn how to used these for regularized logistic regression.
Logistic regression is prone to overfitting. All we have to do is to
change the cost function.
\screenshot{regularizedlogisticreg}{Logistic regression with normalization}
How do we implement this? We treat \(\theta_0\) separately, but then
do something very similar to what we did for linear regression.
The update actually is cosmetically identical to the one we use in
linear regression, but it is actually different since the hypothesis
uses the logistic function, not just a linear function of x.
\screenshot{regularizedgraddeslogistic}{Gradient descent for logistic
regression with regularization}
The term in the square bracket is the new partial derivative.
How to implement this using the advanced optimization. First we must
define a cost function
\screenshot{advancedLogisticRegCostFunction}{A cost function to be
used with the advanced optimization algorithms}
If you understand the stuff presented so far, you probably know as
much machine learning as a lot of engineer working in the silicon
valley. Still more to learn though :-) Next up is highly nonlinear
classifiers that we can use.
\chapter{Neural networks representation}
Neural networks are old, were out of favor for a few years, but today
it's the state of the art.
Why? If the decision boundary is highly nonlinear the logistic
regression will be very difficult. For a quadratic features, the
number of features grows quadratically, and that's a lot of
features. It's both computationally expensive and it's prone to
overfitting. Same thing for even higher orders. High orders of
parameters is a pretty normal situation in machine learning.
Computers don't see things s we do, they just se a whole lot of
numbers. Building a car detector for images is hard. Training the
classifier for cars needs a lot of parameters :-)
\screenshot{whyvisionishard}{Why computer vision is hard, the computer
only sees numbers and has to create a concept of whatever it sees
based on these numbers.}
\screenshot{representingcars}{Representing cars}
Quadratic regression over a a pixel can easily have several tens of
million of features that are applicable for logistic regression.
\section{Neuron and the brain}
They are biologically motivated, just to get some idea of what they
can do. Origins in algorithsm to mimic the brain. Widely used in
80s and 90s, popularities diminished in late 90s. Recent resurgence:
Stae of the art tehniuqe for many applications.
The does a lot of amazing things. There is a hypothesis that the
brain uses a single learning algorithm, the \idx{one learning
algorithm hypothesis}. Example, if we route visual nerves to the
auditory cortex, the animal will learn how to see again. The brain
rewires dynamically. \idx{neuro rewiring experiments} indicates that
different parts of the brain can process different types of
information, so perhaps it is reasonable to assume that all the parts
of the brain uses the same learning algorithm, not a raft of
task-specific algorithm.(metin and frost 1989).
\screenshot{brainsensorrepresentations}{The brain is capable of
mapping a wide range of sensor inputs into stuff it can make sense of}
\subsection{Model representation}
\screenshot{neuroninthebrain}{The structure of a single neuron in the brain}
Brains are full of neurons. Neurons have a body and number of input
wires \idx{dendrites}. The output-wire is called \idx{axon}. At a
simplistic level it gets a bun of input from its input and send an
output to the output axon.
\zcreenshot{neuronsindthebrain2}{Artist's representation of a neuron
in a brain}{10cm}
The neurons sends signals called \idx{spikes} to dendrites of other
neurons. This is the process by which all neural computation
happens. This is also the way that IO is done to muscles.
In an artificial neural network we model a neuron as a logistic unit:
\screenshot{logisticunit}{Modelling a single neuron as a ``logistic
unit'' (using the logistic function)}
This is a very (perhaps vastly) simplified version of the network.
Sometimes an extra input \(x_0=1\) is drawn, and sometimes not. It's
called the \idx{bias unit}. The \idx{activation function} is here
the logistic function. In a neural network calls the \(\theta\)
parameters \idx{weights}.
The diagram above represents a single neuron. A network is a group of
neurons thrown together.
\screenshot{neuralnet}{A schematic drawing of a multi-layer neural network.}
The first layer is called the \idx{input layer}, The final layer is
called the \idx{output layer}. The layer(s)in between is called
\idx{hidden layer}(s) (not observable in the training examples).
\screenshot{nnrepresentation}{Representing a neural network as a
matrix of weights}
In the network we call the unit \(a_i^{(j)}\) the \idx{activation} of
unit \(i\) in layer \(j\). The matrix \(\Theta^{(j)}\) are all the
weights controlling the function mapping from layer \(j\) to layer
\(j+1\).
\subsection{A vectorized representation of neural networks}
\xscreenshot{forwardpropagation2}{Propagating values towards the
output using ``forward propagation''}
New notation : \(a^{(2)}_1 = g(z^{(2)}_1) \) refer to items in layer
2 (the hidden layer) of the network.
We can use this to vectorize the operation of the calculation of
neural network values. The activation layer \(a^{(1)}\) is defined to
be the x value (from linear algebra convenson). We add a \(a_0^{(1)}
= 1 \) as an extra bias input. Similarly we add a \(a_0^{(2)}
= 1 \) to the hidden layer, being a bias unit there. To determine the
output value we calculate \(z^{(3)}\).
\mXXX{Why no thresholding?}
\subsection{Intution about what NNs are doing}
\screenshot{coverupNN}{A neural network where a couple of layers has
been covered up}
A covered up neural network (fig \ref{coverupNN}) is essentially
a logistic regression facility. The features that are fed into the
network are the hidden units instead of the (externally input)
features.
The cool thing about this is that the mapping from layer one to layer
two has learned how to recognize features on its own from the input.
And it is these learned features that are then applied to the final
logistic output function. This is a very flexible mapping function
so it can do a lot more than e.g. a polynomial used in a logistic
regression input.
the \idx{architecture of a neural network} describes how the nodes are
connected.
\subsection{Non-linar classification xor/xnor}
\screenshot{xorxnor}{A neural network capable of calculating the
logical function exclusive or/ exclusive nor (XOR/XNOR)}
\screenshot{andnet}{A neural network computing the logical ``and'' of
two parameters.}
Landmark for the sigmoid function: When the x value is 4.6 the y value
is 0.99.
\screenshot{ornet}{A neural network computing the logical ``or''
function of two parameters}
We can also mae a network for ``not''
\screenshot{negation}{A neural network computing a logical negation}
\screenshot{xnornet}{A neural network computing the ``exclusive nor''
(xnor) logical function}