-
Notifications
You must be signed in to change notification settings - Fork 2
/
prediction.Rmd
1860 lines (1318 loc) · 62.9 KB
/
prediction.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
---
title: "3. Prediction with High Dimensional Predictors"
author: "Lieven Clement"
date: "statOmics, Ghent University (https://statomics.github.io)"
output:
bookdown::pdf_document2:
toc: true
number_sections: true
latex_engine: xelatex
always_allow_html: true
---
```{r, child="_setup.Rmd"}
```
```{r echo=FALSE, message= FALSE}
library(tidyverse)
library(gridExtra)
```
# Introduction
## Prediction with High Dimensional Predictors
General setting:
- Aim: build a **prediction model** that gives a prediction of an outcome for a given set of predictors.
- We use $X$ to refer to the predictors and $Y$ to refer to the outcome.
- A **training data set** is available, say $(\mathbf{X},\mathbf{Y})$. It contains $n$ observations on outcomes and on $p$ predictors.
- Using the training data, a prediction model is build, say $\hat{m}(\mathbf{X})$. This typically involves **model building (feature selection)** and parameter estimation.
- During the model building, potential **models need to be evaluated** in terms of their prediction quality.
## Example: Toxicogenomics in early drug development
### Background
- Effect of compound on gene expression.
- Insight in action and toxicity of drug in early phase
- Determine activity with bio-assay: e.g. binding affinity of compound to cell wall receptor (target, IC50).
- Early phase: 20 to 50 compounds
- Based on in vitro results one aims to get insight in how to build better compound (higher on-target activity less toxicity.
- Small variations in molecular structure lead to variations in BA and gene expression.
- Aim: Build model to predict bio-activity based on gene expression in liver cell line.
### Data
- 30 chemical compounds have been screened for toxicity
- Bioassay data on toxicity screening
- Gene expressions in a liver cell line are profiled for each compound (4000 genes)
```{r}
toxData <- read_csv(
"https://raw.githubusercontent.com/statOmics/HDA2020/data/toxDataCentered.csv",
col_types = cols()
)
svdX <- svd(toxData[,-1])
```
Data is already centered:
```{r}
toxData %>%
colMeans %>%
range
```
```{r}
toxData %>%
names %>%
head
```
- First column contains data on Bioassay.
- The higher the score on Bioassay the more toxic the compound
- Other columns contain data on gene expression X1, ... , X4000
### Data exploration
```{r}
toxData %>%
ggplot(aes(x="",y=BA)) +
geom_boxplot(outlier.shape=NA) +
geom_point(position="jitter")
```
```{r}
svdX <- toxData[,-1] %>%
svd
k <- 2
Vk <- svdX$v[,1:k]
Uk <- svdX$u[,1:k]
Dk <- diag(svdX$d[1:k])
Zk <- Uk%*%Dk
colnames(Zk) <- paste0("Z",1:k)
colnames(Vk) <- paste0("V",1:k)
Zk %>%
as.data.frame %>%
mutate(BA = toxData %>% pull(BA)) %>%
ggplot(aes(x= Z1, y = Z2, color = BA)) +
geom_point(size = 3) +
scale_colour_gradient2(low = "blue",mid="white",high="red") +
geom_point(size = 3, pch = 21, color = "black")
```
- Scores on the first two principal components (or MDS plot).
- Each point corresponds to a compound.
- Color code refers to the toxicity score (higher score more toxic).
- Clear separation between compounds according to toxicity.
---
- Next logic step in a PCA is to interpret the principal components.
- We thus have to assess the loadings.
- We can add a vector for each gene to get a biplot, but this would require plotting 4000 vectors, which would render the plot unreadable.
Alternative graph to look at the many loadings of the first two PCs.
```{r}
grid.arrange(
Vk %>%
as.data.frame %>%
mutate(geneID = 1:nrow(Vk)) %>%
ggplot(aes(x = geneID, y = V1)) +
geom_point(pch=21) +
geom_hline(yintercept = c(-2,0,2)*sd(Vk[,1]), col = "red") ,
Vk %>%
as.data.frame %>%
mutate(geneID = 1:nrow(Vk)) %>%
ggplot(aes(x = geneID, y = V2)) +
geom_point(pch=21) +
geom_hline(yintercept = c(-2,0,2)*sd(Vk[,2]), col = "red"),
ncol=2)
```
- It is almost impossible to interpret the PCs because there are 4000 genes contributing to each PC.
- In an attempt to find the most important genes (in the sense that they drive the interpretation of the PCs), the plots show horizontal reference lines: the average of the loadings, and the average ± twice the standard deviation of the loadings. In between the lines we expects about 95% of the loadings (if they were normally distributed).
- The points outside the band come from the genes that have rather large loadings (in absolute value) and hence are important for the interpretation of the PCs.
- Note, that particularly for the first PC, only a few genes show a markedly large loadings that are negative. This means that an upregulation of these genes will lead to low scores on PC1.
- These genes will very likely play an important role in the toxicity mechanism.
- Indeed, low scores on PC1 are in the direction of more toxicity.
- In the next chapter we will introduce a method to obtain sparse PCs.
### Prediction model
```{r}
m1 <- lm(BA ~ -1 + ., toxData)
m1 %>%
coef %>%
head(40)
m1 %>%
coef %>%
is.na %>%
sum
summary(m1)$r.squared
```
Problem??
## Brain example
- Courtesy to Solomon Kurz. Statistical rethinking with brms, ggplot2, and the tidyverse version 1.2.0.
https://bookdown.org/content/3890/
https://github.com/ASKurz/Statistical_Rethinking_with_brms_ggplot2_and_the_tidyverse
- Data with brain size and body size for seven species
```{r}
brain <-
tibble(species = c("afarensis", "africanus", "habilis", "boisei", "rudolfensis", "ergaster", "sapiens"),
brain = c(438, 452, 612, 521, 752, 871, 1350),
mass = c(37.0, 35.5, 34.5, 41.5, 55.5, 61.0, 53.5))
```
### Data exploration
```{r}
brain
p <- brain %>%
ggplot(aes(x = mass, y = brain, label = species)) +
geom_point()
p + geom_text(nudge_y = 40)
```
### Models
Six models range in complexity from the simple univariate model
\begin{align*}
\text{brain}_i & \sim \operatorname{Normal} (\mu_i, \sigma) \\
\mu_i & = \beta_0 + \beta_1 \text{mass}_i,
\end{align*}
to the dizzying sixth-degree polynomial model
\begin{align*}
\text{brain}_i & \sim \operatorname{Normal} (\mu_i, \sigma) \\
\mu_i & = \beta_0 + \beta_1 \text{mass}_i + \beta_2 \text{mass}_i^2 + \beta_3 \text{mass}_i^3 + \beta_4 \text{mass}_i^4 + \beta_5 \text{mass}_i^5 + \beta_6 \text{mass}_i^6.
\end{align*}
```{r, message = F, warning = F}
formulas <- sapply(1:6, function(i)
return(
paste0("I(mass^",1:i,")") %>% paste(collapse=" + ")
)
)
formulas <- sapply(
paste0("brain ~ ", formulas),
as.formula)
models <- lapply(formulas, lm , data = brain)
```
```{r}
data.frame(
formula=formulas %>%
as.character,
r2 = sapply(
models,
function(mod) summary(mod)$r.squared)
) %>%
ggplot(
aes(x = r2,
y = formula,
label = r2 %>%
round(2) %>%
as.character)
) +
geom_text()
```
We plot the fit for each model individually and them arrange them together in one plot.
```{r}
plots <- lapply(1:6, function(i)
{
p +
geom_smooth(method = "lm", formula = y ~ poly(x,i)) +
ggtitle(
paste0(
"r2 = ",
round(summary(models[[i]])$r.squared*100,1),
"%")
)
})
do.call("grid.arrange",c(plots, ncol = 3))
```
- We clearly see that increasing the model complexity always produces a fit with a smaller SSE.
- The problem of overfitting is very obvious. The more complex polynomial models will not generalise well for prediction!
- We even have a model that fits the data perfectly, but that will make very absurd preditions!
- Too few parameters hurts, too. Fit the underfit intercept-only model.
```{r}
m0 <- lm(brain ~ 1, brain)
summary(m0)
p +
stat_smooth(method = "lm", formula = y ~ 1) +
ggtitle(
paste0(
"r2 = ",
round(summary(m0)$r.squared*100,1),
"%")
)
```
The underfit model did not learn anything about the relation between mass and brain. It would also do a very poor job for predicting new data.
## Overview
We will make a distinction between continuous and discrete outcomes. In this course we focus on
- Linear regression models for continous outcomes
- Penalised regression: Lasso and ridge
- Principal component regression (PCR)
- Logistic regression models for binary outcomes
- Penalised regression: Lasso and ridge
For all types of model, we will discuss feature selection methods.
# Linear Regression for High Dimensional Data
Consider linear regression model (for double centered data)
\[
Y_i = \beta_1X_{i1} + \beta_2 X_{i2} + \cdots + \beta_pX_{ip} + \epsilon_i ,
\]
with $\text{E}\left[\epsilon \mid \mathbf{X}\right]=0$ and $\text{var}\left[\epsilon \mid \mathbf{X}\right]=\sigma^2$.
In matrix notation the model becomes
\[
\mathbf{Y} = \mathbf{X}\mathbf\beta + \mathbf\epsilon.
\]
The least squares estimator of $\mathbf\beta$ is given by
\[
\hat{\mathbf\beta} = (\mathbf{X}^T\mathbf{X})^{-1}\mathbf{X}^T\mathbf{Y} ,
\]
and the variance of $\hat{\mathbf\beta}$ equals
\[
\text{var}\left[\hat{\mathbf\beta}\right] = (\mathbf{X}^T\mathbf{X})^{-1}\sigma^2.
\]
$\longrightarrow$ the $p \times p$ matrix $(\mathbf{X}^T\mathbf{X})^{-1}$ is crucial
Note, that
- with double centered data it is meant that both the responses are centered (mean of $\mathbf{Y}$ is zero) and that all predictors are centered (columns of $\mathbf{X}$ have zero mean). With double centered data the intercept in a linear regression model is always exactly equal to zero and hence the intercept must not be included in the model.
- we do not assume that the residuals are normally distributed. For prediction purposes this is often not required (normality is particularly important for statistical inference in small samples).
## Linear Regression for multivariate data vs High Dimensional Data
- $\mathbf{X^TX}$ and $(\mathbf{X^TX})^{-1}$ are $p \times p$ matrices
- $\mathbf{X^TX}$ can only be inverted if it has rank $p$
- Rank of a matrix of form $\mathbf{X^TX}$, with $\mathbf{X}$ and $n\times p$ matrix, can never be larger than $\min(n,p)$.
- in most regression problems $n>p$ and rank of $(\mathbf{X^TX})$ equals $p$
- in high dimensional regression problems $p >>> n$ and rank of $(\mathbf{X^TX})$ equals $n<p$
- in the toxicogenomics example $n=30<p=4000$ and $\text{rank}(\mathbf{X^TX})\leq n=30$.
$\longrightarrow$ $(\mathbf{X^TX})^{-1}$ does not exist, and neither does $\hat{\boldsymbol{\beta}}$.
## Can SVD help?
- Since the columns of $\mathbf{X}$ are centered, $\mathbf{X^TX} \propto \text{var}\left[\mathbf{X}\right]$.
- if $\text{rank}(\mathbf{X^TX})=n=30$, the PCA will give 30 components, each being a linear combination of $p=4000$ variables. These 30 PCs contain all information present in the original $\mathbf{X}$ data.
- if $\text{rank}(\mathbf{X})=n=30$, the SVD of $\mathbf{X}$ is given by
\[
\mathbf{X} = \sum_{i=1}^n \delta_i \mathbf{u}_i \mathbf{v}_i^T = \mathbf{U} \boldsymbol{\Delta} \mathbf{V}^T = \mathbf{ZV}^T,
\]
with $\mathbf{Z}$ the $n\times n$ matrix with the scores on the $n$ PCs.
- Still problematic because if we use all PCs $n=p$.
# Principal Component Regression
A principal component regression (PCR) consists of
1. transforming $p=4000$ dimensional $X$-variable to the $n=30$ dimensional $Z$-variable (PC scores). The $n$ PCs are mutually uncorrelated.
2. using the $n$ PC-variables as regressors in a linear regression model
3. performing feature selection to select the most important regressors (PC).
Feature selection is key, because we don't want to have as many regressors as there are observations in the data. This would result in zero residual degrees of freedom. (see later)
---
To keep the exposition general so that we allow for a feature selection to have taken place, I use the notation $\mathbf{U}_S$ to denote a matrix with left-singular column vectors $\mathbf{u}_i$, with $i \in {\cal{S}}$ (${\cal{S}}$ an index set referring to the PCs to be included in the regression model).
For example, suppose that a feature selection method has resulted in the selection of PCs 1, 3 and 12 for inclusion in the prediction model, then ${\cal{S}}=\{1,3,12\}$ and
\[
\mathbf{U}_S = \begin{pmatrix}
\mathbf{u}_1 & \mathbf{u}_3 & \mathbf{u}_{12}
\end{pmatrix}.
\]
---
### Example model based on first 4 PCs
```{r}
k <- 30
Uk <- svdX$u[,1:k]
Dk <- diag(svdX$d[1:k])
Zk <- Uk%*%Dk
Y <- toxData %>%
pull(BA)
m4 <- lm(Y~Zk[,1:4])
summary(m4)
```
Note:
- the intercept is estimated as zero. (Why?) The model could have been fitted as
```
m4 <- lm(Y~-1+Zk[,1:4])
```
- the PC-predictors are uncorrelated (by construction)
- first PC-predictors are not necessarily the most important predictors
- $p$-values are not very meaningful when prediction is the objective
Methods for feature selection will be discussed later.
# Ridge Regression
## Penalty
The ridge parameter estimator is defined as the parameter $\mathbf\beta$ that minimises the **penalised least squares criterion**
\[
\text{SSE}_\text{pen}=\Vert\mathbf{Y} - \mathbf{X\beta}\Vert_2^2 + \lambda \Vert \boldsymbol{\beta} \Vert_2^2
\]
- $\Vert \boldsymbol{\beta} \Vert_2^2=\sum_{j=1}^p \beta_j^2$ is the **$L_2$ penalty term**
- $\lambda>0$ is the penalty parameter (to be chosen by the user).
Note, that that is equivalent to minimizing
\[
\Vert\mathbf{Y} - \mathbf{X\beta}\Vert_2^2 \text{ subject to } \Vert \boldsymbol{\beta}\Vert^2_2\leq s
\]
Note, that $s$ has a one-to-one correspondence with $\lambda$
## Graphical interpretation
```{r echo = FALSE, warning = FALSE, message = FALSE}
library(ggforce)
library(latex2exp)
library(gridExtra)
p1 <- ggplot() +
geom_ellipse(aes(x0 = 4, y0 = 11, a = 10, b = 3, angle = pi / 4)) +
geom_ellipse(aes(x0 = 4, y0 = 11, a = 5, b = 1.5, angle = pi / 4)) +
xlim(-12.5, 12.5) +
ylim(-5, 20) +
geom_point(aes(x = 4, y = 11)) +
annotate("text", label = TeX("$(\\hat{\\beta}_1^{ols}, \\hat{\\beta}_2^{ols})$"), x = -5, y = 15, size = 6, parse = TRUE) +
xlab(TeX("$\\beta_1$")) +
ylab(TeX("$\\beta_2$")) +
geom_segment(
aes(x = -5, y = 12.5, xend = 3.7, yend = 11.3),
arrow = arrow(length = unit(0.25, "cm"))
) +
coord_fixed()
pRidge <- p1 +
geom_circle(aes(x0 = 0, y0 = 0, r = 3.9) , color = "red") +
geom_point(aes(x = -1.1, y = 3.75), color = "red") +
annotate("text", label = TeX("$(\\hat{\\beta}_1^{ridge}, \\hat{\\beta}_2^{ridge})$"), x = -8.1, y = 4.45, size = 6, parse = TRUE, color = "red") +
ggtitle("Ridge") +
geom_vline(xintercept = 0, color = "grey") +
geom_hline(yintercept = 0, color = "grey") +
theme_minimal()
pRidge
```
## Solution
The solution is given by
\[
\hat{\boldsymbol{\beta}} = (\mathbf{X^TX}+\lambda \mathbf{I})^{-1} \mathbf{X^T Y}.
\]
It can be shown that $(\mathbf{X^TX}+\lambda \mathbf{I})$ is always of rank $p$ if $\lambda>0$.
Hence, $(\mathbf{X^TX}+\lambda \mathbf{I})$ is invertible and $\hat{\boldsymbol{\beta}}$ exists even if $p>>>n$.
We also find
\[
\text{var}\left[\hat{\mathbf\beta}\right] = (\mathbf{X^TX}+\lambda \mathbf{I})^{-1} \mathbf{X}^T\mathbf{X} (\mathbf{X^TX}+\lambda \mathbf{I})^{-1}\sigma^2
\]
However, it can be shown that improved intervals that also account for the bias can be constructed by using:
\[
\text{var}\left[\hat{\mathbf\beta}\right] = (\mathbf{X^TX}+\lambda \mathbf{I})^{-1} \sigma^2.
\]
### Proof
The criterion to be minimised is
\[
\text{SSE}_\text{pen}=\Vert\mathbf{Y} - \mathbf{X\beta}\Vert_2^2 + \lambda \Vert \boldsymbol{\beta} \Vert_2^2.
\]
First we re-express SSE in matrix notation:
\[
\text{SSE}_\text{pen} = (\mathbf{Y}-\mathbf{X\beta})^T(\mathbf{Y}-\mathbf{X\beta}) + \lambda \boldsymbol{\beta}^T\boldsymbol{\beta}.
\]
The partial derivative w.r.t. $\boldsymbol{\beta}$ is
\[
\frac{\partial}{\partial \boldsymbol{\beta}}\text{SSE}_\text{pen} = -2\mathbf{X}^T(\mathbf{Y}-\mathbf{X\beta})+2\lambda\boldsymbol{\beta}.
\]
Solving $\frac{\partial}{\partial \boldsymbol{\beta}}\text{SSE}_\text{pen}=0$ gives
\[
\hat{\boldsymbol{\beta}} = (\mathbf{X^TX}+\lambda \mathbf{I})^{-1} \mathbf{X^T Y}.
\]
(assumption: $(\mathbf{X^TX}+\lambda \mathbf{I})$ is of rank $p$. This is always true if $\lambda>0$)
## Link with SVD
### SVD and inverse
Write the SVD of $\mathbf{X}$ ($p>n$) as
\[
\mathbf{X} = \sum_{i=1}^n \delta_i \mathbf{u}_i \mathbf{v}_i^T = \sum_{i=1}^p \delta_i \mathbf{u}_i \mathbf{v}_i^T = \mathbf{U}\boldsymbol{\Delta} \mathbf{V}^T ,
\]
with
- $\delta_{n+1}=\delta_{n+2}= \cdots = \delta_p=0$
- $\boldsymbol{\Delta}$ a $p\times p$ diagonal matrix of the $\delta_1,\ldots, \delta_p$
- $\mathbf{U}$ an $n\times p$ matrix and $\mathbf{V}$ a $p \times p$ matrix. Note that only the first $n$ columns of $\mathbf{U}$ and $\mathbf{V}$ are informative.
With the SVD of $\mathbf{X}$ we write
\[
\mathbf{X}^T\mathbf{X} = \mathbf{V}\boldsymbol{\Delta
}^2\mathbf{V}^T.
\]
The inverse of $\mathbf{X}^T\mathbf{X}$ is then given by
\[
(\mathbf{X}^T\mathbf{X})^{-1} = \mathbf{V}\boldsymbol{\Delta}^{-2}\mathbf{V}^T.
\]
Since $\boldsymbol{\Delta}$ has $\delta_{n+1}=\delta_{n+2}= \cdots = \delta_p=0$, it is not invertible.
### SVD of penalised matrix $\mathbf{X^TX}+\lambda \mathbf{I}$
It can be shown that
\[
\mathbf{X^TX}+\lambda \mathbf{I} = \mathbf{V} (\boldsymbol{\Delta}^2+\lambda \mathbf{I}) \mathbf{V}^T ,
\]
i.e. adding a constant to the diagonal elements does not affect the eigenvectors, and all eigenvalues are increased by this constant.
$\longrightarrow$ zero eigenvalues become $\lambda$.
Hence,
\[
(\mathbf{X^TX}+\lambda \mathbf{I})^{-1} = \mathbf{V} (\boldsymbol{\Delta}^2+\lambda \mathbf{I})^{-1} \mathbf{V}^T ,
\]
which can be computed even when some eigenvalues in $\boldsymbol{\Delta}^2$ are zero.
Note, that for high dimensional data ($p>>>n$) many eigenvalues are zero because $\mathbf{X^TX}$ is a $p \times p$ matrix and has rank $n$.
The identity $\mathbf{X^TX}+\lambda \mathbf{I} = \mathbf{V} (\boldsymbol{\Delta}^2+\lambda \mathbf{I}) \mathbf{V}^T$ is easily checked:
\[
\mathbf{V} (\boldsymbol{\Delta}^2+\lambda \mathbf{I}) \mathbf{V}^T = \mathbf{V}\boldsymbol{\Delta}^2\mathbf{V}^T + \lambda \mathbf{VV}^T = \mathbf{V}\boldsymbol{\Delta}^2\mathbf{V}^T + \lambda \mathbf{I} = \mathbf{X^TX}+\lambda \mathbf{I}.
\]
## Properties
- The Ridge estimator is biased! The $\boldsymbol{\beta}$ are shrunken to zero!
\begin{eqnarray}
\text{E}[\hat{\boldsymbol{\beta}}] &=& (\mathbf{X^TX}+\lambda \mathbf{I})^{-1} \mathbf{X}^T \text{E}[\mathbf{Y}]\\
&=& (\mathbf{X}^T\mathbf{X}+\lambda \mathbf{I})^{-1} \mathbf{X}^T \mathbf{X}\boldsymbol{\beta}\\
\end{eqnarray}
- Note, that the shrinkage is larger in the direction of the smaller eigenvalues.
\begin{eqnarray}
\text{E}[\hat{\boldsymbol{\beta}}]&=&\mathbf{V} (\boldsymbol{\Delta}^2+\lambda \mathbf{I})^{-1} \mathbf{V}^T \mathbf{V} \boldsymbol{\Delta}^2 \mathbf{V}^T\boldsymbol{\beta}\\
&=&\mathbf{V} (\boldsymbol{\Delta}^2+\lambda \mathbf{I})^{-1} \boldsymbol{\Delta}^2 \mathbf{V}^T\boldsymbol{\beta}\\
&=& \mathbf{V}
\left[\begin{array}{ccc}
\frac{\delta_1^2}{\delta_1^2+\lambda}&\ldots&0 \\
&\vdots&\\
0&\ldots&\frac{\delta_r^2}{\delta_r^2+\lambda}
\end{array}\right]
\mathbf{V}^T\boldsymbol{\beta}
\end{eqnarray}
- the variance of the prediction $\hat{{Y}}(\mathbf{x})=\mathbf{x}^T\hat\beta$,
\[
\text{var}\left[\hat{{Y}}(\mathbf{x})\mid \mathbf{x}\right] = \mathbf{x}^T(\mathbf{X^TX}+\lambda \mathbf{I})^{-1}\mathbf{x}
\]
is smaller than with the least-squares estimator.
- through the bias-variance trade-off it is hoped that better predictions in terms of expected conditional test error can be obtained, for an appropriate choice of $\lambda$.
Recall the expression of the expected conditional test error
\begin{eqnarray}
Err(\mathbf{x}) &=& \text{E}\left[(\hat{Y} - Y^*)^2\mid \mathbf{x}\right]\\
&=&
\text{var}\left[\hat{Y}\mid \mathbf{x}\right] + \text{bias}^2(\mathbf{x})+
\text{var}\left[Y^*\mid \mathbf{x}\right]
\end{eqnarray}
where
- $\hat{Y}=\hat{Y}(\mathbf{x})=\mathbf{x}^T\hat{\boldsymbol{\beta}}$ is the prediction at $\mathbf{x}$
- $Y^*$ is an outcome at predictor $\mathbf{x}$
- $\mu(\mathbf{x}) = \text{E}\left[\hat{Y}\mid \mathbf{x}\right] \text{ and } \mu^*(x)=\text{E}\left[Y^*\mid \mathbf{x}\right]$
- $\text{bias}(\mathbf{x})=\mu(\mathbf{x})-\mu^*(\mathbf{x})$
- $\text{var}\left[Y^*\mid \mathbf{x}\right]$ the irreducible error that does not depend on the model. It simply originates from observations that randomly fluctuate around the true mean $\mu^*(x)$.
## Toxicogenomics example
```{r}
library(glmnet)
mRidge <- glmnet(
x = toxData[,-1] %>%
as.matrix,
y = toxData %>%
pull(BA),
alpha = 0) # ridge: alpha = 0
plot(mRidge, xvar="lambda")
```
The R function \textsf{glmnet} uses \textsf{lambda} to refer to the penalty parameter. In this course we use $\lambda$, because $\lambda$ is often used as eigenvalues.
The graph shows that with increasing penalty parameter, the parameter estimates are shrunken towards zero. The estimates will only reach zero for $\lambda \rightarrow \infty$. The stronger the shrinkage, the larger the bias (towards zero) and the smaller the variance of the parameter estimators (and hence also smaller variance of the predictions).
Another (informal) viewpoint is the following. By shrinking the estimates towards zero, the estimates loose some of their ``degrees of freedom'' so that the parameters become estimable with only $n<p$ data points. Even with a very small $\lambda>0$, the parameters regain their estimability. However, note that the variance of the estimator is given by
\[
\text{var}\left[\hat{\mathbf\beta}\right] = (\mathbf{X^TX}+\lambda \mathbf{I})^{-1} \sigma^2 = \mathbf{V}(\boldsymbol{\Delta}^2+\lambda\mathbf{I})^{-1}\mathbf{V}^T\sigma^2.
\]
Hence, a small $\lambda$ will result in large variances of the parameter estimators. The larger $\lambda$, the smaller the variances become. In the limit, as $\lambda\rightarrow\infty$, the estimates are converged to zero and show no variability any longer.
# Lasso Regression
- The Lasso is another example of penalised regression.
- The lasso estimator of $\boldsymbol{\beta}$ is the solution to minimising the penalised SSE
\[
\text{SSE}_\text{pen} = \sum_{i=1}^n (Y_i - \mathbf{x}_i^T\boldsymbol{\beta})^2 + \lambda \sum_{j=1}^p \vert \beta_j\vert.
\]
or, equivalently, minimising
\[
\text{SSE} = \Vert \mathbf{Y} - \mathbf{X\beta}\Vert_2^2 \text{ subject to } \Vert \mathbf\beta\Vert_1 \leq c
\]
with
- $\Vert \mathbf\beta\Vert_1 = \sum\limits_{j=1}^p \vert \beta_j \vert$
- Despite strong similarity between ridge and lasso regression ($L_2$ versus $L_1$ norm in penalty term), there is no analytical solution of the lasso parameter estimate of $\mathbf\beta$.
- Fortunately, computational efficient algorithms have been implemented in statistical software
- The Lasso estimator of $\boldsymbol{\beta}$ is biased and generally has a smaller variance then the least-squares estimator.
- Hence, the bias-variance trade-off may here also help in finding better predictions with biased estimators.
- In contrast to ridge regression, however, the lasso estimator can give at most $\min(p,n)$ non-zero $\beta$-estimates.
- Hence, at first sight the lasso is not directly appropriate for high-dimensional settings.
- An important advantage of the lasso is that choosing an appropriate value for $\lambda$ is a kind a model building or feature selection procedure (see further).
## Graphical interpretation of Lasso vs ridge
Note that the lasso is a constrained regression problem with
\[
\Vert \mathbf{Y} - \mathbf{X\beta}\Vert_2^2 \text{ subject to } \Vert \mathbf\beta\Vert_1 \leq c
\]
and ridge
\[
\Vert \mathbf{Y} - \mathbf{X\beta}\Vert_2^2 \text{ subject to } \Vert \mathbf\beta\Vert^2_2 \leq c
\]
```{r echo = FALSE, warning = FALSE, message = FALSE}
pLasso <- p1 +
geom_segment(aes(x = 0, y = 4.2 , xend = 4.2, yend = 0), color = "red") +
geom_segment(aes(x = 0, y = 4.2 , xend = - 4.2, yend = 0), color = "red") +
geom_segment(aes(x = 4.2, y = 0 , xend = 0, yend = -4.2), color = "red") +
geom_segment(aes(x = 0, y = - 4.2 , xend = - 4.2, yend = 0), color = "red") +
geom_point(aes(x = 0, y = 4.2), color = "red") +
annotate("text", label = TeX("$(\\hat{\\beta}_1^{lasso}, \\hat{\\beta}_2^{lasso})$"), x = 7, y = 4.2, size = 6, parse = TRUE, color = "red") +
ggtitle("Lasso") +
geom_vline(xintercept = 0, color = "grey") +
geom_hline(yintercept = 0, color = "grey") +
theme_minimal()
grid.arrange(pLasso, pRidge, ncol = 2)
```
Note, that
- parameters for the lasso can never switch sign, they are set at zero! Selection!
- ridge regression can lead to parameters that switch sign.
## Toxicogenomics example
```{r}
mLasso <- glmnet(
x = toxData[,-1] %>%
as.matrix,
y = toxData %>%
pull(BA),
alpha = 1)
plot(mLasso, xvar = "lambda")
```
- The graph with the paths of the parameter estimates nicely illustrates the typical behaviour of the lasso estimates as a function of $\lambda$: when $\lambda$ increases the estimates are shrunken towards zero.
- When an estimate hits zero, it remains exactly equal to zero when $\gamma$ further increases. A parameter estimate equal to zero, say $\hat\beta_j=0$, implies that the corresponding predictor $x_j$ is no longer included in the model (i.e. $\beta_jx_j=0$).
- The model fit is known as a sparse model fit (many zeroes). Hence, choosing a appropriate value for $\gamma$ is like choosing the important predictors in the model (feature selection).
# Splines and the connection to ridge regression.
## Lidar dataset
- LIDAR (light detection and ranging) uses the reflection of laser-emitted light to detect chemical compounds in the atmosphere.
- The LIDAR technique has proven to be an efficient tool for monitoring the distribution of several atmospheric pollutants of importance; see Sigrist (1994).
- The range is the distance traveled before the light is reflected back to its source.
- The logratio is the logarithm of the ratio of received light from two laser sources.
- One source had a frequency equal to the resonance frequency of the compound of interest, which was mercury in this study.
- The other source had a frequency off this resonance frequency.
- The concentration of mercury can be derived from a regression model of the logratio in function of the range for each range x.
```{r}
library("SemiPar")
data(lidar)
pLidar <- lidar %>%
ggplot(aes(x = range, y = logratio)) +
geom_point() +
xlab("range (m)")
pLidar +
geom_smooth()
```
- The data is non-linear
- Linear regression will not work!
- The data shows a smooth relation between the logratio and the range
## Basis expansion
\[y_i=f(x_i)+\epsilon_i,\]
with
\[f(x)=\sum\limits_{k=1}^K \theta_k b_k(x)\]
- Select set of basis functions $b_k(x)$
- Select number of basis functions $K$
- Examples
- Polynomial model: $x^k$
- Orthogonal series: Fourier, Legendre polynomials, Wavelets
- Polynomial splines: $1, x, (x-t_m)_+$ with $m=1, \ldots, K-2$ knots $t_m$
- ...
### Trunctated line basis
\[y_i=f(x_i)+\epsilon_i,\]
- One of the most simple basis expansions
- $f(x_i)=\beta_0+\beta_1x_i+\sum\limits_{m=1}^{K-2}\theta_m(x_i-t_m)_+$ with $(.)_+$ the operator that takes the positive part.
- Note, that better basis expansions exist, which are orthogonal, computational more stable and/or continuous derivative beyond first order
- We will use this basis for didactical purposes
- We can use OLS to fit y w.r.t. the basis.
```{r}
knots <- seq(400,700,12.5)
basis <- sapply(knots,
function(k,y) (y-k)*(y>k),
y= lidar %>% pull(range)
)
basisExp <- cbind(1, range = lidar %>% pull(range), basis)
splineFitLs <- lm(logratio ~ -1 + basisExp, lidar)
pBasis <- basisExp[,-1] %>%
data.frame %>%
gather("basis","values",-1) %>%
ggplot(aes(x = range, y = values, color = basis)) +
geom_line() +
theme(legend.position="none") +
ylab("basis")
grid.arrange(
pLidar +
geom_line(aes(x = lidar$range, y = splineFitLs$fitted), lwd = 2),
pBasis,
ncol=1)
```
- Note, that the model is overfitting!
- The fit is very wiggly and is tuned too much to the data.
- The fit has a large variance and low bias.
- It will therefore not generalise well to predict the logratio of future observations.
#### Solution for overfitting?
- We could perform model selection on the basis to select the important basis functions to model the signal. But, this will have the undesired property that the fit will no longer be smooth.
- We can also adopt a ridge penalty!
- However, we do not want to penalise the intercept and the linear term.
- Ridge criterion
\[\Vert\mathbf{Y}-\mathbf{X\beta}\Vert^2+\lambda\boldsymbol{\beta}^T\mathbf{D}\boldsymbol{\beta}
\]
With $\mathbf{D}$ with dimensions (K,K): $\mathbf{D}=\left[\begin{array}{cc}\mathbf{0}_{2\times2}& \mathbf{0}_{2\times K-2}\\
\mathbf{0}_{K-2\times2}&\mathbf{I}_{K-2\times K-2}\end{array}\right]$
- Here we will set the penalty at 900.
```{r}
D <- diag(ncol(basisExp))
D[1:2,1:2] <- 0
lambda <- 900
betaRidge <- solve(t(basisExp)%*%basisExp+(lambda*D))%*%t(basisExp)%*%lidar$logratio
grid.arrange(
pLidar +
geom_line(aes(x = lidar$range, y = c(basisExp %*% betaRidge)), lwd = 2),
pBasis,
ncol=1)
```
How do we choose $\lambda$?
---
# Evaluation of Prediction Models
Predictions are calculated with the fitted model
\[
\hat{Y}(\mathbf{x}) = \hat{m}(\mathbf{x})=\mathbf{x}^T\hat{\beta}
\]
when focussing on prediction, we want the prediction error to be as small as possible.
The **prediction error** for a prediction at covariate pattern $\mathbf{x}$ is given by
\[
\hat{Y}(\mathbf{x}) - Y^*,
\]
where
- $\hat{Y}(\mathbf{x})=\mathbf{x}^T\hat{\boldsymbol{\beta}}$ is the prediction at $\mathbf{x}$
- $Y^*$ is an outcome at covariate pattern $\mathbf{x}$
Prediction is typically used to predict an outcome before it is observed.
- Hence, the outcome $Y^*$ is not observed yet, and
- the prediction error cannot be computed.
---
- Recall that the prediction model $\hat{Y}(\mathbf{x})$ is estimated by using data in the training data set $(\mathbf{X},\mathbf{Y})$, and
- that the outcome $Y^*$ is an outcome at $\mathbf{x}$ which is assumed to be independent of the training data.
- Goal is to use prediction model for predicting a future observation ($Y^*$), i.e. an observation that still has to be realised/observed (otherwise prediction seems rather useless).
- Hence, $Y^*$ can never be part of the training data set.
---
Here we provide definitions and we show how the prediction performance of a prediction model can be evaluated from data.
Let ${\cal{T}}=(\mathbf{Y},\mathbf{X})$ denote the training data, from which the prediction model $\hat{Y}(\cdot)$ is build. This building process typically involves feature selection and parameter estimation.
We will use a more general notation for the prediction model: $\hat{m}(\mathbf{x})=\hat{Y}(\mathbf{x})$.
---
## Test or Generalisation Error
The test or generalisation error for prediction model $\hat{m}(\cdot)$ is given by
\[
\text{Err}_{\cal{T}} = \text{E}_{Y^*,X^*}\left[(\hat{m}(\mathbf{X}^*) - Y^*)^2\mid {\cal{T}}\right]
\]
where $(Y^*,X^*)$ is independent of the training data.
---
- Note that the test error is conditional on the training data ${\cal{T}}$.
- Hence, the test error evaluates the performance of the single model build from the observed training data.
- This is the ultimate target of the model assessment, because it is exactly this prediction model that will be used in practice and applied to future predictors $\mathbf{X}^*$ to predict $Y^*$.
- The test error is defined as an average over all such future observations $(Y^*,\mathbf{X}^*)$.
---
## Conditional test error
Sometimes the conditional test error is used:
The conditional test error in $\mathbf{x}$ for prediction model $\hat{m}(\mathbf{x})$ is given by
\[
\text{Err}_{\cal{T}}(\mathbf{x}) = \text{E}_{Y^*}\left[(\hat{m}(\mathbf{x}) - Y^*)^2\mid {\cal{T}}, \mathbf{x}\right]
\]
where $Y^*$ is an outcome at predictor $\mathbf{x}$, independent of the training data.
Hence,
\[
\text{Err}_{\cal{T}} = \text{E}_{X^*}\left[\text{Err}_{\cal{T}}(\mathbf{X}^*)\right].
\]
A closely related error is the **insample error**.
---
## Insample Error
The insample error for prediction model $\hat{m}(\mathbf{x})$ is given by
\[
\text{Err}_{\text{in} \cal{T}} = \frac{1}{n}\sum_{i=1}^n \text{Err}_{\cal{T}}(\mathbf{x}_i),
\]
i.e. the insample error is the sample average of the conditional test errors evaluated in the $n$ training dataset predictors $\mathbf{x}_i$.
Since $\text{Err}_{\cal{T}}$ is an average over all $\mathbf{X}$, even over those predictors not observed in the training dataset, it is sometimes referred to as the **outsample error**.
---
## Estimation of the insample error
We start with introducing the training error rate, which is closely related to the MSE in linear models.
### Training error
The training error is given by
\[
\overline{\text{err}} = \frac{1}{n}\sum_{i=1}^n (Y_i - \hat{m}(\mathbf{x}_i))^2 ,
\]
where the $(Y_i,\mathbf{x}_i)$ from the training dataset which is also used for the calculation of $\hat{m}$.
- The training error is an overly optimistic estimate of the test error $\text{Err}_{\cal{T}}$.
- The training error will never increases when the model becomes more complex. $\longrightarrow$ cannot be used directly as a model selection criterion.
Indeed, model parameters are often estimated by minimising the training error (cfr. SSE).
- Hence the fitted model adapts to the training data, and
- training error will be an overly optimistic estimate of the test error $\text{Err}_{\cal{T}}$.
---
It can be shown that the training error is related to the insample test error via
\[
\text{E}_\mathbf{Y}
\left[\text{Err}_{\text{in}{\cal{T}}}\right] = \text{E}_\mathbf{Y}\left[\overline{\text{err}}\right] + \frac{2}{n}\sum_{i=1}^n \text{cov}_\mathbf{Y}\left[\hat{m}(\mathbf{x}_i),Y_i\right],
\]
Note, that for linear models
\[ \hat{m}(\mathbf{x}_i) = \mathbf{X}\hat{\boldsymbol{\beta}}= \mathbf{X}(\mathbf{X}^T\mathbf{X})^{-1}\mathbf{X}^T\mathbf{Y} = \mathbf{HY}
\]
with
- $\mathbf{H}$ the hat matrix and
- all $Y_i$ are assumed to be independently distributed $N(\mathbf{X}\boldsymbol{\beta},\sigma^2)$
Hence, for linear models with independent observations
\begin{eqnarray}
\text{cov}_\mathbf{Y}\left[\hat{m}(\mathbf{x}_i),Y_i)\right] &=&
\text{cov}_\mathbf{Y}\left[\mathbf{H}_{i}^T\mathbf{Y},Y_i)\right]\\
&=& \text{cov}_\mathbf{Y}\left[h_{ii} Y_i,Y_i\right]\\
&=& h_{ii} \text{cov}_\mathbf{Y}\left[Y_i,Y_i\right]\\
&=& h_{ii} \sigma^2\\
\end{eqnarray}
And we can thus estimate the insample error by Mallow's $C_p$
\begin{eqnarray}
C_p &=& \overline{\text{err}} + \frac{2\sigma^2}{n}\text{tr}(\mathbf{H})\\
&=& \overline{\text{err}} + \frac{2\sigma^2p}{n}
\end{eqnarray}
with $p$ the number of predictors.
- Mallow's $C_p$ is often used for model selection.
- Note, that we can also consider it as a kind of penalized least squares:
\[
n \times C_p = \Vert \mathbf{Y} - \mathbf{X}\boldsymbol{\beta}\Vert_2^2 + 2\sigma^2 \Vert \boldsymbol{\beta} \Vert_0
\]
with $L_0$ norm $\Vert \boldsymbol{\beta} \Vert_0 = \sum_{j=1}^p \beta_p^0 = p$.
---
## Expected test error