generated from statOmics/Rmd-website
-
Notifications
You must be signed in to change notification settings - Fork 0
/
svd.Rmd
executable file
·2208 lines (1683 loc) · 73.4 KB
/
svd.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: "2. Singular Value Decomposition"
author: "Lieven Clement"
date: "statOmics, Ghent University (https://statomics.github.io)"
output:
pdf_document:
toc: true
number_sections: true
latex_engine: xelatex
---
# Introduction
## Motivation
The SVD is one of the most well used and general purpose tools from linear algebra for data processing!
Methodologically
- Dimension reduction (e.g. images, gene expression data, movie preferences)
- Used as a first step in many data reduction and machine learning approaches
- Taylor a coordinate system driven by the data
- Solve system of linear equations for non-square matrices: e.g. linear regression
- Basis for principal component analysis (PCA) and multidimensional scaling (MDS).
- PCA is one of the most widely used methods to study high dimensional data and to understand them in terms of their dominant patterns and correlations
Applications:
- At the heart of search engines: Google
- Basis of many facial recognition methods: e.g. Facebook
- Recommender systems such as Amazon and Netflix
- A standard tool for data exploration and dimension reduction in Genomics
## Disclaimer
When you want to run the script you will have to comment out the eval=FALSE statement in some R chunks. Because the SVD takes a while on the faces example we save the svd for later use. So you have to comment the eval=FALSE statement in this chunk when you run the script for the first time.
## Data
- Extended Yale Face Database B
- Cropped and aligned images of 38 individuals under 64 lighting conditions.
- Each image is 192 pixels tall and 168 pixels wide.
- Each of the facial images in our library will be reshaped into a large vector with 192 × 168 = 32 256 elements.
- We will use the 64 images of 36 people to build our models
```{r libraries, message=FALSE, warning=FALSE, silent=TRUE}
library(pixmap)
library(tidyverse)
library(gridExtra)
library(grid)
library(ggmap)
library(downloader)
library(imager)
```
```{r download-data, warning=FALSE, message=FALSE}
## Download and unzip data
if(!dir.exists("raw-data")) dir.create("raw-data")
download(
"https://github.com/statOmics/HDA2020/raw/data/yalefaces_cropped.zip",
destfile = "raw-data/yalefaces_cropped.zip", mode = "wb", quiet = TRUE
)
unzip ("raw-data/yalefaces_cropped.zip", exdir = "./raw-data")
dir <- "./raw-data/CroppedYale"
```
```{r, warning=FALSE}
people <- list.files(dir)
people2 <- sapply(people,
function(x) list.files(
paste0(dir,"/",x),
full.names=TRUE
)
)
facesList <- lapply(people2, function(x) read.pnm(x))
grid.arrange(
grobs=lapply(facesList[1+(0:35)*64],
function(x) getChannels(x) %>%
ggimage(.,coord_equal=TRUE)
),
ncol=6)
```
## Method
Let $\mathbf{X}$ be an $n\times p$ matrix e.g.
- gene expression of $p=40 000$ genes for $n=30$ subjects
- n = 100 000 000 webpages indexed with p search terms, or
- $n$ images each stored as a $p=32 256$ vector with the intensity of each pixel
<!-- Need "emo" package for emojis, install with -->
<!-- `devtools::install_github("hadley/emo")` -->
__Note:__ the emoji characters will not be visible in the PDF output.
\[X=
\left[\begin{array}{ccc}
-&\mathbf{x}_{1}^T &- \\
\vdots&\vdots&\vdots\\
-&\mathbf{x}_{i}^T &- \\
\vdots&\vdots&\vdots\\
-&\mathbf{x}_{n}^T &- \\
\end{array}\right]_{n \times p}
\begin{array}{c}
`r set.seed(1);emo::ji("beauty")`\\\\
`r set.seed(1);emo::ji("cop")`\\
\\
`r set.seed(1);emo::ji("blonde")`\\
\end{array}
\]
The data matrix $\mathbf{X}$ can be decomposed with the SVD into 3 matrices:
\[
\mathbf{X}=\mathbf{U}_{n\times n}\boldsymbol{\Delta}_{n\times p}\mathbf{V}^T_{p \times p}
\]
- an orthonormal matrix $\mathbf{U}_{n\times n}$ with left singular vectors: $\mathbf{u}_j^T \mathbf{u}_k=1$ if $k=j$ and $\mathbf{u}_j^T \mathbf{u}_k=0$ if $j\neq k$, i.e.
\[ \mathbf{U}^T\mathbf{U}=\mathbf{I}\]
- a matrix $\boldsymbol{\Delta}_{n\times p}$ with only singular values: the singular values $\delta_i$ are the only non-zero elements of the matrix and are on the diagonal element $[\boldsymbol{\Delta}]_{ii}$. They are also organised so that $\delta_1 > \delta_2 > \ldots > \delta_r$.
- an orthonormal matrix $\mathbf{V}_{p\times p}$ with right singular vectors: $\mathbf{v}_j^T \mathbf{v}_k=1$ if $k=j$ and $\mathbf{v}_j^T \mathbf{v}_k=0$ if $j\neq k$ otherwise, i.e.
\[ \mathbf{V}^T\mathbf{V}=\mathbf{I}\]
Note, that there are only $r$ non-zero singular values, with $r$ the rank of matrix $X$: $r \leq \text{min}(n,p)$. So we have $k=1 \ldots r$ non-zero singular values. Hence, we can also rewrite the approximation by restricting us to the rank of matrix $\mathbf{X}$. Indeed, the n times p matrix $\boldsymbol\Delta$ only contains $r$ non-zero diagonal elements!
- So
\[
\mathbf{X}=\mathbf{U}_{n\times r}\boldsymbol{\Delta}_{r\times r}\mathbf{V}^T_{p \times r}
\]
\[
\left[\begin{array}{ccc}
-&\mathbf{x}_{1}^T &- \\
\vdots&\vdots&\vdots\\
-&\mathbf{x}_{i}^T &- \\
\vdots&\vdots&\vdots\\
-&\mathbf{x}_{n}^T &- \\
\end{array}\right]_{n \times p}
=
\left[\begin{array}{ccc}
\mid&&\mid\\
\mathbf{u}_1&\ldots&\mathbf{u}_r\\
\mid&&\mid
\end{array}\right]_{n \times r}
\left[\begin{array}{ccc}
\delta_1\\
&\ddots&\\
&&\delta_r\\
\end{array}\right]_{r \times r}
\left[\begin{array}{ccc}
\mid&&\mid\\
\mathbf{v}_1&\ldots&\mathbf{v}_r\\
\mid&&\mid\\
\end{array}
\right]^T_{p \times r}
\]
Also note that
\[
\mathbf{V}^T=\left[\begin{array}{ccc}
-&\mathbf{v}_{1}^T &- \\
\vdots&\vdots&\vdots\\
-&\mathbf{v}_{r}^T &- \\
\end{array}\right]_{r \times p}
\]
- For high dimensional data $p>>>n$ $\rightarrow$ $\text{max}(r)=n$ and
- equivalently for multivariate data with $n>p$ $\rightarrow$ $\text{max}(r)=p$
We can also rewrite the decomposition using the properties of matrix multiplication
\begin{eqnarray}
\mathbf{X} &=& \delta_1\left[
\begin{array}{c}
\mid\\
\mathbf{u}_1\\
\mid
\end{array}
\right]
\begin{array}{c}
\left[
\begin{array}{ccc}
-&
\mathbf{v}_1^T&
-
\end{array}
\right]\\\quad\\\quad
\end{array}
+ \ldots +
\delta_r\left[
\begin{array}{c}
\mid\\
\mathbf{u}_r\\
\mid
\end{array}
\right]
\begin{array}{c}
\left[
\begin{array}{ccc}
-&
\mathbf{v}_r^T&
-
\end{array}
\right]\\\quad\\\quad
\end{array}\\
\mathbf{X} &=& \sum_{k=1}^r \delta_k\mathbf{u}_k\mathbf{v}_k^T
\end{eqnarray}
- Because both $\mathbf{U}$ and $\mathbf{V}$ are orthonormal all their $r$ vectors are having unit length and they are thus reshaped by the singular values.
- Hence, the singular values determine the importance of the rank one matrices $\delta_k\mathbf{u}_k\mathbf{v}_k^T$ in the reconstruction of the matrix $\mathbf{X}$ and they are ordered so that $\delta_1 > \ldots > \delta_r$.
Note, that for symmetric matrices $\mathbf{X}$ $\longrightarrow$ $\mathbf{U} = \mathbf{V}$.
## Interpretation of singular vectors: face example
### Convert images to vectors
1. Convert images to vectors and store them as a matrix
- We use an `sapply` loop to loop over all faces
- We extract the grey intensities from the pictures
- We convert the matrix in a long skinny vector (`c`)
- We transpose the resulting matrix from sapply
```{r}
allFacesMx <- sapply(facesList,
function(x)
getChannels(x) %>% c
) %>% t
dim(allFacesMx)
```
Save memory by removing facesList object
```
rm(facesList)
gc()
```
Hence we obtain a matrix for n = `r nrow(allFacesMx)` images with p = `r ncol(allFacesMx)` intensities for each pixel of an image.
Before we do the svd we typically center the data by substracting the average of the columns, i.e. the average face.
We will only work with the first 36 people: $n = 36 \times 64 = `r 36*64`$ pictures.
```{r}
allFacesCenteredMx <- allFacesMx[1:(36*64),]
meanFace <- colMeans(allFacesCenteredMx)
allFacesMxCentered <- allFacesCenteredMx -
matrix(1, nrow=nrow(allFacesCenteredMx), ncol=1) %*% matrix(meanFace,nrow=1)
```
### Visualisation of mean image
```{r}
plotFaceVector <- function(faceVector,nrow=192,ncol=168) {
matrix(faceVector,nrow=nrow,ncol=ncol) %>%
ggimage()
}
meanFace %>%
plotFaceVector
```
### SVD
#### Perform SVD in R
1. We adopt svd on the centered matrix
2. We cache the result because the calculation takes 10 minutes.
```{r run-SVD, cache=TRUE}
faceSvd <- svd(allFacesMxCentered)
```
<!-- ```{r, eval=FALSE} -->
<!-- ## Run this code manually to store the SVD for later re-use -->
<!-- saveRDS(faceSvd, file = "faceSvd.rds") -->
<!-- ``` -->
<!-- ```{r, eval=FALSE} -->
<!-- ## Run this code manually to reload the SVD result -->
<!-- faceSvd <- readRDS("faceSvd.rds") -->
<!-- ``` -->
#### SVD
Dimensions of $\mathbf{U}$, $\mathbf{V}$?
```{r}
n <- nrow(allFacesCenteredMx)
p <- ncol(allFacesCenteredMx)
dim(faceSvd$u)
dim(faceSvd$v)
```
Indeed, for the face example $n<p$ so $r=n$
Check orthogonality?
We do not do it for all vectors because it takes too long.
First left eigen vector and second left eigenvector.
Happens in $\mathbf{U}^T\mathbf{U}$
```{r}
t(faceSvd$u[,1])%*%faceSvd$u[,1]
t(faceSvd$u[,1])%*%faceSvd$u[,2]
t(faceSvd$u[,2])%*%faceSvd$u[,2]
```
So we see that the left eigenvectors are orthonormal.
We check if it also holds for the rows i.e. $\mathbf{U}\mathbf{U}^T$
```{r}
t(faceSvd$u[1,])%*%faceSvd$u[1,]
t(faceSvd$u[2,])%*%faceSvd$u[1,]
t(faceSvd$u[2,])%*%faceSvd$u[2,]
```
We also see that the rows of $\mathbf{U}$ are orthonormal.
```{r}
t(faceSvd$v[,1])%*%faceSvd$v[,1]
t(faceSvd$v[,1])%*%faceSvd$v[,2]
t(faceSvd$v[,2])%*%faceSvd$v[,2]
```
So we see that the right eigenvectors are orthonormal.
```{r}
t(faceSvd$v[1,])%*%faceSvd$v[1,]
t(faceSvd$v[1,])%*%faceSvd$v[2,]
t(faceSvd$v[2,])%*%faceSvd$v[2,]
```
This, however does not hold for the rows of $\mathbf{V}$.
This is because the matrix $\mathbf{V}$ no longer is a square matrix! $r=n$ and $r<p$!
#### Visualize right eigenvectors $\mathbf{V}$
```{r}
grid.arrange(
grobs=apply(
faceSvd$v[,1:36],
2,
plotFaceVector
)
)
```
- Hence, the right singular vectors (in $\mathbf{V}$ of $\mathbf{X}=\mathbf{U}\boldsymbol{\Delta}\mathbf{V}$) are also faces and we can thus reconstruct the original faces by linear combinations of the eigen faces.
- The first eigen faces are most important to capture overall patterns in the matrix.
- Here it are mainly characteristics and shadows that are important for all faces.
- From eigen face 5 onwards we start to see specific features.
- In this case: $n < p$, so $r = n$.
\[
\mathbf{X}_{n\times p}=\mathbf{U}_{n \times n}\boldsymbol{\Delta}_{n\times n}\mathbf{V}_{p\times n}^T
\]
\[
\begin{array}{ccccc}
\left[\begin{array}{ccc}
-&\mathbf{x}_{1}^T &- \\
\vdots&\vdots&\vdots\\
-&\mathbf{x}_{i}^T &- \\
\vdots&\vdots&\vdots\\
-&\mathbf{x}_{n}^T &- \\
\end{array}\right]_{n \times p}
\begin{array}{c}
`r set.seed(1);emo::ji("beauty")`\\\\
`r set.seed(1);emo::ji("cop")`\\
\\
`r set.seed(1);emo::ji("blonde")`\\
\end{array}
&=&
\begin{array}{c}
\quad\\
\left[\begin{array}{ccc}
\mid&&\mid\\
\mathbf{u}_1&\ldots&\mathbf{u}_n\\
\mid&&\mid
\end{array}\right]_{n \times n}\\
\quad \\
\end{array}
\begin{array}{c}
\quad\\
\left[\begin{array}{ccc}
\delta_1\\
&\ddots&\\
&&\delta_n\\
\end{array}\right]_{n \times n}\\
\quad\\
\end{array}
\begin{array}{c}
\quad
\left[\begin{array}{ccc}
\mid&&\mid\\
\mathbf{v}_1&\ldots&\mathbf{v}_n\\
\mid&&\mid\\
\end{array}
\right]^T_{p \times n}\\
\begin{array}{ccc}
`r set.seed(1);emo::ji("fear")`&\quad&`r set.seed(1);emo::ji("meh")`
\end{array}
\end{array}
\end{array}
\]
- Or upon transposing the matrix $\mathbf{V}$
\[
\begin{array}{ccccc}
\left[\begin{array}{ccc}
-&\mathbf{x}_{1}^T &- \\
\vdots&\vdots&\vdots\\
-&\mathbf{x}_{i}^T &- \\
\vdots&\vdots&\vdots\\
-&\mathbf{x}_{n}^T &- \\
\end{array}\right]_{n \times p}
\begin{array}{c}
`r set.seed(1);emo::ji("beauty")`\\\\
`r set.seed(1);emo::ji("cop")`\\
\\
`r set.seed(1);emo::ji("blonde")`\\
\end{array}
&=&
\left[\begin{array}{ccc}
\mid&&\mid\\
\mathbf{u}_1&\ldots&\mathbf{u}_n\\
\mid&&\mid
\end{array}\right]_{n \times n}
\left[\begin{array}{ccc}
\delta_1\\
&\ddots&\\
&&\delta_r\\
\end{array}\right]_{n \times n}
\left[\begin{array}{ccc}
-&\mathbf{v}_{1}^T &- \\
\vdots&\vdots&\vdots\\
-&\mathbf{v}_{p}^T &- \\
\end{array}\right]_{n \times p}
\begin{array}{c}
`r set.seed(1);emo::ji("fear")`\\
\\
`r set.seed(1);emo::ji("meh")`
\end{array}
\end{array}
\]
#### Reconstruction of faces via linear combination of eigen faces.
In left singular vectors $u_{ij}$ we quantify the contribution of the $j^\text{th}$ eigenface in the reconstruction of face $i$ and we rescale the importance of each eigen face by its corresponding eigen value $\delta_j$.
\[
\left[\begin{array}{ccc}
-&\mathbf{x}_{1}^T &- \\
\vdots&\vdots&\vdots\\
-&\mathbf{x}_{i}^T &- \\
\vdots&\vdots&\vdots\\
-&\mathbf{x}_{n}^T &- \\
\end{array}\right]_{n \times p}
\begin{array}{c}
`r set.seed(1);emo::ji("beauty")`\\\\
`r set.seed(1);emo::ji("cop")`\\
\\
`r set.seed(1);emo::ji("blonde")`\\
\end{array} =
\delta_1\left[
\begin{array}{c}
\mid\\
\mathbf{u}_1\\
\mid
\end{array}
\right]
\begin{array}{c}
\left[
\begin{array}{ccc}
-&
\mathbf{v}_1^T&
-
\end{array}
\right]\\\quad\\\quad
\end{array}
\begin{array}{c}
`r set.seed(1);emo::ji("fear")`
\\\quad\\\quad
\end{array}
+ \ldots +
\delta_r\left[
\begin{array}{c}
\mid\\
\mathbf{u}_r\\
\mid
\end{array}
\right]
\begin{array}{c}
\left[
\begin{array}{ccc}
-&
\mathbf{v}_r^T&
-
\end{array}
\right]\\\quad\\\quad
\end{array}
\begin{array}{c}
`r set.seed(1);emo::ji("meh")`
\\\quad\\\quad
\end{array}
\]
If we truncate the eigen faces say at $k<r$ we can approximate faces using a limited number of eigen faces!
```{r fig.cap='approximation with 25 (top left), 100 (top right) and 500 (bottom left) eigenfaces and original face (bottom right, or with all eigenfaces)'}
approximateFace <- function(meanFace,faceSvd,k){
reconstruct <- (meanFace + faceSvd$u[1,1:k] %*%
diag(faceSvd$d[1:k]) %*%
t(faceSvd$v[,1:k]) %>%
c)
}
approxHlp <- sapply(
c(25,100,500),
approximateFace,
meanFace=meanFace,
faceSvd=faceSvd)
grid.arrange(
grobs=apply(
cbind(
approxHlp,
allFacesMxCentered[1,]+meanFace
),
2,
plotFaceVector
)
)
```
# SVD as a Matrix Approximation Method
- We have seen that we can use the truncted SVD to approximate matrix $\mathbf{X}$ by $\tilde{\mathbf{X}}$, with $k<r$ and
\[
\tilde{\mathbf{X}}=\mathbf{U}_{n\times k}\boldsymbol{\Delta}_{k\times k}\mathbf{V}_{p \times k}^T
\]
- It can be shown that **SVD: optimal approximation**
- Let $\mathbf{X}$ be an $n\times p$ matrix of rank $r\leq \min(n,p)$, and let $\mathbf{A}$ denote an $n \times p$ matrix of rank $k\leq r$, with elements denoted by $a_{ij}$.
- The matrix $\mathbf{A}$ of rank $k\leq r$ that minimises the Frobenius norm
\[
\vert\vert\mathbf{X}-\mathbf{A}\vert\vert^2_\text{fr}=\sum_{i=1}^n\sum_{j=1}^p (x_{ij}-a_{ij})^2
\]
is given by the truncated SVD
\[
\mathbf{X}_k = \sum_{j=1}^k \delta_j \mathbf{u}_j\mathbf{v}_j^T.
\]
- The truncated SVD has $k < r$ terms. Hence, generally $\mathbf{X}_k$ does not coincide with $\mathbf{X}$. It is considered as an approximation.
- Note, that the truncated SVD thus approximates the matrix by minimising a kind of sum of least squared errors between the elements of matrix $\mathbf{X}$ and $\mathbf{A}$ and that
- the truncated SVD $\mathbf{X}_k$ is the best rank-k approximation of $\mathbf{X}$ in terms of this
Frobenius norm.
- Also, note that upon truncation
\[\mathbf{V}^T_{p\times k} \mathbf{V}_{p\times k} = \mathbf{I}_{k\times k}\]
\[\mathbf{U}^T_{n\times k} \mathbf{U}_{n\times k} = \mathbf{I}_{k\times k}\]
- But, that
\[\mathbf{V}_{p\times k} \mathbf{V}_{p\times k}^T \neq \mathbf{I}_{p\times p}!!!\]
\[\mathbf{U}_{n\times k} \mathbf{U}_{n\times k}^T \neq \mathbf{I}_{n\times n}!!!\]
---
Some **informal statement** about the truncated SVD
\[
\mathbf{X}_k = \sum_{j=1}^k \delta_j \mathbf{u}_j\mathbf{v}_j^T.
\]
- It can be considered as a weighted sum of matrices $\mathbf{u}_j\mathbf{v}_j^T$, with weights $\delta_j$.
- The terms are ordered with decreasing weights $\delta_1\geq \delta_2 \geq \cdots \geq \delta_k >0$.
- The matrices $\mathbf{u}_j\mathbf{v}_j^T$ are of equal "magnitude" (constructed from normalised vectors).
- Truncation at $k$ results in $k$ $\delta_j$'s, $k\times n$ elements in the $\mathbf{u}_j$ and $k \times p$ elements in the $\mathbf{v}_j$. Hence a total of $k+kn+kp=k(1+n+p)$ elements (usually much smaller than $np$). (Note that restrictions apply to $\mathbf{u}_j$ and $\mathbf{v}_j$; hence even less independent elements).
$\longrightarrow$ **data compression**
## Example 1: Image compression
### Painting Mondriaan: Composition_No.III with red, blue, yellow and black (1929).
- Have a look at this painting of Mondriaan (1872 -- 1944), here shown in black-and-white.
#### Load the original painting
1. fetch image from the web
2. convert into greyscale
3. plot
4. save as Matrix
```{r}
mondriaan <- load.image("https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/Piet_Mondrian_-_Composition_No._III%2C_with_red%2C_blue%2C_yellow_and_black%2C_1929.jpg/1920px-Piet_Mondrian_-_Composition_No._III%2C_with_red%2C_blue%2C_yellow_and_black%2C_1929.jpg")
mondriaan <- grayscale(mondriaan)
plot(mondriaan,axes=FALSE)
X <- matrix(as.data.frame(mondriaan)[,3],nrow=nrow(mondriaan),ncol=ncol(mondriaan))
```
- This picture can be represented as a $`r nrow(mondriaan)` \times `r ncol(mondriaan)``$ matrix $\mathbf{X}$ with gray scale intensities $\in [0,1]$. ($\approx 4\times 10^6$ data entries)
- We will here not transform the image in a vector, but will look at the performance of the SVD to compress this image. The SVD can be applied to any matrix!
#### Singular values
```{r}
monSvd <- svd(X)
p1 <- data.frame(x=1:length(monSvd$d),y=monSvd$d) %>%
ggplot(aes(x=x,y=y)) +
geom_point() +
xlab("k") +
ylab("singular value")
p2 <- data.frame(x=1:10,y=monSvd$d[1:10]) %>%
ggplot(aes(x=x,y=y)) +
geom_point() +
xlab("k") +
ylab("singular value")
grid.arrange(p1,p2,nrow=1)
```
- The singular values decay very quickly!
#### Data compression
- We make the plot for a reconstruction with 1 singular vector. This leads to a data compression of $1-\frac{(1+`r nrow(mondriaan)`+`r ncol(mondriaan)`)}{`r nrow(mondriaan) `\times `r ncol(mondriaan)`}$ = `r 100 - round((1+nrow(mondriaan)+ncol(mondriaan))/(nrow(mondriaan)*ncol(mondriaan))*100,1)`%. We only use 1 left singular vector (`r nrow(mondriaan)`), 1 eigen value, 1 right singular vector (`r ncol(mondriaan)`).
```{r}
k <- 1
approxMon <- monSvd$u[,1:k] %*%
diag(monSvd$d[1:k],ncol=k) %*%
t(monSvd$v[,1:k])
approxMon[approxMon < 0] <- 0
approxMon[approxMon > 1] <- 1
as.cimg(approxMon) %>%
plot(.,main=paste0("Approximation with ",k," singular vectors"),axes=FALSE)
```
- We make the plot for a reconstruction with 2 singular vector. This leads to a data compression of $1-\frac{2\times (1+`r nrow(mondriaan)`+`r ncol(mondriaan)`)}{`r nrow(mondriaan) `\times `r ncol(mondriaan)`}$ = `r 100 - round(2*(1+nrow(mondriaan)+ncol(mondriaan))/(nrow(mondriaan)*ncol(mondriaan))*100,1)`%. We only use 2 left singular vectors
(2 $\times$ `r nrow(mondriaan)`), 2 singular values, 2 right singular vectors (2 $\times$ `r ncol(mondriaan)`).
```{r}
k <- 2
approxMon <- monSvd$u[,1:k] %*%
diag(monSvd$d[1:k],ncol=k) %*%
t(monSvd$v[,1:k])
approxMon[approxMon < 0] <- 0
approxMon[approxMon > 1] <- 1
as.cimg(approxMon) %>%
plot(.,main=paste0("Approximation with ",k," singular vectors"),axes=FALSE)
```
```{r}
par (mfrow=c(3,3))
par(mar=c(1,2,1,1))
for (k in c(1:8))
{
approxMon <- monSvd$u[,1:k] %*%
diag(monSvd$d[1:k],ncol=k) %*%
t(monSvd$v[,1:k])
approxMon[approxMon < 0] <- 0
approxMon[approxMon > 1] <- 1
approxMon %>%
as.cimg %>%
plot(.,main=paste0(k," singular vectors"),axes=FALSE)
}
plot(as.cimg(X),main=paste0("Original image"),axes=FALSE)
```
### More complex painting: Composition A, Piet Mondriaan
#### Load the original painting
```{r}
mondriaan <- load.image("https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Composition_A_by_Piet_Mondrian_Galleria_Nazionale_d%27Arte_Moderna_e_Contemporanea.jpg/1920px-Composition_A_by_Piet_Mondrian_Galleria_Nazionale_d%27Arte_Moderna_e_Contemporanea.jpg")
mondriaan <- grayscale(mondriaan)
plot(mondriaan,axes=FALSE)
X <- matrix(as.data.frame(mondriaan)[,3],nrow=dim(mondriaan)[1],ncol=dim(mondriaan)[2])
```
#### Singular values
```{r, cache=TRUE}
monSvd <- svd(X)
```
```{r}
p1 <- data.frame(x=1:length(monSvd$d),y=monSvd$d) %>%
ggplot(aes(x=x,y=y)) +
geom_point() +
xlab("k") +
ylab("singular value")
p2 <- data.frame(x=1:10,y=monSvd$d[1:10]) %>%
ggplot(aes(x=x,y=y)) +
geom_point() +
xlab("k") +
ylab("singular value")
grid.arrange(p1,p2,nrow=1)
```
- The singular values decay a bit slower. The painting is a bit more complex. More lines and colors.
#### Evaluate data compression
```{r}
par (mfrow=c(3,3))
par(mar=c(1,2,1,1))
for (k in c(1,seq(3,21,3)))
{
approxMon <- monSvd$u[,1:k] %*%
diag(monSvd$d[1:k],ncol=k) %*%
t(monSvd$v[,1:k])
approxMon[approxMon < 0] <- 0
approxMon[approxMon > 1] <- 1
approxMon %>%
as.cimg %>%
plot(.,main=paste0(k," singular vectors"),axes=FALSE)
}
plot(as.cimg(X),main=paste0("Original image"),axes=FALSE)
```
### Self portret Piet Mondriaan
#### Load the painting
```{r}
mondriaan <- load.image("https://upload.wikimedia.org/wikipedia/commons/thumb/6/66/Mondrian_Zelfportret.jpg/1920px-Mondrian_Zelfportret.jpg")
mondriaan <- grayscale(mondriaan)
plot(mondriaan,axes=FALSE)
X <- matrix(as.data.frame(mondriaan)[,3],nrow=dim(mondriaan)[1],ncol=dim(mondriaan)[2])
```
#### Singular values
```{r, cache=TRUE}
monSvd <- svd(X)
```
```{r}
p1 <- data.frame(x=1:length(monSvd$d),y=monSvd$d) %>%
ggplot(aes(x=x,y=y)) +
geom_point() +
xlab("k") +
ylab("singular value")
p2 <- data.frame(x=1:10,y=monSvd$d[1:10]) %>%
ggplot(aes(x=x,y=y)) +
geom_point() +
xlab("k") +
ylab("singular value")
grid.arrange(p1,p2,nrow=1)
```
- The singular values decay much slower. The painting is more complex.
#### Evaluate compression
```{r}
par (mfrow=c(3,3))
par(mar=c(1,2,1,1))
for (k in c(1,5,10,20,30,40,50,100))
{
approxMon <- monSvd$u[,1:k] %*%
diag(monSvd$d[1:k],ncol=k) %*%
t(monSvd$v[,1:k])
approxMon[approxMon < 0] <- 0
approxMon[approxMon > 1] <- 1
approxMon %>%
as.cimg %>%
plot(.,main=paste0(k," singular vectors"),axes=FALSE)
}
plot(as.cimg(X),main=paste0("Original image"),axes=FALSE)
```
Here we need at least 40 singular vector. This leads to a data compression of $1-\frac{40\times (1+`r nrow(mondriaan)`+`r ncol(mondriaan)`)}{`r nrow(mondriaan)` \times `r ncol(mondriaan)`}$ = `r 100 - round(40*(1+nrow(mondriaan)+ncol(mondriaan))/(nrow(mondriaan)*ncol(mondriaan))*100,1)`%. We only use 40 left singular vectors ($40 \times `r nrow(mondriaan)`$), 40 singular values, 40 right eigens vector ($40\times `r ncol(mondriaan)`$).
# Geometric interpretation
Write the **truncated SVD** as
\[
\mathbf{X}_k = \mathbf{U}_k \boldsymbol{\Delta}_k \mathbf{V}_k^T = \mathbf{Z}_k \mathbf{V}_k^T
\]
with
\[
\mathbf{Z}_k = \mathbf{U}_k \boldsymbol{\Delta}_k
\]
an $n \times k$ matrix.
Each of the $n$ rows of $\mathbf{Z}_k$, say $\mathbf{z}^T_{k,i}$, represents a point in a $k$-dimensional space.
Because of the orthonormality of the singular vectors, we also have
\begin{eqnarray*}
\mathbf{X}_k\mathbf{V}_k &=& \mathbf{Z}_k \mathbf{V}_k^T\mathbf{V}_k \\
\mathbf{X}_k\mathbf{V}_k &=& \mathbf{Z}_k.
\end{eqnarray*}
Thus the matrix $\mathbf{V}_k$ is a **transformation matrix** that may be used to transform $\mathbf{X}_k$ into $\mathbf{Z}_k$, and $\mathbf{Z}_k$ into $\mathbf{X}_k$.
---
Note that
- The matrix $\mathbf{V}_k$ transforms the $p$-dimensional $\mathbf{X}_k$ into the $k$-dimensional $\mathbf{Z}_k$: $\mathbf{Z}_k = \mathbf{X}_k\mathbf{V}_k$. Note, however, that the matrix $\mathbf{X}_k$ must not necessarily be used for this transformation, because the SVD of the original matrix $\mathbf{X}$ also gives directly $\mathbf{Z}_k = \mathbf{U}_k \boldsymbol{\Delta}_k$.
- The inverse transformation from the $k$-dimensional $\mathbf{Z}_k$ to the $p$-dimensional $\mathbf{X}_k$ is given by the transpose of $\mathbf{V}_k$: $\mathbf{Z}_k \mathbf{V}_k^T=\mathbf{X}_k$. Often inverse transformations are given by the inverse of a matrix, but thanks to the orthonormality of the columns of $\mathbf{V}_k$, we get $\mathbf{V}_k^T\mathbf{V}_k=\mathbf{I}$, and thus $\mathbf{V}_k^T$ acts as an inverse.
- The transformation from the $k$-dimensional $\mathbf{Z}_k$ to the $p$-dimensional $\mathbf{X}_k$ is transforming points from a low dimensional space ($k$) to a high dimensional space ($p$). You may not interpret this as if this transformation adds information; the transformed points in $\mathbf{X}_k$ still live in a $k$-dimensional subspace of the larger $p$-dimensional space; the matrix $\mathbf{X}_k$ is only of rank $k$ and thus contains less information than the original data matrix $\mathbf{X}$ (if rank($\mathbf{X}$)$=r>k$).
---
More importantly, it can be shown that (thanks to orthonormality of $\mathbf{V}$)
\[
\mathbf{X}\mathbf{V}_k = \mathbf{Z}_k.
\]
This follows from (w.l.g. rank($\mathbf{X}$)=$r$)
\begin{eqnarray*}
\mathbf{X}\mathbf{V}_k
&=& \mathbf{UDV}^T\mathbf{V}_k = \mathbf{UD}\begin{pmatrix}
\mathbf{v}_1^T \\
\vdots \\
\mathbf{v}_r^T
\end{pmatrix}
\begin{pmatrix}
\mathbf{v}_1 \ldots \mathbf{v}_k
\end{pmatrix} \\
&=& \mathbf{UDV}^T\mathbf{V}_k = \mathbf{UD}\begin{pmatrix}
1 & 0 & \ldots & 0 \\
0 & 1 & \ldots & 0 \\
\vdots & \vdots & \ddots & 0 \\
0 & 0 & \ldots & 1 \\
0 & 0 & \ldots & 0 \\
\vdots & \vdots & \vdots & \vdots \\
0 & 0 & \ldots & 0
\end{pmatrix} \
= \mathbf{U}_k\boldsymbol{\Delta}_k = \mathbf{Z}_k
\end{eqnarray*}
The $p \times k$ matrix $\mathbf{V}_k$ acts as a transformation matrix: transforming $n$ points in a $p$ dimensional space to $n$ points in a $k$ dimensional space.
---
We take a closer look at
\[
\mathbf{Z}_k = \mathbf{X}\mathbf{V}_k = \begin{pmatrix}
\mathbf{x}_1^T \\
\vdots \\
\mathbf{x}_n^T
\end{pmatrix} \begin{pmatrix}
\mathbf{v}_1 \ldots \mathbf{v}_k
\end{pmatrix}.
\]
The $i$th row (observation) in $\mathbf{Z}_k$ equals
\[
\mathbf{z}_{k,i}^T = \mathbf{x}_i^T\mathbf{V}_k = \left(\mathbf{x}_i^T \mathbf{v}_1 , \mathbf{x}_i^T \mathbf{v}_2 , \ldots , \mathbf{x}_i^T \mathbf{v}_k\right).
\]
Hence, $\mathbf{z}_{k,i}^T = \mathbf{x}_i^T\mathbf{V}_k$ is the orthogonal projection of $\mathbf{x}_i$ onto the $k$-dimensional subspace spanned by the columns of $\mathbf{V}_k$.
SVD transforms data set to lower dimensional data set:
The SVD thus gives a transformation of the $p$ dimensional data to $k\leq r$ dimensional data:
\[
\mathbf{Z}_k = \mathbf{X}\mathbf{V}_k.
\]
This is essentially a dimension reduction.
----
Note that,
- The transformation from $p$-dimensional $\mathbf{X}$ to $k$-dimensional $\mathbf{Z}_k$ is important. It shows that the $n$ points in the rows of $\mathbf{Z}_k$ are the result of projecting the $n$ points in $\mathbf{X}$ onto the columns of $\mathbf{V}_k$ (i.e. the first $k$ singular vectors of $\mathbf{X}$). We say that the space of $\mathbf{Z}_k$ is spanned by the column of $\mathbf{V}_k$.
- The points (rows) in $\mathbf{X}$ live in a $p$-dimensional space (or rank($\mathbf{X}$)$=r$ if $r<p$) and they are thus projected onto a lower dimensional space. This is in contrast to the projection $\mathbf{X}_k\mathbf{V}_k=\mathbf{Z}_k$, because the points in $\mathbf{X}_k$ live in a $k$-dimensional subspace of $\mathbf{X}$.
- Note that with $k<r$ there is no unique transformation to transform $\mathbf{Z}_k$ back to $\mathbf{X}$. On the previous slide we only established the transformation $\mathbf{Z}_k \mathbf{V}_k^T=\mathbf{X}_k$. Indeed, starting from $\mathbf{X}\mathbf{V}_k = \mathbf{Z}_k$, and right-multiplying with $\mathbf{V}_k^T$ does not give the backtransformation, because $\mathbf{V}_k\mathbf{V}_k^T$ is not the identity matrix.
# Interpretation of SVD in terms of correlation matrices
For a matrix $\mathbf X$ the sample variance covariance matrix estimator is $p\times p$ matrix
\begin{eqnarray}
\mathbf{S}&=&\frac{1}{N-1}(\mathbf{X}-\bar{\mathbf{X}})^T (\mathbf{X}-\bar{\mathbf{X}})\\
&=&\frac{1}{N-1}\left[\mathbf{X}^T\mathbf{X} - \bar{\mathbf{X}}^T\bar{\mathbf{X}}\right]
\end{eqnarray}
So $\mathbf{X}^T\mathbf{X}$ defines up to a constant the variance covariance matrix of $\mathbf{X}$! When the matrix is column centered $\mathbf{S}=\frac{1}{n-1}\mathbf{X}^T\mathbf{X}$.
The same holds for the rows of $\mathbf{X}$! The covariance between the subjects can be estimated as \[\mathbf{S}=\frac{1}{p-1}\mathbf{X}\mathbf{X}^T\] upon row centering.
Note, that
\begin{eqnarray}
\mathbf{X}^T\mathbf{X} &=& \mathbf{V}\boldsymbol{\Delta}\mathbf{U}^T \mathbf{U} \boldsymbol{\Delta} \mathbf{V}^T \\
&=&\mathbf{V}\boldsymbol{\Delta}^2 \mathbf{V}^T
\end{eqnarray}
If we rewrite the expression
\begin{eqnarray}
\mathbf{X}^T\mathbf{X}\mathbf{V} &=&\mathbf{V}\boldsymbol{\Delta}^2 \mathbf{V}^T\mathbf{V}\\
&=&\mathbf{V}\boldsymbol{\Delta}^2
\end{eqnarray}
So, if the data are centered, the SVD can be used to perform a spectral decomposition of the sample covariance matrix where the right singular vectors correspond to the eigen vectors of the covariance matrix and the eigenvalues are the squared singular values!
Similarly the left singular values can be used to estimate the covariance matrix of the rows of $\mathbf{X}$. So in our notation covariance between subjects.
\begin{eqnarray}
\mathbf{X}\mathbf{X}^T &=&\mathbf{U}\boldsymbol{\Delta}^2 \mathbf{U}^T
\end{eqnarray}
This link is for instance very useful for recommender systems, i.e. to propose movies based on the subjects with whom you correlate. We will also exploit this when we discuss on PCA.
# SVD and inverse of a matrix
A linear system of equations with $n$ equations and $n$ unknowns
\[
\mathbf{A}_{n\times n} \boldsymbol{\beta} = \mathbf{b}
\]
can be solved by
\[
\boldsymbol{\beta} = \mathbf{A}_{n\times n}^{-1} \mathbf{b}
\]
A unique solution exists if A is full rank.
Note, that a singular value decomposition of the square matrix $\mathbf{A}=\mathbf{V}\boldsymbol{\Delta}\mathbf{V}^T$ enables the inverse to be written as
\[
\mathbf{A}^{-1} = \mathbf{V}\boldsymbol{\Delta}^{-1}\mathbf{V}^T
\]
indeed
\[
\mathbf{A}^{-1} \mathbf{A} = \mathbf{V}\boldsymbol{\Delta}^{-1}\mathbf{V}^T\mathbf{V}\boldsymbol{\Delta}\mathbf{V}^T = \mathbf{I}
\]
Note, that the SVD generalizes this to systems of under (n<p, fat short matrices)
and over determined systems (n>p tall skinny matrices):
Let
\begin{eqnarray}
\mathbf{A} = \mathbf{U}\boldsymbol{\Delta}\mathbf{V}^T
\end{eqnarray}
and we want to solve
\begin{eqnarray}
\mathbf{A} \boldsymbol{\beta} &=& \mathbf{b}\\
\mathbf{U}\boldsymbol{\Delta}\mathbf{V}^T \boldsymbol{\beta} &=& \mathbf{b}\\