forked from statOmics/HDDA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsvd.Rmd
executable file
·2902 lines (2322 loc) · 88.8 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:
bookdown::pdf_document2:
toc: true
number_sections: true
latex_engine: xelatex
always_allow_html: true
---
```{r, child="_setup.Rmd"}
```
# 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 singular vector and second left singular vector.
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 singular vectors 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 singular vectors 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 singular vectors $\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 singular faces.
- The first singular 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 singular 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 singular faces.
In left singular vectors $u_{ij}$ we quantify the contribution of the $j^\text{th}$ singular face in the reconstruction of face $i$ and we rescale the importance of each singular face by its corresponding singular 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 singular faces say at $k<r$ we can approximate faces using a limited number of singular faces!
```{r fig.cap='approximation with 25 (top left), 100 (top right) and 500 (bottom left) singular faces and original face (bottom right, or with all singular faces)'}
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 singular 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 singular vector ($40\times `r ncol(mondriaan)`$).
# Geometric interpretation
<div style="position: relative;width: 100%;height: 0;padding-bottom: 56.25%;">
<iframe
src="https://www.youtube.com/embed/srUDBwP9IW8"
style=" position:absolute;top: 0;left: 0;width: 100%;height: 100%;"
frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</br>
We introduce the geometric interpretation of the svd by using a toy example.
## Iris dataset
The iris dataset is a dataset on iris flowers.
- Three species (setosa, virginica and versicolor)
- Length and width of Sepal leafs
- Length and width of Petal Leafs
For didactical purposes we will use a subset of the data.
- Virginica Species
- 3 Variables: Sepal Length, Sepal Width, Petal Length
- This allows us to visualise the data in 3D plots
- Illustrate the data compression of the SVD from 3 to two dimensions.
### Subset the data
```{r}
library(tidyverse)
library(plotly)
irisSub <- iris %>%
filter(Species == "virginica") %>%
dplyr::select("Sepal.Length","Sepal.Width","Petal.Length")
```
```{r echo=FALSE}
p1 <- plot_ly(
irisSub,
x = ~Sepal.Width,
y = ~Sepal.Length,
z= ~Petal.Length) %>%
add_markers(type="scatter3d") %>%
layout(
scene = list(
aspectmode="cube",
xaxis = list(range=c(-1,1)*max(abs(irisSub))), yaxis = list(range=c(-1,1)*max(abs(irisSub))), zaxis = list(range=c(-1,1)*max(abs(irisSub)))
)
)
p1
```
### Center the data
```{r}
X <- irisSub %>% scale(scale=FALSE)
```
The data is translated to a mean of [0, 0, 0].
```{r echo = FALSE}
p2 <- plot_ly(X %>% as.data.frame, x = ~Sepal.Length, y = ~Sepal.Width, z= ~Petal.Length) %>%
add_markers(type="scatter3d") %>%
layout(
scene = list(
aspectmode="cube",
xaxis = list(range=c(-1,1)*max(abs(irisSub))), yaxis = list(range=c(-1,1)*max(abs(irisSub))), zaxis = list(range=c(-1,1)*max(abs(irisSub)))
)
)
p2
```
We zoom in and add the original axis in grey in the origin.
```{r echo=FALSE}
p3 <- plot_ly(X %>% as.data.frame,
x = ~Sepal.Length,
y = ~Sepal.Width,
z= ~Petal.Length) %>%
layout(
scene = list(
aspectmode="cube",
xaxis = list(range=c(-1,1)*max(abs(irisSub))), yaxis = list(range=c(-1,1)*max(abs(irisSub))), zaxis = list(range=c(-1,1)*max(abs(irisSub)))
)
) %>% layout(
scene = list(aspectmode="cube",
xaxis = list(range=c(-1,1)*max(abs(X))),
yaxis = list(range=c(-1,1)*max(abs(X))),
zaxis = list(range=c(-1,1)*max(abs(X))))) %>%
add_trace(
x = c(0,1),
y = c(0,0),
z = c(0,0),
mode = "lines",
line = list(width = 5, color = "grey"),
type="scatter3d") %>%
add_trace(
x = c(0, 0),
y = c(0, 1), z = c(0, 0),
mode = "lines",
line = list(
width = 5,
color = "grey"),
type="scatter3d") %>%
add_trace(
x = c(0, 0),
y = c(0, 0),
z = c(0, 1),
mode = "lines",
line = list(width = 5, color = "grey"),
type = "scatter3d") %>%
hide_legend()
p3 %>%
add_markers(
type = "scatter3d",
type = "markers",
marker = list(color="#1f77b4")
)
```
## SVD iris dataset
1. We adopt the SVD on the centered data
```{r}
irisSvd <- svd(X)
```
2. We extract
- the right singular vectors $\mathbf{V}$ and
- the projections $\mathbf{Z}$
```{r}
V <- irisSvd$v
Z <- irisSvd$u %*% diag(irisSvd$d)
```
Note, that
- the SVD is essentially a rotation to a new coordinate system.
- we plotted $\mathbf{V}_3$ with dots because we will use the SVD for dimension reduction \[\text{3D} \rightarrow \text{2D}\]
```{r echo=FALSE}
p4 <- p3 %>%
add_trace(
x = c(0, V[1,1]),
y = c(0, V[2,1]),
z = c(0, V[3,1]),
mode = "lines",
line = list(width = 5,
color = "red"),
type="scatter3d") %>%
add_trace(
x = c(0, V[1,2]),
y = c(0, V[2,2]),
z = c(0, V[3,2]),
mode = "lines",
line = list(width = 5, color = "red"),
type = "scatter3d") %>%
add_trace(
x = c(0, V[1,3]),
y = c(0, V[2,3]),
z = c(0, V[3,3]),
mode = "lines",
line = list(