-
Notifications
You must be signed in to change notification settings - Fork 8
/
Rcourse.tex
2641 lines (2032 loc) · 105 KB
/
Rcourse.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
\PassOptionsToPackage{unicode=true}{hyperref} % options for packages loaded elsewhere
\PassOptionsToPackage{hyphens}{url}
%
\documentclass[]{book}
\usepackage{lmodern}
\usepackage{amssymb,amsmath}
\usepackage{ifxetex,ifluatex}
\usepackage{fixltx2e} % provides \textsubscript
\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{textcomp} % provides euro and other symbols
\else % if luatex or xelatex
\usepackage{unicode-math}
\defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase}
\fi
% use upquote if available, for straight quotes in verbatim environments
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
% use microtype if available
\IfFileExists{microtype.sty}{%
\usepackage[]{microtype}
\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
}{}
\IfFileExists{parskip.sty}{%
\usepackage{parskip}
}{% else
\setlength{\parindent}{0pt}
\setlength{\parskip}{6pt plus 2pt minus 1pt}
}
\usepackage{hyperref}
\hypersetup{
pdftitle={R (BGU course)},
pdfauthor={Jonathan D. Rosenblatt},
pdfkeywords={Rstats, Statistics},
pdfborder={0 0 0},
breaklinks=true}
\urlstyle{same} % don't use monospace font for urls
\usepackage{color}
\usepackage{fancyvrb}
\newcommand{\VerbBar}{|}
\newcommand{\VERB}{\Verb[commandchars=\\\{\}]}
\DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\{\}}
% Add ',fontsize=\small' for more characters per line
\usepackage{framed}
\definecolor{shadecolor}{RGB}{248,248,248}
\newenvironment{Shaded}{\begin{snugshade}}{\end{snugshade}}
\newcommand{\AlertTok}[1]{\textcolor[rgb]{0.94,0.16,0.16}{#1}}
\newcommand{\AnnotationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\AttributeTok}[1]{\textcolor[rgb]{0.77,0.63,0.00}{#1}}
\newcommand{\BaseNTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\BuiltInTok}[1]{#1}
\newcommand{\CharTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\CommentTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textit{#1}}}
\newcommand{\CommentVarTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\ConstantTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\ControlFlowTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{\textbf{#1}}}
\newcommand{\DataTypeTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{#1}}
\newcommand{\DecValTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\DocumentationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\ErrorTok}[1]{\textcolor[rgb]{0.64,0.00,0.00}{\textbf{#1}}}
\newcommand{\ExtensionTok}[1]{#1}
\newcommand{\FloatTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\FunctionTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\ImportTok}[1]{#1}
\newcommand{\InformationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{\textbf{#1}}}
\newcommand{\NormalTok}[1]{#1}
\newcommand{\OperatorTok}[1]{\textcolor[rgb]{0.81,0.36,0.00}{\textbf{#1}}}
\newcommand{\OtherTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{#1}}
\newcommand{\PreprocessorTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textit{#1}}}
\newcommand{\RegionMarkerTok}[1]{#1}
\newcommand{\SpecialCharTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\SpecialStringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\StringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\VariableTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\VerbatimStringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\WarningTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\usepackage{longtable,booktabs}
% Fix footnotes in tables (requires footnote package)
\IfFileExists{footnote.sty}{\usepackage{footnote}\makesavenoteenv{longtable}}{}
\usepackage{graphicx,grffile}
\makeatletter
\def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth\else\Gin@nat@width\fi}
\def\maxheight{\ifdim\Gin@nat@height>\textheight\textheight\else\Gin@nat@height\fi}
\makeatother
% Scale images if necessary, so that they will not overflow the page
% margins by default, and it is still possible to overwrite the defaults
% using explicit options in \includegraphics[width, height, ...]{}
\setkeys{Gin}{width=\maxwidth,height=\maxheight,keepaspectratio}
\setlength{\emergencystretch}{3em} % prevent overfull lines
\providecommand{\tightlist}{%
\setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
\setcounter{secnumdepth}{5}
% Redefines (sub)paragraphs to behave more like sections
\ifx\paragraph\undefined\else
\let\oldparagraph\paragraph
\renewcommand{\paragraph}[1]{\oldparagraph{#1}\mbox{}}
\fi
\ifx\subparagraph\undefined\else
\let\oldsubparagraph\subparagraph
\renewcommand{\subparagraph}[1]{\oldsubparagraph{#1}\mbox{}}
\fi
% set default figure placement to htbp
\makeatletter
\def\fps@figure{htbp}
\makeatother
\usepackage{booktabs}
\usepackage{amsthm}
\usepackage[margin=0.7in]{geometry}
\usepackage{fancyhdr}
\pagestyle{fancy}
\makeatletter
\def\thm@space@setup{%
\thm@preskip=8pt plus 2pt minus 4pt
\thm@postskip=\thm@preskip
}
\makeatother
\renewcommand{\href}[2]{#2\footnote{\url{#1}}}
\usepackage[]{natbib}
\bibliographystyle{apalike}
\title{R (BGU course)}
\author{Jonathan D. Rosenblatt}
\date{2020-12-14}
\usepackage{amsthm}
\newtheorem{theorem}{Theorem}[chapter]
\newtheorem{lemma}{Lemma}[chapter]
\newtheorem{corollary}{Corollary}[chapter]
\newtheorem{proposition}{Proposition}[chapter]
\newtheorem{conjecture}{Conjecture}[chapter]
\theoremstyle{definition}
\newtheorem{definition}{Definition}[chapter]
\theoremstyle{definition}
\newtheorem{example}{Example}[chapter]
\theoremstyle{definition}
\newtheorem{exercise}{Exercise}[chapter]
\theoremstyle{remark}
\newtheorem*{remark}{Remark}
\newtheorem*{solution}{Solution}
\let\BeginKnitrBlock\begin \let\EndKnitrBlock\end
\begin{document}
\maketitle
{
\setcounter{tocdepth}{1}
\tableofcontents
}
\hypertarget{preface}{%
\chapter{Preface}\label{preface}}
Placeholder
\hypertarget{notation-conventions}{%
\section{Notation Conventions}\label{notation-conventions}}
\hypertarget{acknowledgements}{%
\section{Acknowledgements}\label{acknowledgements}}
\hypertarget{intro}{%
\chapter{Introduction}\label{intro}}
Placeholder
\hypertarget{what-r}{%
\section{What is R?}\label{what-r}}
\hypertarget{ecosystem}{%
\section{The R Ecosystem}\label{ecosystem}}
\hypertarget{bibliographic-notes}{%
\section{Bibliographic Notes}\label{bibliographic-notes}}
\hypertarget{basics}{%
\chapter{R Basics}\label{basics}}
Placeholder
\hypertarget{other-ides}{%
\subsection{Other IDEs}\label{other-ides}}
\hypertarget{file-types}{%
\section{File types}\label{file-types}}
\hypertarget{simple-calculator}{%
\section{Simple calculator}\label{simple-calculator}}
\hypertarget{probability-calculator}{%
\section{Probability calculator}\label{probability-calculator}}
\hypertarget{getting-help}{%
\section{Getting Help}\label{getting-help}}
\hypertarget{variable-assignment}{%
\section{Variable Assignment}\label{variable-assignment}}
\hypertarget{missing}{%
\section{Missing}\label{missing}}
\hypertarget{piping}{%
\section{Piping}\label{piping}}
\hypertarget{vector-creation-and-manipulation}{%
\section{Vector Creation and Manipulation}\label{vector-creation-and-manipulation}}
\hypertarget{search-paths-and-packages}{%
\section{Search Paths and Packages}\label{search-paths-and-packages}}
\hypertarget{simple-plotting}{%
\section{Simple Plotting}\label{simple-plotting}}
\hypertarget{object-types}{%
\section{Object Types}\label{object-types}}
\hypertarget{data-frames}{%
\section{Data Frames}\label{data-frames}}
\hypertarget{exctraction}{%
\section{Exctraction}\label{exctraction}}
\hypertarget{augmentations-of-the-data.frame-class}{%
\section{Augmentations of the data.frame class}\label{augmentations-of-the-data.frame-class}}
\hypertarget{data-import-and-export}{%
\section{Data Import and Export}\label{data-import-and-export}}
\hypertarget{import-from-web}{%
\subsection{Import from WEB}\label{import-from-web}}
\hypertarget{import-from-clipboard}{%
\subsection{Import From Clipboard}\label{import-from-clipboard}}
\hypertarget{export-as-csv}{%
\subsection{Export as CSV}\label{export-as-csv}}
\hypertarget{export-non-csv-files}{%
\subsection{Export non-CSV files}\label{export-non-csv-files}}
\hypertarget{reading-from-text-files}{%
\subsection{Reading From Text Files}\label{reading-from-text-files}}
\hypertarget{writing-data-to-text-files}{%
\subsection{Writing Data to Text Files}\label{writing-data-to-text-files}}
\hypertarget{xlsx-files}{%
\subsection{.XLS(X) files}\label{xlsx-files}}
\hypertarget{massive-files}{%
\subsection{Massive files}\label{massive-files}}
\hypertarget{databases}{%
\subsection{Databases}\label{databases}}
\hypertarget{functions}{%
\section{Functions}\label{functions}}
\hypertarget{looping}{%
\section{Looping}\label{looping}}
\hypertarget{apply}{%
\section{Apply}\label{apply}}
\hypertarget{recursion}{%
\section{Recursion}\label{recursion}}
\hypertarget{strings}{%
\section{Strings}\label{strings}}
\hypertarget{dates-and-times}{%
\section{Dates and Times}\label{dates-and-times}}
\hypertarget{dates}{%
\subsection{Dates}\label{dates}}
\hypertarget{times}{%
\subsection{Times}\label{times}}
\hypertarget{lubridate-package}{%
\subsection{lubridate Package}\label{lubridate-package}}
\hypertarget{complex-objects}{%
\section{Complex Objects}\label{complex-objects}}
\hypertarget{vectors-and-matrix-products}{%
\section{Vectors and Matrix Products}\label{vectors-and-matrix-products}}
\hypertarget{rstudio-projects}{%
\section{RStudio Projects}\label{rstudio-projects}}
\hypertarget{bibliographic-notes-1}{%
\section{Bibliographic Notes}\label{bibliographic-notes-1}}
\hypertarget{practice-yourself}{%
\section{Practice Yourself}\label{practice-yourself}}
\hypertarget{datatable}{%
\chapter{data.table}\label{datatable}}
Placeholder
\hypertarget{make-your-own-variables}{%
\section{Make your own variables}\label{make-your-own-variables}}
\hypertarget{join}{%
\section{Join}\label{join}}
\hypertarget{reshaping-data}{%
\section{Reshaping data}\label{reshaping-data}}
\hypertarget{wide-to-long}{%
\subsection{Wide to long}\label{wide-to-long}}
\hypertarget{long-to-wide}{%
\subsection{Long to wide}\label{long-to-wide}}
\hypertarget{bibliographic-notes-2}{%
\section{Bibliographic Notes}\label{bibliographic-notes-2}}
\hypertarget{practice-yourself-1}{%
\section{Practice Yourself}\label{practice-yourself-1}}
\hypertarget{eda}{%
\chapter{Exploratory Data Analysis}\label{eda}}
Placeholder
\hypertarget{summary-statistics}{%
\section{Summary Statistics}\label{summary-statistics}}
\hypertarget{categorical-data}{%
\subsection{Categorical Data}\label{categorical-data}}
\hypertarget{summary-of-univariate-categorical-data}{%
\subsubsection{Summary of Univariate Categorical Data}\label{summary-of-univariate-categorical-data}}
\hypertarget{summary-of-bivariate-categorical-data}{%
\subsubsection{Summary of Bivariate Categorical Data}\label{summary-of-bivariate-categorical-data}}
\hypertarget{summary-of-multivariate-categorical-data}{%
\subsubsection{Summary of Multivariate Categorical Data}\label{summary-of-multivariate-categorical-data}}
\hypertarget{continous-data}{%
\subsection{Continous Data}\label{continous-data}}
\hypertarget{summary-of-univariate-continuous-data}{%
\subsubsection{Summary of Univariate Continuous Data}\label{summary-of-univariate-continuous-data}}
\hypertarget{summary-of-location}{%
\subsubsection{Summary of Location}\label{summary-of-location}}
\hypertarget{summary-of-scale}{%
\subsubsection{Summary of Scale}\label{summary-of-scale}}
\hypertarget{summary-of-asymmetry}{%
\subsubsection{Summary of Asymmetry}\label{summary-of-asymmetry}}
\hypertarget{summary-of-bivariate-continuous-data}{%
\subsubsection{Summary of Bivariate Continuous Data}\label{summary-of-bivariate-continuous-data}}
\hypertarget{summary-of-multivariate-continuous-data}{%
\subsubsection{Summary of Multivariate Continuous Data}\label{summary-of-multivariate-continuous-data}}
\hypertarget{visualization}{%
\section{Visualization}\label{visualization}}
\hypertarget{categorical-data-1}{%
\subsection{Categorical Data}\label{categorical-data-1}}
\hypertarget{visualizing-univariate-categorical-data}{%
\subsubsection{Visualizing Univariate Categorical Data}\label{visualizing-univariate-categorical-data}}
\hypertarget{visualizing-bivariate-categorical-data}{%
\subsubsection{Visualizing Bivariate Categorical Data}\label{visualizing-bivariate-categorical-data}}
\hypertarget{visualizing-multivariate-categorical-data}{%
\subsubsection{Visualizing Multivariate Categorical Data}\label{visualizing-multivariate-categorical-data}}
\hypertarget{continuous-data}{%
\subsection{Continuous Data}\label{continuous-data}}
\hypertarget{visualizing-univariate-continuous-data}{%
\subsubsection{Visualizing Univariate Continuous Data}\label{visualizing-univariate-continuous-data}}
\hypertarget{visualizing-bivariate-continuous-data}{%
\subsubsection{Visualizing Bivariate Continuous Data}\label{visualizing-bivariate-continuous-data}}
\hypertarget{visualizing-multivariate-continuous-data}{%
\subsubsection{Visualizing Multivariate Continuous Data}\label{visualizing-multivariate-continuous-data}}
\hypertarget{parcoord}{%
\subsubsection{Parallel Coordinate Plots}\label{parcoord}}
\hypertarget{candlestick-chart}{%
\subsubsection{Candlestick Chart}\label{candlestick-chart}}
\hypertarget{mixed-type-data}{%
\section{Mixed Type Data}\label{mixed-type-data}}
\hypertarget{alluvial}{%
\subsection{Alluvial Diagram}\label{alluvial}}
\hypertarget{bibliographic-notes-3}{%
\section{Bibliographic Notes}\label{bibliographic-notes-3}}
\hypertarget{practice-yourself-2}{%
\section{Practice Yourself}\label{practice-yourself-2}}
\hypertarget{lm}{%
\chapter{Linear Models}\label{lm}}
Placeholder
\hypertarget{problem-setup}{%
\section{Problem Setup}\label{problem-setup}}
\hypertarget{ols-estimation-in-r}{%
\section{OLS Estimation in R}\label{ols-estimation-in-r}}
\hypertarget{inference}{%
\section{Inference}\label{inference}}
\hypertarget{testing-a-hypothesis-on-a-single-coefficient}{%
\subsection{Testing a Hypothesis on a Single Coefficient}\label{testing-a-hypothesis-on-a-single-coefficient}}
\hypertarget{constructing-a-confidence-interval-on-a-single-coefficient}{%
\subsection{Constructing a Confidence Interval on a Single Coefficient}\label{constructing-a-confidence-interval-on-a-single-coefficient}}
\hypertarget{multiple-regression}{%
\subsection{Multiple Regression}\label{multiple-regression}}
\hypertarget{anova-testing-a-hypothesis-on-a-single-contrast}{%
\subsection{\texorpdfstring{ANOVA (\emph{)
\#\#\# Testing a Hypothesis on a Single Contrast (})}{ANOVA () \#\#\# Testing a Hypothesis on a Single Contrast ()}}\label{anova-testing-a-hypothesis-on-a-single-contrast}}
\hypertarget{extra-diagnostics}{%
\section{Extra Diagnostics}\label{extra-diagnostics}}
\hypertarget{diagnosing-heteroskedasticity}{%
\subsection{Diagnosing Heteroskedasticity}\label{diagnosing-heteroskedasticity}}
\hypertarget{diagnosing-multicolinearity}{%
\subsection{Diagnosing Multicolinearity}\label{diagnosing-multicolinearity}}
\hypertarget{how-does-r-encode-factor-variables}{%
\section{How Does R Encode Factor Variables?}\label{how-does-r-encode-factor-variables}}
\hypertarget{bibliographic-notes-4}{%
\section{Bibliographic Notes}\label{bibliographic-notes-4}}
\hypertarget{practice-yourself-3}{%
\section{Practice Yourself}\label{practice-yourself-3}}
\hypertarget{glm}{%
\chapter{Generalized Linear Models}\label{glm}}
Placeholder
\hypertarget{problem-setup-1}{%
\section{Problem Setup}\label{problem-setup-1}}
\hypertarget{logistic-regression}{%
\section{Logistic Regression}\label{logistic-regression}}
\hypertarget{logistic-regression-with-r}{%
\subsection{Logistic Regression with R}\label{logistic-regression-with-r}}
\hypertarget{poisson-regression}{%
\section{Poisson Regression}\label{poisson-regression}}
\hypertarget{extensions}{%
\section{Extensions}\label{extensions}}
\hypertarget{bibliographic-notes-5}{%
\section{Bibliographic Notes}\label{bibliographic-notes-5}}
\hypertarget{practice-glm}{%
\section{Practice Yourself}\label{practice-glm}}
\hypertarget{lme}{%
\chapter{Linear Mixed Models}\label{lme}}
Placeholder
\hypertarget{problem-setup-2}{%
\section{Problem Setup}\label{problem-setup-2}}
\hypertarget{non-linear-mixed-models}{%
\subsection{Non-Linear Mixed Models}\label{non-linear-mixed-models}}
\hypertarget{generalized-linear-mixed-models-glmm}{%
\subsection{Generalized Linear Mixed Models (GLMM)}\label{generalized-linear-mixed-models-glmm}}
\hypertarget{lmms-in-r}{%
\section{LMMs in R}\label{lmms-in-r}}
\hypertarget{relation-to-paired-t-test}{%
\subsubsection{Relation to Paired t-test}\label{relation-to-paired-t-test}}
\hypertarget{a-single-random-effect}{%
\subsection{A Single Random Effect}\label{a-single-random-effect}}
\hypertarget{a-full-mixed-model}{%
\subsection{A Full Mixed-Model}\label{a-full-mixed-model}}
\hypertarget{sparsity-and-memory-efficiency}{%
\subsection{Sparsity and Memory Efficiency}\label{sparsity-and-memory-efficiency}}
\hypertarget{serial}{%
\section{Serial Correlations in Space/Time}\label{serial}}
\hypertarget{extensions-1}{%
\section{Extensions}\label{extensions-1}}
\hypertarget{cr-se}{%
\subsection{Cluster Robust Standard Errors}\label{cr-se}}
\hypertarget{linear-models-for-panel-data}{%
\subsection{Linear Models for Panel Data}\label{linear-models-for-panel-data}}
\hypertarget{testing-hypotheses-on-correlations}{%
\subsection{Testing Hypotheses on Correlations}\label{testing-hypotheses-on-correlations}}
\hypertarget{bibliographic-notes-6}{%
\section{Bibliographic Notes}\label{bibliographic-notes-6}}
\hypertarget{practice-yourself-4}{%
\section{Practice Yourself}\label{practice-yourself-4}}
\hypertarget{multivariate}{%
\chapter{Multivariate Data Analysis}\label{multivariate}}
Placeholder
\hypertarget{signal-detection}{%
\section{Signal Detection}\label{signal-detection}}
\hypertarget{hotellings-t2-test}{%
\subsection{Hotelling's T2 Test}\label{hotellings-t2-test}}
\hypertarget{various-types-of-signal-to-detect}{%
\subsection{Various Types of Signal to Detect}\label{various-types-of-signal-to-detect}}
\hypertarget{simes-test}{%
\subsection{Simes' Test}\label{simes-test}}
\hypertarget{signal-detection-with-r}{%
\subsection{Signal Detection with R}\label{signal-detection-with-r}}
\hypertarget{signal-counting}{%
\section{Signal Counting}\label{signal-counting}}
\hypertarget{identification}{%
\section{Signal Identification}\label{identification}}
\hypertarget{signal-identification-in-r}{%
\subsection{Signal Identification in R}\label{signal-identification-in-r}}
\hypertarget{signal-estimation-bibliographic-notes-practice-yourself}{%
\section{\texorpdfstring{Signal Estimation (*)
\#\# Bibliographic Notes
\#\# Practice Yourself}{Signal Estimation (*) \#\# Bibliographic Notes \#\# Practice Yourself}}\label{signal-estimation-bibliographic-notes-practice-yourself}}
\hypertarget{supervised}{%
\chapter{Supervised Learning}\label{supervised}}
Machine learning is very similar to statistics, but it is certainly not the same.
As the name suggests, in machine learning we want machines to learn.
This means that we want to replace hard-coded expert algorithm, with data-driven self-learned algorithm.
There are many learning setups, that depend on what information is available to the machine.
The most common setup, discussed in this chapter, is \emph{supervised learning}.
The name takes from the fact that by giving the machine data samples with known inputs (a.k.a. features) and desired outputs (a.k.a. labels), the human is effectively supervising the learning.
If we think of the inputs as predictors, and outcomes as predicted, it is no wonder that supervised learning is very similar to statistical prediction.
When asked ``are these the same?'' I like to give the example of internet fraud.
If you take a sample of fraud ``attacks'', a statistical formulation of the problem is highly unlikely.
This is because fraud events are not randomly drawn from some distribution, but rather, arrive from an adversary learning the defenses and adapting to it.
This instance of supervised learning is more similar to game theory than statistics.
Other types of machine learning problems include \citep{sammut2011encyclopedia}:
\begin{itemize}
\item
\textbf{Unsupervised Learning}:
Where we merely analyze the inputs/features, but no desirable outcome is available to the learning machine.
See Chapter \ref{unsupervised}.
\item
\textbf{Semi Supervised Learning}:
Where only part of the samples are labeled.
A.k.a. \emph{co-training}, \emph{learning from labeled and unlabeled data}, \emph{transductive learning}.
\item
\textbf{Active Learning}:
Where the machine is allowed to query the user for labels. Very similar to \emph{adaptive design of experiments}.
\item
\textbf{Learning on a Budget}:
A version of active learning where querying for labels induces variable costs.
\item
\textbf{Weak Learning}:
A version of supervised learning where the labels are given not by an expert, but rather by some heuristic rule.
Example: mass-labeling cyber attacks by a rule based software, instead of a manual inspection.
\item
\textbf{Reinforcement Learning}:\\
Similar to active learning, in that the machine may query for labels.
Different from active learning, in that the machine does not receive labels, but \emph{rewards}.
\item
\textbf{Structure Learning}:
An instance of supervised learning where we predict objects with structure such as dependent vectors, graphs, images, tensors, etc.
\item
\textbf{Online Learning}:
An instance of supervised learning, where we need to make predictions where data inputs as a stream.
\item
\textbf{Transduction}:
An instance of supervised learning where we need to make predictions for a new set of predictors, but which are known at the time of learning.
Can be thought of as semi-supervised \emph{extrapolation}.
\item
\textbf{Covariate shift}:
An instance of supervised learning where we need to make predictions for a set of predictors that ha a different distribution than the data generating source.
\item
\textbf{Targeted Learning}:
A form of supervised learning, designed at causal inference for decision making.
\item
\textbf{Co-training}:
An instance of supervised learning where we solve several problems, and exploit some assumed relation between the problems.
\item
\textbf{Manifold learning}: An instance of unsupervised learning, where the goal is to reduce the dimension of the data by embedding it into a lower dimensional manifold.
A.k.a. \emph{support estimation}.
\item
\textbf{Similarity Learning}: Where we try to learn how to measure similarity between objects (like faces, texts, images, etc.).
\item
\textbf{Metric Learning}: Like \emph{similarity learning}, only that the similarity has to obey the definition of a \emph{metric}.
\item
\textbf{Learning to learn}:
Deals with the carriage of ``experience'' from one learning problem to another.
A.k.a. \emph{cummulative learning}, \emph{knowledge transfer}, and \emph{meta learning}.
\end{itemize}
For a list of ``14 types of machine learning'' see \href{https://machinelearningmastery.com/types-of-learning-in-machine-learning/}{here}.
\hypertarget{problem-setup-3}{%
\section{Problem Setup}\label{problem-setup-3}}
We now present the \emph{empirical risk minimization} (ERM) approach to supervised learning, a.k.a. \emph{M-estimation} in the statistical literature.
\BeginKnitrBlock{remark}
\iffalse{} {Remark. } \fi{}We do not discuss purely algorithmic approaches such as K-nearest neighbour and \emph{kernel smoothing} due to space constraints.
For a broader review of supervised learning, see the Bibliographic Notes.
\EndKnitrBlock{remark}
\BeginKnitrBlock{example}[Rental Prices]
\protect\hypertarget{exm:rental-prices}{}{\label{exm:rental-prices} \iffalse (Rental Prices) \fi{} }Consider the problem of predicting if a mail is spam or not based on its attributes: length, number of exclamation marks, number of recipients, etc.
\EndKnitrBlock{example}
Given \(n\) samples with inputs \(x\) from some space \(\mathcal{X}\) and desired outcome, \(y\), from some space \(\mathcal{Y}\).
In our example, \(y\) is the spam/no-spam label, and \(x\) is a vector of the mail's attributes.
Samples, \((x,y)\) have some distribution we denote \(P\).
We want to learn a function that maps inputs to outputs, i.e., that classifies to spam given. This function is called a \emph{hypothesis}, or \emph{predictor}, denoted \(f\), that belongs to a hypothesis class \(\mathcal{F}\) such that \(f:\mathcal{X} \to \mathcal{Y}\).
We also choose some other function that fines us for erroneous prediction.
This function is called the \emph{loss}, and we denote it by \(l:\mathcal{Y}\times \mathcal{Y} \to \mathbb{R}^+\).
\BeginKnitrBlock{remark}
\iffalse{} {Remark. } \fi{}The \emph{hypothesis} in machine learning is only vaguely related the \emph{hypothesis} in statistical testing, which is quite confusing.
\EndKnitrBlock{remark}
\BeginKnitrBlock{remark}
\iffalse{} {Remark. } \fi{}The \emph{hypothesis} in machine learning is not a bona-fide \emph{statistical model} since we don't assume it is the data generating process, but rather some function which we choose for its good predictive performance.
\EndKnitrBlock{remark}
The fundamental task in supervised (statistical) learning is to recover a hypothesis that minimizes the average loss in the sample, and not in the population.
This is know as the \emph{risk minimization problem}.
\BeginKnitrBlock{definition}[Risk Function]
\protect\hypertarget{def:unnamed-chunk-4}{}{\label{def:unnamed-chunk-4} \iffalse (Risk Function) \fi{} }The \emph{risk function}, a.k.a. \emph{generalization error}, or \emph{test error}, is the population average loss of a predictor \(f\):
\begin{align}
R(f):=\mathbb{E}_P[l(f(x),y)].
\end{align}
\EndKnitrBlock{definition}
The best predictor, is the risk minimizer:
\begin{align}
f^* := argmin_f \{R(f)\}.
\label{eq:risk}
\end{align}
Another fundamental problem is that we do not know the distribution of all possible inputs and outputs, \(P\).
We typically only have a sample of \((x_i,y_i), i=1,\dots,n\).
We thus state the \emph{empirical} counterpart of \eqref{eq:risk}, which consists of minimizing the average loss.
This is known as the \emph{empirical risk miminization} problem (ERM).
\BeginKnitrBlock{definition}[Empirical Risk]
\protect\hypertarget{def:unnamed-chunk-5}{}{\label{def:unnamed-chunk-5} \iffalse (Empirical Risk) \fi{} }The \emph{empirical risk function}, a.k.a. \emph{in-sample error}, or \emph{train error}, is the sample average loss of a predictor \(f\):
\begin{align}
R_n(f):= 1/n \sum_i l(f(x_i),y_i).
\end{align}
\EndKnitrBlock{definition}
A good candidate proxy for \(f^*\) is its empirical counterpart, \(\hat f\), known as the \emph{empirical risk minimizer}:
\begin{align}
\hat f := argmin_f \{ R_n(f) \}.
\label{eq:erm}
\end{align}
To make things more explicit:
\begin{itemize}
\tightlist
\item
\(f\) may be a linear function of the attributes, so that it may be indexed simply with its coefficient vector \(\beta\).
\item
\(l\) may be a squared error loss: \(l(f(x),y):=(f(x)-y)^2\).
\end{itemize}
Under these conditions, the best predictor \(f^* \in \mathcal{F}\) from problem \eqref{eq:risk} is to
\begin{align}
f^* := argmin_\beta \{ \mathbb{E}_{P(x,y)}[(x'\beta-y)^2] \}.
\end{align}
When using a linear hypothesis with squared loss, we see that the empirical risk minimization problem collapses to an ordinary least-squares problem:
\begin{align}
\hat f := argmin_\beta \{1/n \sum_i (x_i'\beta - y_i)^2 \}.
\end{align}
When data samples are assumingly independent, then maximum likelihood estimation is also an instance of ERM, when using the (negative) log likelihood as the loss function.
If we don't assume any structure on the hypothesis, \(f\), then \(\hat f\) from \eqref{eq:erm} will interpolate the data, and \(\hat f\) will be a very bad predictor.
We say, it will \emph{overfit} the observed data, and will have bad performance on new data.
We have several ways to avoid overfitting:
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\tightlist
\item
Restrict the hypothesis class \(\mathcal{F}\) (such as linear functions).
\item
Penalize for the complexity of \(f\). The penalty denoted by \(\Vert f \Vert\).
\item
Unbiased risk estimation:
\(R_n(f)\) is not an unbiased estimator of \(R(f)\).
Why? Think of estimating the mean with the sample minimum\ldots{}
Because \(R_n(f)\) is downward biased, we may add some correction term, or compute \(R_n(f)\) on different data than the one used to recover \(\hat f\).
\end{enumerate}
Almost all ERM algorithms consist of some combination of all the three methods above.
\hypertarget{common-hypothesis-classes}{%
\subsection{Common Hypothesis Classes}\label{common-hypothesis-classes}}
Some common hypothesis classes, \(\mathcal{F}\), with restricted complexity, are:
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\item
\textbf{Linear hypotheses}: such as linear models, GLMs, and (linear) support vector machines (SVM).
\item
\textbf{Neural networks}: a.k.a. \emph{feed-forward} neural nets, \emph{artificial} neural nets, and the celebrated class of \emph{deep} neural nets.
\item
\textbf{Tree}: a.k.a. \emph{decision rules}, is a class of hypotheses which can be stated as ``if-then'' rules.
\item
\textbf{Reproducing Kernel Hilbert Space}: a.k.a. RKHS, is a subset of ``the space of all functions\footnote{It is even a subset of the Hilbert space, itself a subset of the space of all functions.}'' that is both large enough to capture very complicated relations, but small enough so that it is less prone to overfitting, and also surprisingly simple to compute with.
\end{enumerate}
\hypertarget{common-complexity-penalties}{%
\subsection{Common Complexity Penalties}\label{common-complexity-penalties}}
The most common complexity penalty applies to classes that have a finite dimensional parametric representation, such as the class of linear predictors, parametrized via its coefficients \(\beta\).
In such classes we may penalize for the norm of the parameters.
Common penalties include:
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\tightlist
\item
\textbf{Ridge penalty}: penalizing the \(l_2\) norm of the parameter. I.e. \(\Vert f \Vert=\Vert \beta \Vert_2^2=\sum_j \beta_j^2\).
\item
\textbf{LASSO penalty}: penalizing the \(l_1\) norm of the parameter. I.e., \(\Vert f \Vert=\Vert \beta \Vert_1=\sum_j |\beta_j|\). Also known as \textbf{Basis Pursuit}, in signal processing.
\item
\textbf{Elastic net}: a combination of the lasso and ridge penalty. I.e. ,\(\Vert f \Vert= \alpha \Vert \beta \Vert_2^2 + (1-\alpha) \Vert \beta \Vert_1\).
\item
\textbf{Function Norms}: If the hypothesis class \(\mathcal{F}\) does not admit a finite dimensional representation, the penalty is no longer a function of the parameters of the function. We may, however, penalize not the parametric representation of the function, but rather the function itself \(\Vert f \Vert=\sqrt{\int f(t)^2 dt}\).
\end{enumerate}
\hypertarget{unbiased-risk-estimation}{%
\subsection{Unbiased Risk Estimation}\label{unbiased-risk-estimation}}
The fundamental problem of overfitting, is that the empirical risk, \(R_n(\hat f)\), is downward biased to the population risk, \(R(\hat f)\).
We can remove this bias in two ways:
(a) purely algorithmic \emph{resampling} approaches, and (b) theory driven estimators.
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\item
\textbf{Train-Validate-Test}:
The simplest form of algorithmic validation is to split the data.
A \emph{train} set to train/estimate/learn \(\hat f\).
A \emph{validation} set to compute the out-of-sample expected loss, \(R(\hat f)\), and pick the best performing predictor.
A \emph{test} sample to compute the out-of-sample performance of the selected hypothesis.
This is a very simple approach, but it is very ``data inefficient'', thus motivating the next method.
\item
\textbf{V-Fold Cross Validation}:
By far the most popular algorithmic unbiased risk estimator; in \emph{V-fold CV} we ``fold'' the data into \(V\) non-overlapping sets.
For each of the \(V\) sets, we learn \(\hat f\) with the non-selected fold, and assess \(R(\hat f)\)) on the selected fold.
We then aggregate results over the \(V\) folds, typically by averaging.
\item
\textbf{AIC}:
Akaike's information criterion (AIC) is a theory driven correction of the empirical risk, so that it is unbiased to the true risk.
It is appropriate when using the likelihood loss.
\item
\textbf{Cp}:
Mallow's Cp is an instance of AIC for likelihood loss under normal noise.
\end{enumerate}
Other theory driven unbiased risk estimators include the \emph{Bayesian Information Criterion} (BIC, aka SBC, aka SBIC), the \emph{Minimum Description Length} (MDL), \emph{Vapnic's Structural Risk Minimization} (SRM), the \emph{Deviance Information Criterion} (DIC), and the \emph{Hannan-Quinn Information Criterion} (HQC).
Other resampling based unbiased risk estimators include resampling \textbf{without replacement} algorithms like \emph{delete-d cross validation} with its many variations, and \textbf{resampling with replacement}, like the \emph{bootstrap}, with its many variations.
\hypertarget{collecting-the-pieces}{%
\subsection{Collecting the Pieces}\label{collecting-the-pieces}}
An ERM problem with regularization will look like
\begin{align}
\hat f := argmin_{f \in \mathcal{F}} \{ R_n(f) + \lambda \Vert f \Vert \}.
\label{eq:erm-regularized}
\end{align}
Collecting ideas from the above sections, a typical supervised learning pipeline will include: choosing the hypothesis class, choosing the penalty function and level, unbiased risk estimator.
We emphasize that choosing the penalty function, \(\Vert f \Vert\) is not enough, and we need to choose how ``hard'' to apply it.
This if known as the \emph{regularization level}, denoted by \(\lambda\) in Eq.\eqref{eq:erm-regularized}.
Examples of such combos include:
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\tightlist
\item
Linear regression, no penalty, train-validate test.
\item
Linear regression, no penalty, AIC.
\item
Linear regression, \(l_2\) penalty, V-fold CV. This combo is typically known as \emph{ridge regression}.
\item
Linear regression, \(l_1\) penalty, V-fold CV. This combo is typically known as \emph{LASSO regression}.
\item
Linear regression, \(l_1\) and \(l_2\) penalty, V-fold CV. This combo is typically known as \emph{elastic net regression}.
\item
Logistic regression, \(l_2\) penalty, V-fold CV.
\item
SVM classification, \(l_2\) penalty, V-fold CV.
\item
Deep network, no penalty, V-fold CV.
\item
Unrestricted, \(\Vert \partial^2 f \Vert_2\), V-fold CV. This combo is typically known as a \emph{smoothing spline}.
\end{enumerate}
For fans of statistical hypothesis testing we will also emphasize:
Testing and prediction are related, but are not the same:
\begin{itemize}
\tightlist
\item
In the current chapter, we do not claim our models, \(f\), are generative. I.e., we do not claim that there is some causal relation between \(x\) and \(y\). We only claim that \(x\) predicts \(y\).
\item
It is possible that we will want to ignore a significant predictor, and add a non-significant one \citep{foster2004variable}.
\item
Some authors will use hypothesis testing as an initial screening for candidate predictors.
This is a useful heuristic, but that is all it is-- a heuristic. It may also fail miserably if predictors are linearly dependent (a.k.a. multicollinear).
\end{itemize}
\hypertarget{supervised-learning-in-r}{%
\section{Supervised Learning in R}\label{supervised-learning-in-r}}
At this point, we have a rich enough language to do supervised learning with R.
In these examples, I will use two data sets from the \textbf{ElemStatLearn} package, that accompanies the seminal book by \citet{friedman2001elements}.
I use the \texttt{spam} data for categorical predictions, and \texttt{prostate} for continuous predictions.
In \texttt{spam} we will try to decide if a mail is spam or not.
In \texttt{prostate} we will try to predict the size of a cancerous tumor.
You can now call \texttt{?prostate} and \texttt{?spam} to learn more about these data sets.
Some boring pre-processing.
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{# Preparing prostate data}
\KeywordTok{data}\NormalTok{(}\StringTok{"prostate"}\NormalTok{, }\DataTypeTok{package =} \StringTok{'ElemStatLearn'}\NormalTok{)}
\NormalTok{prostate <-}\StringTok{ }\NormalTok{data.table}\OperatorTok{::}\KeywordTok{data.table}\NormalTok{(prostate)}
\NormalTok{prostate.train <-}\StringTok{ }\NormalTok{prostate[train}\OperatorTok{==}\OtherTok{TRUE}\NormalTok{, }\OperatorTok{-}\StringTok{"train"}\NormalTok{]}
\NormalTok{prostate.test <-}\StringTok{ }\NormalTok{prostate[train}\OperatorTok{!=}\OtherTok{TRUE}\NormalTok{, }\OperatorTok{-}\StringTok{"train"}\NormalTok{]}
\NormalTok{y.train <-}\StringTok{ }\NormalTok{prostate.train}\OperatorTok{$}\NormalTok{lcavol}
\NormalTok{X.train <-}\StringTok{ }\KeywordTok{as.matrix}\NormalTok{(prostate.train[, }\OperatorTok{-}\StringTok{'lcavol'}\NormalTok{] )}
\NormalTok{y.test <-}\StringTok{ }\NormalTok{prostate.test}\OperatorTok{$}\NormalTok{lcavol }
\NormalTok{X.test <-}\StringTok{ }\KeywordTok{as.matrix}\NormalTok{(prostate.test[, }\OperatorTok{-}\StringTok{'lcavol'}\NormalTok{] )}
\CommentTok{# Preparing spam data:}
\KeywordTok{data}\NormalTok{(}\StringTok{"spam"}\NormalTok{, }\DataTypeTok{package =} \StringTok{'ElemStatLearn'}\NormalTok{)}
\NormalTok{n <-}\StringTok{ }\KeywordTok{nrow}\NormalTok{(spam)}
\NormalTok{train.prop <-}\StringTok{ }\FloatTok{0.66}
\NormalTok{train.ind <-}\StringTok{ }\KeywordTok{sample}\NormalTok{(}\DataTypeTok{x =} \KeywordTok{c}\NormalTok{(}\OtherTok{TRUE}\NormalTok{,}\OtherTok{FALSE}\NormalTok{), }
\DataTypeTok{size =}\NormalTok{ n, }
\DataTypeTok{prob =} \KeywordTok{c}\NormalTok{(train.prop,}\DecValTok{1}\OperatorTok{-}\NormalTok{train.prop), }
\DataTypeTok{replace=}\OtherTok{TRUE}\NormalTok{)}
\NormalTok{spam.train <-}\StringTok{ }\NormalTok{spam[train.ind,]}
\NormalTok{spam.test <-}\StringTok{ }\NormalTok{spam[}\OperatorTok{!}\NormalTok{train.ind,]}
\NormalTok{y.train.spam <-}\StringTok{ }\NormalTok{spam.train}\OperatorTok{$}\NormalTok{spam}
\NormalTok{X.train.spam <-}\StringTok{ }\KeywordTok{as.matrix}\NormalTok{(spam.train[,}\KeywordTok{names}\NormalTok{(spam.train)}\OperatorTok{!=}\StringTok{'spam'}\NormalTok{] ) }
\NormalTok{y.test.spam <-}\StringTok{ }\NormalTok{spam.test}\OperatorTok{$}\NormalTok{spam}
\NormalTok{X.test.spam <-}\StringTok{ }\KeywordTok{as.matrix}\NormalTok{(spam.test[,}\KeywordTok{names}\NormalTok{(spam.test)}\OperatorTok{!=}\StringTok{'spam'}\NormalTok{]) }
\NormalTok{spam.dummy <-}\StringTok{ }\NormalTok{spam}
\NormalTok{spam.dummy}\OperatorTok{$}\NormalTok{spam <-}\StringTok{ }\KeywordTok{as.numeric}\NormalTok{(spam}\OperatorTok{$}\NormalTok{spam}\OperatorTok{==}\StringTok{'spam'}\NormalTok{) }
\NormalTok{spam.train.dummy <-}\StringTok{ }\NormalTok{spam.dummy[train.ind,]}
\NormalTok{spam.test.dummy <-}\StringTok{ }\NormalTok{spam.dummy[}\OperatorTok{!}\NormalTok{train.ind,]}
\end{Highlighting}
\end{Shaded}
We also define some utility functions that we will require down the road.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{l2 <-}\StringTok{ }\ControlFlowTok{function}\NormalTok{(x) x}\OperatorTok{^}\DecValTok{2} \OperatorTok{%>%}\StringTok{ }\NormalTok{sum }\OperatorTok{%>%}\StringTok{ }\NormalTok{sqrt }
\NormalTok{l1 <-}\StringTok{ }\ControlFlowTok{function}\NormalTok{(x) }\KeywordTok{abs}\NormalTok{(x) }\OperatorTok{%>%}\StringTok{ }\NormalTok{sum }
\NormalTok{MSE <-}\StringTok{ }\ControlFlowTok{function}\NormalTok{(x) x}\OperatorTok{^}\DecValTok{2} \OperatorTok{%>%}\StringTok{ }\NormalTok{mean }
\NormalTok{missclassification <-}\StringTok{ }\ControlFlowTok{function}\NormalTok{(tab) }\KeywordTok{sum}\NormalTok{(tab[}\KeywordTok{c}\NormalTok{(}\DecValTok{2}\NormalTok{,}\DecValTok{3}\NormalTok{)])}\OperatorTok{/}\KeywordTok{sum}\NormalTok{(tab)}
\end{Highlighting}
\end{Shaded}
\hypertarget{least-squares}{%
\subsection{Linear Models with Least Squares Loss}\label{least-squares}}
The simplest approach to supervised learning, is simply with OLS: a linear predictor, squared error loss, and train-test risk estimator.
Notice the better in-sample MSE than the out-of-sample. That is overfitting in action.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{ols}\FloatTok{.1}\NormalTok{ <-}\StringTok{ }\KeywordTok{lm}\NormalTok{(lcavol}\OperatorTok{~}\NormalTok{. ,}\DataTypeTok{data =}\NormalTok{ prostate.train)}
\CommentTok{# Train error:}
\KeywordTok{MSE}\NormalTok{( }\KeywordTok{predict}\NormalTok{(ols}\FloatTok{.1}\NormalTok{)}\OperatorTok{-}\NormalTok{prostate.train}\OperatorTok{$}\NormalTok{lcavol) }
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] 0.4383709
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{# Test error:}
\KeywordTok{MSE}\NormalTok{( }\KeywordTok{predict}\NormalTok{(ols}\FloatTok{.1}\NormalTok{, }\DataTypeTok{newdata=}\NormalTok{prostate.test)}\OperatorTok{-}\StringTok{ }\NormalTok{prostate.test}\OperatorTok{$}\NormalTok{lcavol)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] 0.5084068
\end{verbatim}
Things to note:
\begin{itemize}
\tightlist
\item
I use the \texttt{newdata} argument of the \texttt{predict} function to make the out-of-sample predictions required to compute the test-error.
\item
The test error is larger than the train error. That is overfitting in action.
\end{itemize}
We now implement a V-fold CV, instead of our train-test approach.
The assignment of each observation to each fold is encoded in \texttt{fold.assignment}.
The following code is extremely inefficient, but easy to read.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{folds <-}\StringTok{ }\DecValTok{10}
\NormalTok{fold.assignment <-}\StringTok{ }\KeywordTok{sample}\NormalTok{(}\DecValTok{1}\OperatorTok{:}\NormalTok{folds, }\KeywordTok{nrow}\NormalTok{(prostate), }\DataTypeTok{replace =} \OtherTok{TRUE}\NormalTok{)}
\NormalTok{errors <-}\StringTok{ }\OtherTok{NULL}
\ControlFlowTok{for}\NormalTok{ (k }\ControlFlowTok{in} \DecValTok{1}\OperatorTok{:}\NormalTok{folds)\{}
\NormalTok{ prostate.cross.train <-}\StringTok{ }\NormalTok{prostate[fold.assignment}\OperatorTok{!=}\NormalTok{k,] }\CommentTok{# train subset}
\NormalTok{ prostate.cross.test <-}\StringTok{ }\NormalTok{prostate[fold.assignment}\OperatorTok{==}\NormalTok{k,] }\CommentTok{# test subset}
\NormalTok{ .ols <-}\StringTok{ }\KeywordTok{lm}\NormalTok{(lcavol}\OperatorTok{~}\NormalTok{. ,}\DataTypeTok{data =}\NormalTok{ prostate.cross.train) }\CommentTok{# train}
\NormalTok{ .predictions <-}\StringTok{ }\KeywordTok{predict}\NormalTok{(.ols, }\DataTypeTok{newdata=}\NormalTok{prostate.cross.test)}
\NormalTok{ .errors <-}\StringTok{ }\NormalTok{.predictions}\OperatorTok{-}\NormalTok{prostate.cross.test}\OperatorTok{$}\NormalTok{lcavol }\CommentTok{# save prediction errors in the fold}
\NormalTok{ errors <-}\StringTok{ }\KeywordTok{c}\NormalTok{(errors, .errors) }\CommentTok{# aggregate error over folds.}
\NormalTok{\}}
\CommentTok{# Cross validated prediction error:}
\KeywordTok{MSE}\NormalTok{(errors)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] 0.5459498
\end{verbatim}
Let's try all possible variable subsets, and choose the best performer with respect to the Cp criterion, which is an unbiased risk estimator.