-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path02-regression-multiple.Rmd
2432 lines (1590 loc) · 64.9 KB
/
02-regression-multiple.Rmd
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
<!--
kate: indent-width 4; word-wrap-column 74; default-dictionary en_AU
Copyright (C) 2020-2021, Marek Gagolewski <https://www.gagolewski.com>
This material is licensed under the Creative Commons BY-NC-ND 4.0 License.
-->
# Multiple Regression
```{r chapter-header-motd,echo=FALSE,results="asis"}
cat(readLines("chapter-header-motd.md"), sep="\n")
```
<!-- TODO
standardisation of variables and interpretability
show how to "derive" the original model from the "standardised" one
-->
## Introduction
### Formalism
Let $\mathbf{X}\in\mathbb{R}^{n\times p}$ be an input matrix
that consists of $n$ points in a $p$-dimensional space.
In other words, we have a database on $n$ objects, each of which
being described by means of $p$ numerical features.
\[
\mathbf{X}=
\left[
\begin{array}{cccc}
x_{1,1} & x_{1,2} & \cdots & x_{1,p} \\
x_{2,1} & x_{2,2} & \cdots & x_{2,p} \\
\vdots & \vdots & \ddots & \vdots \\
x_{n,1} & x_{n,2} & \cdots & x_{n,p} \\
\end{array}
\right]
\]
Recall that in supervised learning,
apart from $\mathbf{X}$, we are also given the corresponding $\mathbf{y}$;
with each input point $\mathbf{x}_{i,\cdot}$ we associate the desired output $y_i$.
In this chapter we are still interested in **regression** tasks;
hence, we assume that each $y_i$
it is a real number, i.e., $y_i\in\mathbb{R}$.
Hence, our dataset is $[\mathbf{X}\ \mathbf{y}]$ --
where each object is represented as a row vector
$[\mathbf{x}_{i,\cdot}\ y_i]$, $i=1,\dots,n$:
\[
[\mathbf{X}\ \mathbf{y}]=
\left[
\begin{array}{ccccc}
x_{1,1} & x_{1,2} & \cdots & x_{1,p} & y_1\\
x_{2,1} & x_{2,2} & \cdots & x_{2,p} & y_2\\
\vdots & \vdots & \ddots & \vdots & \vdots\\
x_{n,1} & x_{n,2} & \cdots & x_{n,p} & y_n\\
\end{array}
\right].
\]
### Simple Linear Regression - Recap
In a simple regression task, we have assumed that $p=1$ -- there is only
one independent variable,
denoted $x_i=x_{i,1}$.
We restricted ourselves to linear models of the form $Y=f(X)=a+bX$
that minimised the sum of squared residuals (SSR), i.e.,
\[
\min_{a,b\in\mathbb{R}} \sum_{i=1}^n \left(
a+bx_i-y_i
\right)^2.
\]
The solution is:
\[
\left\{
\begin{array}{rl}
b = & \dfrac{
n \displaystyle\sum_{i=1}^n x_i y_i - \displaystyle\sum_{i=1}^n y_i \displaystyle\sum_{i=1}^n x_i
}{
n \displaystyle\sum_{i=1}^n x_i x_i - \displaystyle\sum_{i=1}^n x_i\displaystyle\sum_{i=1}^n x_i
}\\
a = & \dfrac{1}{n}\displaystyle\sum_{i=1}^n y_i - b \dfrac{1}{n} \displaystyle\sum_{i=1}^n x_i \\
\end{array}
\right.
\]
Fitting in R can be performed by calling the `lm()` function:
```{r simple_recap1}
library("ISLR") # Credit dataset
X <- as.numeric(Credit$Balance[Credit$Balance>0])
Y <- as.numeric(Credit$Rating[Credit$Balance>0])
f <- lm(Y~X) # Y~X is a formula, read: Y is a function of X
print(f)
```
Figure \@ref(fig:simple-recap2) gives the scatter plot
of Y vs. X together with the fitted simple linear model.
```{r simple-recap2,fig.cap="Fitted regression line for the Credit dataset"}
plot(X, Y, xlab="X (Balance)", ylab="Y (Credit)")
abline(f, col=2, lwd=3)
```
## Multiple Linear Regression
### Problem Formulation
Let's now generalise the above to the case of many variables
$X_1, \dots, X_p$.
We wish to model the dependent variable as a function of $p$ independent variables.
\[
Y = f(X_1,\dots,X_p) \qquad (+\varepsilon)
\]
Restricting ourselves to the class of **linear models**, we have
\[
Y = \beta_0 + \beta_1 X_1 + \beta_2 X_2 + \dots + \beta_p X_p.
\]
Above we studied the case where $p=1$, i.e., $Y=a+bX_1$ with $\beta_0=a$ and $\beta_1=b$.
The above equation defines:
- $p=1$ --- a line (see Figure \@ref(fig:simple-recap2)),
- $p=2$ --- a plane (see Figure \@ref(fig:scatterplot3dexample)),
- $p\ge 3$ --- a hyperplane (well, most people find it difficult
to imagine objects in high dimensions,
but we are lucky to have this thing called maths).
```{r scatterplot3dexamplefit,echo=FALSE}
X1 <- as.numeric(Credit$Balance[Credit$Balance>0])
X2 <- as.numeric(Credit$Income[Credit$Balance>0])
Y <- as.numeric(Credit$Rating[Credit$Balance>0])
f <- lm(Y~X1+X2)
```
```{r scatterplot3dexample,echo=FALSE,fig.height=4,fig.cap="Fitted regression plane for the Credit dataset"}
par(ann=FALSE) # to disable our plot.window trickery
library("scatterplot3d")
s3d <- scatterplot3d(X1, X2, Y,
angle=60, # change angle to reveal more
highlight.3d=TRUE, xlab="Balance", ylab="Income",
zlab="Rating")
s3d$plane3d(f, lty.box="solid")
```
### Fitting a Linear Model in R
`lm()` accepts a formula of the form `Y~X1+X2+...+Xp`.
It finds the least squares fit, i.e., solves
\[
\min_{\beta_0, \beta_1,\dots, \beta_p\in\mathbb{R}}
\sum_{i=1}^n \left( \beta_0 + \beta_1 x_{i,1}+\dots+\beta_p x_{i,p} - y_i \right) ^2
\]
```{r fig_scatterplot3dexamplefit}
<<scatterplot3dexamplefit>>
f$coefficients # ß0, ß1, ß2
```
By the way, the 3D scatter plot in Figure \@ref(fig:scatterplot3dexample)
was generated by calling:
```{r fig_scatterplot3dexamplefit_show_code,fig.keep='none',eval=FALSE,echo=-1}
<<scatterplot3dexample>>
```
(`s3d` is an R list, one of its elements named `plane3d` is a function object -- this is legal)
## Finding the Best Model
### Model Diagnostics
<!-- more metrics:
https://scikit-learn.org/stable/modules/model_evaluation.html#regression-metrics
-->
Here is Rating ($Y$) as function of Balance ($X_1$, lefthand side of Figure \@ref(fig:x12-y))
and Income ($X_2$, righthand side of Figure \@ref(fig:x12-y)).
```{r x12-y,echo=FALSE,fig.cap="Scatter plots of $Y$ vs. $X_1$ and $X_2$"}
par(mfrow=c(1,2))
plot(X1, Y, xlab="X1 (Balance)", ylab="Y (Rating)")
f1 <- lm(Y~X1) # Rating ~ Balance
abline(f1, col=2,lwd=3)
plot(X2, Y, xlab="X2 (Income)", ylab="Y (Rating)")
f2 <- lm(Y~X2) # Rating ~ Income
abline(f2, col=2, lwd=3)
```
Moreover, Figure \@ref(fig:x12-ycolmap) depicts
(in a hopefully readable manner) both $X_1$ and $X_2$ with Rating $Y$
encoded with a colour (low ratings are green, high ratings are red;
some rating values are explicitly printed out within the plot).
```{r x12-ycolmap,echo=FALSE,fig.cap="A heatmap for Rating as a function of Balance and Income; greens represent low credit ratings, whereas reds -- high ones"}
library("RColorBrewer")
pal <- paste0(rev(brewer.pal(11, "RdYlGn")), "77")
C <- pal[cut(Y, seq(min(Y), max(Y), length.out=length(pal)-1))]
plot(X1, X2, col=C, pch=16, cex=3, xlab="X1 (Balance)", ylab="X2 (Income)")
set.seed(123)
which_y <- order(Y)
which_y <- as.numeric(sapply(split(which_y, cut(Y[which_y], seq(min(Y), max(Y), length.out=length(pal)-1))), range))
text(X1[which_y], X2[which_y], Y[which_y])
```
Consider the three following models.
Formula | Equation
--------------------------|----------------------------------------------------
Rating ~ Balance + Income | $Y=\beta_0 + \beta_1 X_1 + \beta_2 X_2$
Rating ~ Balance | $Y=a + b X_1$ ($\beta_0=a, \beta_1=b, \beta_2=0$)
Rating ~ Income | $Y=a + b X_2$ ($\beta_0=a, \beta_1=0, \beta_2=b$)
```{R}
f12 <- lm(Y~X1+X2) # Rating ~ Balance + Income
f12$coefficients
f1 <- lm(Y~X1) # Rating ~ Balance
f1$coefficients
f2 <- lm(Y~X2) # Rating ~ Income
f2$coefficients
```
Which of the three models is the best?
Of course, by using the word "best",
we need to answer the question "best?... but with respect to what kind of measure?"
So far we were fitting w.r.t. SSR,
as the multiple regression model generalises the two simple ones,
the former must yield a not-worse SSR.
This is because in the case of $Y=\beta_0 + \beta_1 X_1 + \beta_2 X_2$,
setting $\beta_1$ to 0 (just one of uncountably many possible $\beta_1$s,
if it happens to be the *best* one, good for us)
gives $Y=a + b X_2$
whereas by setting $\beta_2$ to 0 we obtain $Y=a + b X_1$.
```{r ssrs}
sum(f12$residuals^2)
sum(f1$residuals^2)
sum(f2$residuals^2)
```
We get that, in terms of SSRs, $f_{12}$ is better than $f_{2}$,
which in turn is better than $f_{1}$.
However, these error values per se (sheer numbers)
are meaningless (not meaningful).
Remark.
: Interpretability in ML has always been an important issue, think the EU
General Data Protection Regulation (GDPR), amongst others.
#### SSR, MSE, RMSE and MAE
The quality of fit can be assessed by performing some *descriptive
statistical analysis of the residuals*, $\hat{y}_i-y_i$,
for $i=1,\dots,n$.
I know how to summarise data on the residuals!
Of course I should compute their arithmetic mean and I'm done with that task!
Interestingly, the mean of residuals (this can be shown analytically)
in the least squared fit is always equal to $0$:
\[
\frac{1}{n} \sum_{i=1}^n (\hat{y}_i-y_i)=0.
\]
Therefore, we need a different metric.
{ BEGIN exercise }
(\*) A proof of this fact is left as an exercise to the curious;
assume $p=1$ just as in the previous chapter and note that $\hat{y}_i=a x_i+b$.
{ END exercise }
```{r meanresiduals}
mean(f12$residuals) # almost zero numerically
all.equal(mean(f12$residuals), 0)
```
We noted that sum of squared residuals (SSR) is not interpretable,
but the mean squared residuals
(MSR) -- also called mean squared error (MSE) regression loss -- is a little better.
Recall that mean is defined as the sum divided by number of samples.
\[
\mathrm{MSE}(f) = \frac{1}{n} \sum_{i=1}^n (f(\mathbf{x}_{i,\cdot})-y_i)^2.
\]
```{r mse}
mean(f12$residuals^2)
mean(f1$residuals^2)
mean(f2$residuals^2)
```
This gives an information of how much do we err *per sample*,
so at least this measure does not depend on $n$ anymore.
However, if the original $Y$s are, say, in metres $[\mathrm{m}]$,
MSE is expressed in metres squared $[\mathrm{m}^2]$.
To account for that, we may consider the root mean squared error (RMSE):
\[
\mathrm{RMSE}(f) = \sqrt{\frac{1}{n} \sum_{i=1}^n (f(\mathbf{x}_{i,\cdot})-y_i)^2}.
\]
This is just like with the sample variance vs. standard deviation --
recall the latter is defined as the square root of the former.
```{r rmse}
sqrt(mean(f12$residuals^2))
sqrt(mean(f1$residuals^2))
sqrt(mean(f2$residuals^2))
```
The interpretation of the RMSE is rather quirky;
it is some-sort-of-averaged *deviance* from the true rating
(which is on the scale 0--1000, hence we see that the first model is not
that bad). Recall that the square function is sensitive to large observations,
hence, it penalises notable deviations more heavily.
As still we have a problem with finding something easily interpretable
(your non-technical boss or client may ask you: but what do these numbers mean??),
we suggest here that the mean absolute error (MAE;
also called mean absolute deviations, MAD)
might be a better idea than the above:
\[
\mathrm{MAE}(f) = \frac{1}{n} \sum_{i=1}^n |f(\mathbf{x}_{i,\cdot})-y_i|.
\]
```{r mae}
mean(abs(f12$residuals))
mean(abs(f1$residuals))
mean(abs(f2$residuals))
```
With the above we may say "On average, the predicted rating differs from the
observed one by...". That is good enough.
Remark.
: (\*) You may ask why don't we fit models so as to minimise the MAE
and we minimise the RMSE instead (note that minimising RMSE is the same as
minimising the SSR, one is a strictly monotone transformation of the other
and do not affect the solution). Well, it is possible.
It turns out that, however, minimising MAE is more computationally expensive
and the solution may be numerically unstable.
So it's rarely an analyst's first choice (assuming they are well-educated
enough to know about the MAD regression task). However, it may be worth
trying it out sometimes.
Sometimes we might prefer MAD regression to the classic one
if our data is heavily contaminated by outliers. But
in such cases it is worth checking if proper data cleansing does
the trick.
#### Graphical Summaries of Residuals
If we are not happy with single numerical aggregated of the residuals
or their absolute values, we can (and should) always compute a whole
bunch of descriptive statistics:
```{r summaryresiduals}
summary(f12$residuals)
summary(f1$residuals)
summary(f2$residuals)
```
The outputs generated by `summary()` include:
- `Min.` -- sample minimum
- `1st Qu.` -- 1st quartile == 25th percentile == quantile of order 0.25
- `Median` -- median == 50th percentile == quantile of order 0.5
- `3rd Qu.` -- 3rd quartile = 75th percentile == quantile of order 0.75
- `Max.` -- sample maximum
For example, 1st quartile is the observation $q$ such that
25\% values are $\le q$ and 75\% values are $\ge q$,
see `?quantile` in R.
Graphically, it is nice to summarise the empirical distribution
of the residuals on a **box and whisker plot**.
Here is the key to decipher Figure \@ref(fig:boxplot-explained):
* IQR == Interquartile range == Q3$-$Q1 (box width)
* The box contains 50\% of the "most typical" observations
* Box and whiskers altogether have width $\le$ 4 IQR
* Outliers == observations potentially worth inspecting (is it a bug or a feature?)
```{r boxplot-explained,echo=FALSE,fig.cap="An example boxplot"}
x <- f1$residuals
boxplot(x, horizontal=TRUE, xlim=c(-0.3, 2.3), ylim=c(-300, 300), col="white")
q1 <- quantile(x, 0.25)
q2 <- quantile(x, 0.5)
q3 <- quantile(x, 0.75)
iqr <- q3-q1
segments(q2, 0, q2, 1, lty=3)
text(q2, 0, "Median", pos=1)
segments(q1, 2, q1, 1, lty=3)
text(q1, 2, "1st Qu. (Q1)", pos=3)
segments(q3, 1.8, q3, 1, lty=3)
text(q3, 1.8, "3rd Qu. (Q3)", pos=3)
segments(min(x), 2, min(x), 1, lty=3)
text(min(x), 2, "Min.", pos=3)
segments(max(x), 1.8, max(x), 1, lty=3)
text(max(x), 1.8, "Max.", pos=3)
segments(q3+1.5*iqr, 2, sort(x[x>q3+1.5*iqr], decreasing=TRUE)[c(1, 5, 10)], 1, lty=3)
text(q3+1.5*iqr, 2, "(potential) outliers", pos=3)
segments(q3+1.5*iqr, 0, q3+1.5*iqr, 1, lty=3)
text(q3+1.5*iqr, 0, "Q3 + 1.5 IQR", pos=1)
segments(q1-1.5*iqr, 0, q1-1.5*iqr, 1, lty=3)
text(q1-1.5*iqr, 0, "Q1 - 1.5 IQR", pos=1)
```
Figure \@ref(fig:boxplot-residuals) is worth a thousand words:
```{r boxplot-residuals,fig.cap="Box plots of the residuals for the three models studied"}
boxplot(horizontal=TRUE, xlab="residuals", col="white",
list(f12=f12$residuals, f1=f1$residuals, f2=f2$residuals))
abline(v=0, lty=3)
```
Figure \@ref(fig:violinplot-residuals) gives a *violin plot* -- a blend of a box plot and a (kernel) density estimator (histogram-like):
```{r violinplot-residuals,message=FALSE,fig.cap="Violin plots of the residuals for the three models studied"}
library("vioplot")
vioplot(horizontal=TRUE, xlab="residuals", col="white",
list(f12=f12$residuals, f1=f1$residuals, f2=f2$residuals))
abline(v=0, lty=3)
```
We can also take a look at the absolute values of the residuals.
Here are some descriptive statistics:
```{r absresiduals}
summary(abs(f12$residuals))
summary(abs(f1$residuals))
summary(abs(f2$residuals))
```
Figure \@ref(fig:absresiduals-boxplot) is worth \$1000:
```{r absresiduals-boxplot,fig.cap="Box plots of the modules of the residuals for the three models studied"}
boxplot(horizontal=TRUE, col="white", xlab="abs(residuals)",
list(f12=abs(f12$residuals), f1=abs(f1$residuals),
f2=abs(f2$residuals)))
abline(v=0, lty=3)
```
#### Coefficient of Determination (R-squared)
If we didn't know the range of the dependent variable
(in our case we do know that the credit rating is on the scale 0--1000),
the RMSE or MAE would be hard to interpret.
It turns out that there is a popular *normalised* (unit-less) measure
that is somehow easy to interpret with no domain-specific knowledge
of the modelled problem.
Namely, the (unadjusted) **$R^2$ score** (the coefficient of determination)
is given by:
\[
R^2(f) = 1 - \frac{\sum_{i=1}^{n} \left(y_i-f(\mathbf{x}_{i,\cdot})\right)^2}{\sum_{i=1}^{n} \left(y_i-\bar{y}\right)^2},
\]
where $\bar{y}$ is the arithmetic mean $\frac{1}{n}\sum_{i=1}^n y_i$.
```{r rsquared}
(r12 <- summary(f12)$r.squared)
1 - sum(f12$residuals^2)/sum((Y-mean(Y))^2) # the same
(r1 <- summary(f1)$r.squared)
(r2 <- summary(f2)$r.squared)
```
The coefficient of determination gives the proportion of variance of the
dependent variable explained by independent variables in the model;
$R^2(f)\simeq 1$ indicates a perfect fit.
The first model is a very good one, the simple models are
"more or less okay".
Unfortunately, $R^2$ tends to automatically increase as the number of independent variables
increase (recall that the more variables in the model,
the better the SSR must be).
To correct for this phenomenon, we sometimes consider the **adjusted $R^2$**:
\[
\bar{R}^2(f) = 1 - (1-{R}^2(f))\frac{n-1}{n-p-1}
\]
```{r adj-rsquared}
summary(f12)$adj.r.squared
n <- length(x); 1 - (1 - r12)*(n-1)/(n-3) # the same
summary(f1)$adj.r.squared
summary(f2)$adj.r.squared
```
In other words, the adjusted $R^2$ penalises for more complex models.
Remark.
: (\*) Side note -- results of some statistical tests (e.g., significance of coefficients)
are reported by calling `summary(f12)` etc. --- refer to a more advanced source to obtain more information.
These, however, require the verification of some assumptions regarding the input data
and the residuals.
```{r summary_f12}
summary(f12)
```
#### Residuals vs. Fitted Plot
We can also create scatter plots of the residuals
(predicted $\hat{y}_i$ minus
true $y_i$) as a function of the predicted
$\hat{y}_i=f(\mathbf{x}_{i,\cdot})$, see Figure \@ref(fig:resid-vs-fitted).
```{r resid-vs-fitted,fig.cap="Residuals vs. fitted outputs for the three regression models"}
Y_pred12 <- f12$fitted.values # predict(f12, data.frame(X1, X2))
Y_pred1 <- f1$fitted.values # predict(f1, data.frame(X1))
Y_pred2 <- f2$fitted.values # predict(f2, data.frame(X2))
par(mfrow=c(1, 3))
plot(Y_pred12, Y_pred12-Y)
plot(Y_pred1, Y_pred1 -Y)
plot(Y_pred2, Y_pred2 -Y)
```
Ideally (provided that the hypothesis that the dependent variable
is indeed a linear function of the dependent variable(s) is true),
we would expect to see a point cloud that spread around $0$ in a
very much unorderly fashion.
<!--
homoskedastic
-->
### Variable Selection
Okay, up to now we've been considering the problem of modelling
the `Rating` variable as a function of `Balance` and/or `Income`.
However, it the `Credit` data set there are other variables
possibly worth inspecting.
Consider all quantitative (numeric-continuous) variables in the `Credit` data set.
```{r Csubset}
C <- Credit[Credit$Balance>0,
c("Rating", "Limit", "Income", "Age",
"Education", "Balance")]
head(C)
```
Obviously there are many possible combinations of the variables
upon which regression models can be constructed
(precisely, for $p$ variables there are $2^p$ such models).
How do we choose the *best* set of inputs?
Remark.
: We should already be suspicious at this point:
wait... *best* requires some sort of criterion, right?
First, however, let's draw a matrix of scatter plots for
every pair of variables
-- so as to get an impression of how individual variables
interact with each other, see Figure \@ref(fig:pairs).
```{r pairs,fig.height=6,fig.cap="Scatter plot matrix for the Credit dataset"}
pairs(C)
```
It seems like `Rating` depends on `Limit` almost linearly...
We have a tool to actually quantify the degree of linear dependence
between a pair of variables --
Pearson's $r$ -- the linear correlation coefficient:
\[
r(\boldsymbol{x},\boldsymbol{y}) = \frac{
\sum_{i=1}^n (x_i-\bar{x}) (y_i-\bar{y})
}{
\sqrt{\sum_{i=1}^n (x_i-\bar{x})^2} \sqrt{\sum_{i=1}^n (y_i-\bar{y})^2}
}.
\]
It holds $r\in[-1,1]$, where:
* $r=1$ -- positive linear dependence ($y$ increases as $x$ increases)
* $r=-1$ -- negative linear dependence ($y$ decreases as $x$ increases)
* $r\simeq 0$ -- uncorrelated or non-linearly dependent
Figure \@ref(fig:pearson-interpret) gives an illustration of the above.
```{r pearson-interpret,echo=FALSE,fig.height=6,fig.cap="Different datasets and the corresponding Pearson's $r$ coefficients"}
par(mfrow=c(2,2))
set.seed(123)
x <- runif(25)
y <- 7*x+3+rnorm(25,0,0.5)
plot(x, y, axes=FALSE, ann=FALSE)
legend("topleft", bg="white", legend=c(sprintf("r=%.2f", cor(x,y)), "positive correlation"))
box()
y <- -7*x+3+rnorm(25,0,0.5)
plot(x, y, axes=FALSE, ann=FALSE)
legend("topright", bg="white", legend=c(sprintf("r=%.2f", cor(x,y)), "negative correlation"))
box()
y <- runif(25)
plot(x, y, axes=FALSE, ann=FALSE)
legend("topleft", bg="white", legend=c(sprintf("r=%.2f", cor(x,y)), "no correlation"))
box()
x <- runif(25)
y <- abs((x-0.5)*100)+rnorm(length(x))
plot(x, y, axes=FALSE, ann=FALSE)
legend("top", bg="white", legend=c(sprintf("r=%.2f", cor(x,y)), "non-linear correlation"))
box()
```
To compute Pearson's $r$ between all pairs of variables, we call:
```{r pearson_cor}
round(cor(C), 3)
```
`Rating` and `Limit` are almost perfectly linearly correlated,
and both seem to describe the same thing.
For practical purposes, we'd rather model `Rating` as a function of the other variables.
For simple linear regression models, we'd choose either `Income` or `Balance`.
How about multiple regression though?
The best model:
* has high predictive power,
* is simple.
These two criteria are often mutually exclusive.
<!--
Tension between prediction and description, between technology and science
"what companies want" -- more money (models that increase revenue, even slightly, at all cost)
-->
Which variables should be included in the optimal model?
Again, the definition of the "best" object needs a *fitness* function.
For fitting a single model to data, we use the SSR.
We need a metric that takes the number of dependent variables into account.
Remark.
: (\*) Unfortunately, the adjusted $R^2$, despite its interpretability,
is not really suitable for this task. It does not penalise complex models
heavily enough to be really useful.
Here we'll be using **the Akaike Information Criterion** (AIC).
For a model $f$ with $p'$ independent variables:
\[
\mathrm{AIC}(f) = 2(p'+1)+n\log(\mathrm{SSR}(f))-n\log n
\]
Our task is to find the combination of independent variables
that minimises the AIC.
Remark.
: (\*\*) Note that this is a bi-level optimisation problem -- for every
considered combination of variables (which we look for),
we must solve another problem of finding the best model
involving these variables -- the one that minimises the SSR.
\[
\min_{s_1,s_2,\dots,s_p\in\{0, 1\}}
\left(
\begin{array}{l}
2\left(\displaystyle\sum_{j=1}^p s_j +1\right)+\\
n\log\left(
\displaystyle\min_{\beta_0,\beta_1,\dots,\beta_p\in\mathbb{R}}
\sum_{i=1}^n \left(
\beta_0 + s_1\beta_1 x_{i,1} + \dots + s_p\beta_p x_{i,p}
-y_i
\right)^2
\right)
\end{array}
\right)
\]
We dropped the $n\log n$ term, because it is always constant
and hence doesn't affect the solution.
If $s_j=0$, then the $s_j\beta_j x_{i,j}$ term is equal to
$0$, and hence is not considered in the model.
This plays the role of including $s_j=1$ or omitting $s_j=0$ the $j$-th
variable in the model building exercise.
For $p$ variables, the number of their possible
combinations is equal to $2^p$
(grows exponentially with $p$).
For large $p$ (think big data), an extensive search is impractical
(in our case we could get away with this though -- left as an exercise
to a slightly more advanced reader).
Therefore, to find the variable combination minimising the AIC,
we often rely on one of the two following greedy heuristics:
- forward selection:
1. start with an empty model
2. find an independent variable
whose addition to the current model would yield the highest decrease in the AIC and add it to the model
3. go to step 2 until AIC decreases
- backward elimination:
1. start with the full model
2. find an independent variable
whose removal from the current model would decrease the AIC the most and eliminate it from the model
3. go to step 2 until AIC decreases
Remark.
: (\*\*) The above bi-level optimisation problem
can be solved by implementing a genetic algorithm -- see further chapter for more details.
Remark.
: (\*) There are of course many other methods which also perform
some form of variable selection, e.g., lasso regression.
But these minimise a different objective.
First, a forward selection example.
We need a data sample to work with:
```{r step1a}
C <- Credit[Credit$Balance>0,
c("Rating", "Income", "Age",
"Education", "Balance")]
```
Then, a formula that represents a model with no variables
(model from which we'll start our search):
```{r step1b}
(model_empty <- Rating~1)
```
Last, we need a model that includes all the variables.
We're too lazy to list all of them manually, therefore,
we can use the `model.frame()` function to generate
a corresponding formula:
```{r step1c}
(model_full <- formula(model.frame(Rating~., data=C))) # all variables
```
Now we are ready.
```{r step1d}
step(lm(model_empty, data=C), # starting model
scope=model_full, # gives variables to consider
direction="forward")
formula(lm(Rating~., data=C))
```
The full model has been selected.
<!-- TODO: detailed explanation what's happening here -->
. . .
And now for something completely different --
a backward elimination example:
```{r step2}
step(lm(model_full, data=C), # from
scope=model_empty, # to
direction="backward")
```
The full model is considered the best again.
<!-- TODO: detailed explanation what's happening here -->
. . .
Forward selection example -- full dataset:
```{r step3}
C <- Credit[, # do not restrict to Credit$Balance>0
c("Rating", "Income", "Age",
"Education", "Balance")]
step(lm(model_empty, data=C),
scope=model_full,
direction="forward")
```
This procedure suggests including only the `Balance` and `Income`
variables.
. . .
Backward elimination example -- full dataset:
```{r step4}
step(lm(model_full, data=C), # full model
scope=model_empty, # empty model
direction="backward")
```
This procedure gives the same results as forward selection
(however, for other data sets this might not necessarily be the case).
### Variable Transformation
So far we have been fitting linear models of the form:
\[
Y = \beta_0 + \beta_1 X_1 + \dots + \beta_p X_p.
\]
What about some non-linear models such as polynomials etc.? For example:
\[
Y = \beta_0 + \beta_1 X_1 + \beta_2 X_1^2 + \beta_3 X_1^3 + \beta_4 X_2.
\]
Solution: pre-process inputs by setting
$X_1' := X_1$, $X_2' := X_1^2$, $X_3' := X_1^3$, $X_4' := X_2$
and fit a linear model:
\[
Y = \beta_0 + \beta_1 X_1' + \beta_2 X_2' + \beta_3 X_3' + \beta_4 X_4'.
\]
This trick works for every model of the form
$Y=\sum_{i=1}^k \sum_{j=1}^p \varphi_{i,j}(X_j)$ for any $k$
and any univariate functions $\varphi_{i,j}$.
Also, with a little creativity (and maths), we might be able to transform
a few other models to a linear one, e.g.,