-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlec08.Rmd
1293 lines (860 loc) · 34.8 KB
/
lec08.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: "Lecture 8"
author: "DJM"
date: "13 November 2018"
output:
pdf_document: default
slidy_presentation:
css: http://mypage.iu.edu/~dajmcdon/teaching/djmRslidy.css
font_adjustment: 0
bibliography: booth-refs.bib
---
\newcommand{\E}{\mathbb{E}}
\newcommand{\Expect}[1]{\mathbb{E}\left[ #1 \right]}
\newcommand{\Var}[1]{\mathbb{V}\left[ #1 \right]}
\newcommand{\Cov}[2]{\mathrm{Cov}\left[#1,\ #2\right]}
\newcommand{\given}{\ \vert\ }
\renewcommand{\P}{\mathbb{P}}
\newcommand{\argmin}{\arg\min}
\newcommand{\argmax}{\arg\max}
\newcommand{\F}{\mathcal{F}}
\newcommand{\norm}[1]{\left\lVert #1 \right\rVert}
\newcommand{\indicator}{\mathbf{1}}
\renewcommand{\bar}{\overline}
\renewcommand{\hat}{\widehat}
\newcommand{\tr}[1]{\mbox{tr}(#1)}
\newcommand{\X}{X}
\newcommand{\R}{\mathbb{R}}
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(message=FALSE, warning=FALSE, echo=FALSE,
fig.align='center',fig.width=10,
fig.height=6, cache=TRUE, autodep = TRUE)
library(tidyverse)
theme_set(theme_minimal(base_family="Times"))
green = '#00AF64'
blue = '#0B61A4'
red = '#FF4900'
orange = '#FF9200'
colvec = c(green,blue,red,orange)
```
# Motivation
## Overview
Representation learning is the idea that performance of ML methods is
highly dependent on the choice of representation
For this reason, much of ML is geared towards transforming the data into
the relevant features and then using these as inputs
This idea is as old as statistics itself, really,
(e.g. Pearson (1901), where PCA was first introduced)
However, the idea is constantly revisited in a variety of fields and
contexts
Commonly, these learned representations capture 'low level' information
like overall shape types
Other sharp features, such as images, aren't captured
It is possible to quantify this intuition for PCA at least
## PCA
Principal components analysis (PCA) is an (unsupervised) dimension
reduction technique
It solves various equivalent optimization problems
(Maximize variance, minimize $L_2$ distortions, find closest subspace of a given rank,\ldots)
At its core, we are finding linear combinations of the original
(centered) covariates $$Z_{ij} = \alpha_j^{\top} X_i$$
This is expressed via the SVD: $\X - \overline{\X} = UDV^{\top}$ as
$$Z = \X V = UD$$
## Lower dimensional embeddings
Suppose we have predictors $x_1$ and $x_2$
- We more faithfully preserve the structure of the data by keeping
$x_1$ and setting $x_2$ to zero than the opposite
```{r, echo=FALSE}
df = data.frame(x=rep(rnorm(20,sd=1),3),y=rep(rnorm(20,sd=.2),3),
lab = rep(c('data','x2 only','x1 only'),each=20))
df[21:40,1] = 0
df[41:60,2] = 0
ggplot(df,aes(x=x,y=y,color=lab)) + geom_point() + ylim(-2,2) + xlim(-2,2) +
theme(legend.title = element_blank(), legend.position = 'bottom') +
ylab('x2') + xlab('x1')
```
## Lower dimensional embeddings
An important feature of the previous example is that $x_1$ and $x_2$ aren't
correlated
What if they are?
```{r, echo=FALSE}
theta = -pi/4
R = matrix(c(cos(theta),sin(theta),-sin(theta),cos(theta)),2)
X = as.matrix(df[1:20,1:2]) %*% R
df2 = data.frame(x=rep(X[,1],3),y=rep(X[,2],3),
lab = rep(c('data','x2 only','x1 only'),each=20))
df2[21:40,1] = 0
df2[41:60,2] = 0
df2 %>% filter(lab=='data') %>%
ggplot(aes(x=x,y=y)) + geom_point() + ylim(-2,2) + xlim(-2,2) +
theme(legend.title = element_blank(), legend.position = 'bottom') +
ylab('x2') + xlab('x1')
```
## Lower dimensional embeddings
We lose a lot of structure by setting either $x_1$ or $x_2$ to zero
```{r, echo=FALSE}
df2 %>%
ggplot(aes(x=x,y=y,color=lab)) + geom_point() + ylim(-2,2) + xlim(-2,2) +
theme(legend.title = element_blank(), legend.position = 'bottom') +
ylab('x2') + xlab('x1')
```
## Lower dimensional embeddings
There isn't that much structurally different between the examples
One is just a rotation of the other
```{r, echo=FALSE}
df3 = bind_rows(df,df2)
df3$version = rep(c('original','rotated'),each=60)
df3 %>%
ggplot(aes(x=x,y=y,color=lab)) + geom_point() + ylim(-2,2) + xlim(-2,2) +
facet_grid(~version)+
theme(legend.title = element_blank(), legend.position = 'bottom') +
ylab('x2') + xlab('x1')
```
## PCA
If we knew how to rotate our data, then we could more easily retain the structure.
__PCA__ gives us exactly this rotation
## Optimization
If we want to find the first $K$ principal components, the relevant
optimization program is:
$$\min_{\mu,(\lambda_i),V_K} \sum_{i=1}^n \norm{X_i - \mu - V_K \lambda_i}^2$$
This representation is important
It shows that we are trying to reconstruct lower dimensional representations of the
covariates
## PCA
$$\min_{\mu,(\lambda_i),V_K} \sum_{i=1}^n \norm{X_i - \mu - V_K \lambda_i}^2$$
We can partially optimize for $\mu$ and $(\lambda_i)$ to find
- $\hat\mu = \overline{X}$
- $\hat\lambda_i = V_K^{\top}(X_i - \hat \mu)$
We can find
$$\min_{V } \sum_{i=1}^n \norm{(X_i - \hat\mu) - V V^{\top}(X_i - \hat\mu)}^2$$
where $V$ is constrained to be orthogonal
This is the so called Steifel manifold of rank-$K$ orthogonal matrices
The solution is given by the singular vectors $V$
# (General) spectral connectivity analysis
## Metric embeddings
Spectral connectivity analysis (SCA)
* Linear and nonlinear
* Dimension reduction or feature creation
* Examples: PCA, Locally
linear embeddings, Hessian maps, ~~Laplacian
eigenmaps~~
* Useful tools in classification, clustering, (regression)
## PCA (review)
Collect data: $X_1,\ldots,X_n$ where $X_i\in\R^p$.
1. Center and (scale) the data matrix $\X$
2. Compute the SVD of $\X = U\Sigma V^\top$ or $\X\X^\top = U\Sigma^2U^\top$ or $X^\top X = V\Sigma^2 V^\top$
3. Return $U_d\Sigma_d$, where $\Sigma_d$ is the largest $d$
eigenvalues of $\X$
* You need to compute SVD of $\X\X^\top$ [or $\X$]
## When PCA works well
PCA "works" when the data can be represented (in a lower dimension) as
'lines' (or planes, or hyperplanes).
So, in two dimensions:
```{r good-pca, echo=FALSE}
set.seed(12345)
library(mvtnorm)
m = c(2,3)
covmat = matrix(c(1,.75,.75,1),2)
ee = eigen(covmat)
x = rmvnorm(200, m, covmat)
z = apply(x, 1, function(x) sqrt(sum(x^2)))
df = data.frame(x=x[,1], y=x[,2], z=z)
ss = sqrt(ee$values)
df_arrows = data.frame(x1 = m[1], y1 = m[2],
x2 = m[1] + ee$vectors[1,]*ss/sum(ss),
y2 = m[2] + ee$vectors[2,]*ss/sum(ss))
g <- ggplot(df) + geom_point(aes(x=x,y=y,col=z)) + theme_minimal(base_family = 'serif')
g + scale_color_gradient(low=blue, high=orange) +
geom_segment(aes(x=x1,y=y1,xend=x2,yend=y2), data=df_arrows, arrow=arrow())
```
## PCA reduced
Here, we can capture a lot of the variation and underlying
'structure' with just 1 dimension, instead of the original 2 (the coloring is for visualizing).
```{r pca-reduced, echo=FALSE}
xx = scale(x, center=m, scale=FALSE) %*% ee$vectors[,1]
df2 = data.frame(x=xx + m[1], y=xx + m[2], z=z)
g <- ggplot(df2) + geom_point(aes(x=x,y=y,col=z)) + theme_minimal(base_family = 'serif')
g + scale_color_gradient(low=blue, high=orange)
```
## PCA bad
What about other data structures? Again in two dimensions
```{r spiral, echo=FALSE}
tt = seq(0,4*pi,length=100)
df_spiral = data.frame(x = 3/2*tt*sin(tt), y = 0.5*tt*cos(tt), z=tt)
ee = eigen(crossprod(scale(as.matrix(df_spiral[,1:2]))))
ss = sqrt(ee$values)
df_arrows = data.frame(x1 = 0, y1 = 0,
x2 = ee$vectors[1,]*ss/sum(ss)*10,
y2 = ee$vectors[2,]*ss/sum(ss)*10)
g1 <- ggplot(df_spiral) + geom_point(aes(x=x,y=y,col=z)) +
scale_color_gradient(low=blue, high=orange) +
geom_segment(aes(x=x1,y=y1,xend=x2,yend=y2), data=df_arrows, arrow=arrow())
g1
```
## PCA bad (2)
Here, we have failed miserably.
There is actually only 1 dimension
to this data (imagine walking up the spiral going
from blue to orange).
However, when we write it as 1 PCA dimension,
all the points are all `mixed up'.
```{r spiral-reduced}
xx = as.matrix(df_spiral[,1:2]) %*% ee$vectors[,1]
df_spiral2 = data.frame(x=xx, y=xx, z=tt)
g <- ggplot(df_spiral2) + geom_point(aes(x=x,y=y,col=z)) +
theme_minimal(base_family = 'serif')
g + scale_color_gradient(low=blue, high=orange)
```
## Explanation
* PCA wants to minimize distances (equivalently maximize
variance). This means it 'slices' through the data at the
'meatiest' point, and then the next one, and so on. If the data are
'curved' this is going to induce artifacts.
* PCA also looks at things as being 'close' if they are near each
other in a Euclidean sense.
* On the spiral, our intuition says
that things are 'close' only if the distance is constrained to go
along the curve. In other words, purple and blue are close, blue and
orange are not.
# Nonlinearity and CMDS
## Kernel PCA (KPCA)
Classical PCA comes from
$\tilde{X}= X- MX= UDV^{\top}$, where
$M = \mathbf{1}\mathbf{1}^{\top}/n$ and
$\mathbf{1} = (1,1,\ldots,1)^{\top}$
However, we can just as easily get it from the outer
product
$$\mathbb{K} = \tilde{X}\tilde{X}^{\top} = (I - M)XX^{\top}(I - M) = UD^2U^{\top}$$
The intuition behind KPCA is that $\mathbb{K}$ is an expansion into a
kernel space, where
$$\mathbb{K}_{i,i'} = k( \tilde{X}_i,\tilde{X}_{i'}) = \langle \tilde{X}_i,\tilde{X}_{i'} \rangle$$
__Reminder:__ Anytime we see an
inner product, we can kernelize it
## Kernel PCA
Following this intuition, the approach is simple:
1. Specify a kernel $k$
(e.g.
$k(X,X') = \exp\{ -\gamma^{-1}\left|\left| X - X' \right|\right|_2^2\}$)
2. Form $K_{i,i'} = k(X_i,X_{i'})$
3. Standardize and get eigenvector decomposition
$$\mathbb{K} = (I - M)K(I - M) = UD^2U^{\top}$$
This implicitly finds the inner product:
$$k(X_i,X_{i'}) = \langle \phi(X_i),\phi(X_{i'})\rangle$$ However, we
need only specify the kernel
## Kernel PCA
The scores are still $Z = UD$
The $q^{th}$ KPCA score is (up to centering)
$$Z_{iq} = \sum_{i'=1}^n \beta_{i'q} k(X_i,X_{i'})$$ where
$\beta_{i',q} = u_{i'q}/d_q$
__Note:__ As we don't explicitly
generate the feature map, there are no loadings
## Kernel PCA
__Reminder:__ To get the first PC
in classical PCA, we want to solve
$$\max_\alpha \mathbb{V}\alpha^{\top}X \quad \textrm{ subject to } \quad \left|\left| \alpha \right|\right|_2^2 = 1$$
Translate this into the kernel setting, and we are trying to solve
$$\max_{g \in \mathcal{H}_k} \mathbb{V}g(X) \textrm{ subject to } \left|\left| g \right|\right|_{\mathcal{H}_k} = 1$$
The representer theorem states that a
solution to this problem is
$$\hat{g}(X) = \sum_{i=1}^n \beta_i k(X,X_i)$$
Compare $$Z_{iq} = \sum_{i'=1}^n \beta_{i'q} k(X_i,X_{i'})$$ where
$\beta_{i',q} = u_{i'q}/d_q$
## KPCA example
```{r, echo=FALSE}
n = nrow(df_spiral)
I_M = (diag(n) - tcrossprod(rep(1,n))/n)
kp = (tcrossprod(as.matrix(df_spiral[,1:2])) + 1)^2
Kp = I_M %*% kp %*% I_M
Ep = eigen(Kp, symmetric = TRUE)
polydf = data_frame(
x=Ep$vectors[,1]*Ep$values[1],
y=Ep$vectors[,2]*Ep$values[2],
z = df_spiral$z)
kg = exp(-as.matrix(dist(df_spiral[,1:2]))^2 / 10)
Kg = I_M %*% kg %*% I_M
Eg = eigen(Kg, symmetric = TRUE)
gaussdf = data_frame(
x=Eg$vectors[,1]*Eg$values[1],
y=Eg$vectors[,2]*Eg$values[2],
z = df_spiral$z)
dfkern = bind_rows(df_spiral, df_spiral2, polydf, gaussdf)
dfkern$method = rep(c('data','pca','KPCA poly(2)', 'KPCA gauss(100)'), each=n)
dfkern %>%
ggplot(aes(x=x,y=y,color=z)) + geom_point() +
facet_wrap(~method,scales = 'free', nrow=2) +
scale_color_gradient(low=blue, high=orange)
```
## KPCA: summary
Kernel PCA seeks to generalize the notion of
similarity using a kernel map
This can be interpreted as finding smooth,
orthogonal directions in a RKHS
This can allow us to start picking up nonlinear (in the original feature
space) aspects of our data
This new representation can be passed to a
supervised method to form a semisupervised
learner
# Semi-supervised detour
## Basic semi-supervised
1. You get data $\mathcal{D}_{train} = \{(X_1,Y_1),\ldots,(X_n,Y_n)\}$.
2. You do something unsupervised on the $X$'s to create features (like PCA).
3. You use the learned features to find a predictor $\hat{f}$ using the new features.
## Semisupervised learning in practice
Looking at: $$Z_{iq} = \sum_{i'=1}^n \beta_{i'q} k(X_i,X_{i'})$$ this is
only defined at our observed features
Write
- $\mathcal{D}_{train} = \{(X_1,Y_1),\ldots,(X_n,Y_n)\}$
- $\mathcal{D}_{test} = \{(X^*_1,Y^*_1),\ldots,(X^*_{n^*},Y^*_{n^*})\}$
Two common scenarios are
1. We are given $\mathcal{D}_{train}$ and $X^*_1,\ldots,X^*_{n^*}$ to
build $\hat{f}$
2. We are given only $\mathcal{D}_{train}$ to build $\hat{f}$
## Case 1
We are given $\mathcal{D}_{train}$ and $X^*_1,\ldots,X^*_{n^*}$ to build
$\hat{f}$
Then we can just use straight forward KPCA
(Or any unsupervised learning step)
1. Form $\mathbb{K}$ on $\mathcal{D}_{train}$ and
$X^*_1,\ldots,X^*_{n^*}$
2. Get $UD$
3. Pass $Z_q = UD[,1:q]$ to train $\hat{f}$
4. Get $\hat{Y} = \hat{f}(Z_q)$
## Case 2
We are given only $\mathcal{D}_{train}$ to build $\hat{f}$
Now, we don't know the coordinates of
$X^*_1,\ldots,X^*_{n^*}$ in the representation space
To get a new observation $X^*$ embedded into this representation:
$$Z_0 = D^{-1}U^{\top} (I - M)[k^* - K \mathbf{1}/n]$$ where
$k^* = [k(X^*,X_1),\ldots,k(X^*,X_n)]^{\top}$
Then we compute:
1. Form $\mathbb{K}$ on $\mathcal{D}_{train}$
2. Get $UD$
3. Pass $Z_q = UD[,1:q]$ to train $\hat{f}$
4. Form $Z_q^*$ for all $X^*_1,\ldots,X^*_{n^*}$
5. Get $\hat{Y}_{test} = \hat{f}(Z_q^*)$
# Classical multidimensional scaling
## CMDS
A broader class comes from the following procedure (see Figure 4.2 in the text):
1. Calculate a matrix of distances (or dissimilarities) between data points ($\Delta$)
2. Choose some function $\tau: \R\rightarrow\R$ and set $B=\tau(\Delta^2)$.
3. Write $B = U\Sigma U^\top$ (find the eigendecomposition)
4. Approximate your data with $U_{[d]}\Sigma_{[d]}^{1/2}$ where $[d]$ means "the first $d$ columns"
CMDS (I think) is steps 2-4: embedding "dissimilarities" by using the eigendecomposition.
## What I'll call Laplacian Eigenmaps
We can get an estimate of the distance in the unknown geometry that
the data come from (known as a 'nonlinear' manifold) by altering the
usual Euclidean distance.
In this case, I'll use the heat kernel (like most everyone) but this is not necessary.
Distance between $x$ and $y$:
* PCA: $\| x-y\|_2$
* Laplacian eigenmaps : $\exp\left(-\frac{\|x-y\|_2^2}{\epsilon}\right)$
Some notes:
* The name 'Laplacian Eigenmaps' comes from getting the
eigenvector decomposition of the Laplacian restricted to the
manifold (which is the second derivative version of the gradient).
This gives crucial information about its geometry.
* The form of the distance says that if $\|x-y\|_2^2$ is much
bigger than $\epsilon$, then the distance is effectively zero. This
encodes the idea that things that are 'close' in Euclidean distance
are 'close' on the manifold as well.
* If the manifold is smooth, then local
Euclidean distance is an approximation to the distance on the
manifold.
## What is a manifold?
How good of an approximation is Euclidean distance?
This question is equivalent to how asking: how quickly does the
tangent (space) change?
In 1-D, the tangent space is just the first derivative at that point:
$$f(x) = x^2 \Rightarrow f'(x) = 2x.$$
```{r}
quad <- function(x) x^2
ggplot(data.frame(x=c(-1,1)), aes(x)) + stat_function(fun=quad, color=blue) +
geom_abline(slope = 1, intercept = -.25, color=red)
```
## What is a manifold
Therefore, the quality of the (local) Euclidean distance, depends on the
second derivative
(ie: how fast does the first derivative change?)
In higher dimensions, the second derivative is known as the
__Laplacian__:
$$\sum_{j} \frac{\partial^2 f}{\partial x_j^2}$$ (Note: This is also
known as the divergence of the gradient)
## What are Laplacian Eigenmaps, then?
Imagine the operator $\mathbb{L}$ that performs this operation:
$$\mathbb{L} f = \sum_{j} \frac{\partial^2 f}{\partial x_j^2}$$
Then $\mathbb{L}$ is the __Laplacian__, mapping
a function to the divergence of its gradient
* **Key Idea:** We can get the eigenvectors/eigenvalues of $\mathbb{L}$. Analogously to PCA, we can now do inference with these eigenvectors.
Note: There is a substantial
overlap with KPCA, the difference being the centering of $K$ and the
row sum versus column sum normalization
## Laplacian Eigenmaps (procedure)
Collect data: $X_1,\ldots,X_n$ where $X_i\in\R^p$.
1. Center and scale the data matrix $\X$
2. Compute $\mathbb{K}$ where
\[
\mathbb{K}_{ij} = \exp\left(-\frac{\|X_i-X_j\|_2^2}{\epsilon}\right)
\]
3. Form the Laplacian $\mathbb{L} = \mathbb{I} -
\mathbb{M}^{-1}\mathbb{K}$ where $\mathbb{M} =$ `diag(rowSums(`$\mathbb{K}$`))`
4. Compute the SVD of $\mathbb{L} = U\Sigma U^\top$.
5. Return $U_d\Sigma_d^{-1}$, where $\Sigma_d$ contains the __smallest__ $d$ nonzero
eigenvalues of $\mathbb{L}$
(Note that the eigenvectors of $\mathbb{L}$ and
$\mathbb{M}^{-1}\mathbb{K}$ are the same, but $\Sigma(\mathbb{L})
= \mathbb{I} - \Sigma(\mathbb{M}^{-1}\mathbb{K})$)
* This is basically just CMDS on $\tau(\Delta)$.
* ~~You need to compute SVD of $\mathbb{L}$.~~
## Deeper investigation 1.
The distance matrix
```{r,fig.width=10,fig.height=5}
Delta = as.matrix(dist(df_spiral[,1:2]))
df_Delta = gather(as.data.frame(Delta),key='y')
df_Delta$x = rep(1:n,n)/n
df_Delta = mutate(df_Delta, y= as.numeric(y)/n)
g2 <- ggplot(df_Delta,aes(x=x,y=y,fill=value)) + geom_raster() +
scale_fill_gradient(low=blue, high=orange)
gridExtra::grid.arrange(g1,g2,nrow=1)
```
## More deeper
Exponentiate $-\Delta/\gamma$
```{r,fig.width=10,fig.height=5}
K = exp(-Delta^2/.95)
df_K = gather(as.data.frame(K),key='y')
df_K$x = rep(1:n,n)/n
df_K = mutate(df_K, y= as.numeric(y)/n)
g3 <- ggplot(df_K,aes(x=x,y=y,fill=value)) + geom_raster() +
scale_fill_gradient(low=blue, high=orange)
gridExtra::grid.arrange(g2,g3,nrow=1)
```
## More deeperer
Form Laplacian: $\mathbb{L} = \mathbb{I} - \mathbb{M}^{-1}\mathbb{K}$
```{r,fig.width=10,fig.height=5}
L = diag(n) - diag(1/rowSums(K)) %*% K
df_L = gather(as.data.frame(L),key='y')
df_L$x = rep(1:n,n)/n
df_L = mutate(df_L, y= as.numeric(y)/n)
g4 <- ggplot(df_L,aes(x=x,y=y,fill=value)) + geom_raster() +
scale_fill_gradient(low=blue, high=orange)
gridExtra::grid.arrange(g3,g4,nrow=1)
```
## Diffusion distance
```{r, out.width="1000px"}
include_graphics("gfx/diffuse.jpg")
```
## Projection
```{r, out.height="600px"}
include_graphics("gfx/spiralcoord.jpg")
```
## Another example
```{r, out.width="1000px"}
include_graphics("gfx/swissRoll.png")
```
<!--
## What goes wrong?
Collect data: $X_1,\ldots,X_n$ where $X_i\in\R^p$.
You want to perform PCA / Laplacian eigenmaps / LLE /
dimension reduction / manifold learning
$n$, $p$ are Big, like really ~~BIG~~
You have some problems:
1. The matrices $\X\X^\top$ or $\mathbb{L}$ may be hard to store
2. Computing the SVD of either is an $O(n^3)$ operation
(for PCA, it is $O(\min\{np^2,p^3\})$, but both are big)
# Approximation: Can we compute the SVD approximately and still do a good job?
## Nyström extension
Based on a technique for finding a numerical solution for
integral equations
Very similar to out-of-sample embedding
Algorithm (briefly)
1. Subsample $\L$: choose $M\subset \{1,\ldots,n\}$ such
that $|M|=m$, $m \ll n$
\[
\widetilde{\L} := \L_{M,M}
\]
2. Compute eigendecomposition of $\widetilde{\L}=\widetilde{U}\widetilde{\Sigma}\widetilde{U}^\top$
3. "Extend" $\widetilde{U}$ via simple formula to create $U^{nys}$
Write
\[
\begin{aligned}
\L &= \begin{bmatrix} \L_{M,M} & \L_{12}\\ \L_{21} & \L_{22} \end{bmatrix}
& U^{nys} &= \begin{bmatrix} \widetilde{U}\\ \L_{21}\widetilde{U}\widetilde{\Sigma}^{-1}
\end{bmatrix}
\end{aligned}
\]
Requires only O$(nm^2)$ computations
## Gaussian projection
Produces an orthonormal matrix $Q$ which approximates col$(W)$
1. Draw $n\times m$ Gaussian random matrix $\Omega$.
2. Form $Y = \L \Omega$.
3. Construct $Q$, an orthonormal matrix such that col$(Q)$ = col$(Y)$
4. Form $B$ such that $B$ minimizes $|| BQ^{\top}\Omega - Q^{\top}Y||_2$
5. Compute the eigenvector decomposition of $B$, ie: $B = \widehat U \widehat \Sigma \widehat U^{\top}$
6. Return $U^{gp} = Q \widehat U$.
* Requires O$(n^2m)$ computations
* remains orthonormal
(Steps 3 and 4 with QR decomposition)
see Halko, Martinsson, and Tropp (2009)
# Implementation
## Here's our true manifold.
```{r elephant, echo=FALSE}
tt = -100:500/100
elephant <- function(tt,eye=TRUE){
x = 12*cos(3*tt) - 14*cos(5*tt) + 50*sin(tt) + 18*sin(2*tt)
y = -30*sin(tt) + 8*sin(2*tt) - 10*sin(3*tt) - 60*cos(tt)
if(eye) return(data.frame(y=c(y,20),x=c(-x,20)))
else return(data.frame(y=y,x=-x))
}
ele = elephant(tt)
ele$tt = c(tt,-2)
ggplot(ele, aes(x=y,y=x,col=tt)) + geom_point() + theme_minimal(base_family = 'serif') +
scale_color_gradient(low=blue, high=orange)
```
## Data
```{r elephant-data, echo=FALSE}
n = 250
tt = runif(n,-1,5)
dele = elephant(tt,FALSE)+rnorm(n,0,2)
dele$tt = tt
ggplot(dele, aes(x=y,y=x,col=tt)) + geom_point() + theme_minimal(base_family = 'serif') +
scale_color_gradient(low=blue, high=orange)
X = as.matrix(dele[,1:2])
```
## PCA
```{r pca-elephant, echo=TRUE}
Xbar = colMeans(X)
Xc = scale(X, center=Xbar, scale=FALSE) ## Decided not to scale
ee = eigen(tcrossprod(Xc))
Xhat = ee$vectors[,1] * sqrt(ee$values[1])
df_to_plot = data.frame(x=Xhat+Xbar[1], y=Xhat+Xbar[2], z=tt)
ggplot(df_to_plot, aes(x=y,y=x,col=tt)) + geom_point() +
theme_minimal(base_family = 'serif') +
scale_color_gradient(low=blue, high=orange)
```
Not too good.
## Approximate PCA?
Not really necessary since $p$ is small. But we do it anyway.
```{r pca-elephant-approx, echo=TRUE}
select = sample.int(nrow(X), floor(nrow(X)/2))
Xsmall = X[select,]
Xrest = X[-select,]
Xbarsmall = colMeans(Xsmall)
Xcsmall = scale(Xsmall, center=Xbar, scale=FALSE) ## Decided not to scale
ee = eigen(tcrossprod(Xcsmall))
L21 = tcrossprod(scale(Xrest, center=Xbarsmall, scale=FALSE), Xcsmall)
Xhat = c(ee$vectors[,1], L21 %*% ee$vectors[,1]/ee$values[1]) * sqrt(ee$values[1])
df_to_plot = data.frame(x=Xhat+Xbarsmall[1], y=Xhat+Xbarsmall[2], z=tt)
ggplot(df_to_plot, aes(x=y,y=x,col=tt)) + geom_point() +
theme_minimal(base_family = 'serif') +
scale_color_gradient(low=blue, high=orange)
```
## Laplacian eigenmaps
```{r le-elephant, echo=TRUE}
Dmat = as.matrix(dist(Xc))^2
K = exp(-Dmat/150) ## Why 150??
K[K<.1] = 0 ## sometimes this helps
L = diag(nrow(K)) - diag(1/rowSums(K)) %*% K
ee = eigen(L)
tail(ee$values,10)
last = which.min(ee$values[ee$values>1e-12])
Xhat = ee$vectors[,last] / ee$values[last]
df_to_plot = data.frame(x=Xhat+Xbar[1], y=Xhat+Xbar[2], z=tt)
ggplot(df_to_plot, aes(x=x,y=y,col=tt)) + geom_point() +
theme_minimal(base_family = 'serif') +
scale_color_gradient(low=blue, high=orange)
```
Still not great. (Try as I might)
## Approximate LE?
```{r le-elephant-approx, echo=TRUE}
Ks = K[select,select]
ls = length(select)
Ls = diag(ls) - diag(1/rowSums(Ks)) %*% Ks
ee = eigen(Ls)
ee$values = Re(ee$values) ##!
ee$vectors = Re(ee$vectors)
tail(ee$values)
last = which.min(ee$values[ee$values>1e-12])
L21 = L[-select,select]
Xhat = c(ee$vectors[,last], L21 %*% ee$vectors[,last]/ee$values[last]) / ee$values[last]
df_to_plot = data.frame(x=Xhat+Xbar[1], y=Xhat+Xbar[2], z=tt)
ggplot(df_to_plot, aes(x=y,y=x,col=tt)) + geom_point() +
theme_minimal(base_family = 'serif') +
scale_color_gradient(low=blue, high=orange)
```
Pretty bad. I think I screwed something up.
## Conclusions
1. Tuning parameter selection is critical
2. Construction of $\mathbb{K}$ is important: different similarity measures lead to drastically different solutions, often garbage
3. Gaussian projection gives orthogonal features (might work better in the LE result above)
4. Need some targeted theory
-->
# Clustering whirlwind
# K-means
## K-means
1. Select a number of clusters $K$.
2. Let $C_1,\ldots,C_K$ partition $\{1,2,3,\ldots,n\}$ such that
- All observations belong to some set $C_j$.
- No observation belongs to more than one set.
3. K-means attempts to form these sets by making [within-cluster
variation]{style="color: orangemain"}, $W(C_k)$, as small as
possible. $$\min_{C_1,\ldots,C_K} \sum_{k=1}^K W(C_k).$$
4. To Define $W$, we need a concept of distance. By far the most common
is Euclidean
$$W(C_k) = \frac{1}{|C_k|} \sum_{i,i' \in C_k} \norm{X_i - X_{i'}}_2^2.$$
That is, the average (Euclidean) distance between all cluster
members.
## K-means
It turns out $$\min_{C_1,\ldots,C_K} \sum_{k=1}^K W(C_k).$$ is too hard
of a problem to solve computationally ($K^n$ partitions!).
So, we make a greedy approximation:
1. Randomly assign observations to the $K$ clusters
2. Iterate until the cluster assignments stop changing:
- For each of $K$ clusters, compute the
centroid, which is the $p$-length
vector of the means in that cluster.
- Assign each observation to the cluster whose centroid is closest
(in Euclidean distance).
This procedure is guaranteed to decrease (1) at each step.
## K-means: A Summary
To fit K-means, you need to
1. Pick $K$ (inherent in the method)
2. Convince yourself you have found a good solution (due to the
randomized approach to the algorithm).
It turns out that 1. is difficult to do in a
principled way. We will discuss this next
For 2., a commonly used approach is to run
K-means many times with different starting points. Pick the solution
that has the smallest value for
$$\min_{C_1,\ldots,C_K} \sum_{k=1}^K W(C_k)$$
## Choosing the Number of Clusters
Why is it important?
- It might make a big difference (concluding there are $K = 2$ cancer
sub-types versus $K = 3$).
- One of the major goals of statistical learning is automatic
inference. A good way of choosing $K$ is certainly a part of this.
## Reminder: What does $K$-means do?
Given a number of clusters $K$, we (approximately) minimize:
$$\sum_{k=1}^K W(C_k)
%= \sum_{k=1}^K \frac{1}{|C_k|} \sum_{i,i' \in C_k} \sum_{j=1}^p (x_{ij} - x_{i'j})^2
= \sum_{k=1}^K\frac{1}{|C_k|} \sum_{i,i' \in C_k} ||X_i - X_{i'}||_2^2.$$
We can rewrite this in terms of the
centroids as
$$W(K) = \sum_{k=1}^K \sum_{i \in C_k} ||X_i - \overline{X}_k||_2^2,$$
## Minimizing $W$ in $K$
Of course, a lower value of $W$ is better. Why not minimize $W$?
Within-cluster variation measures how tightly
grouped the clusters are.
As we increase
$K$, this will always decrease.
What we are missing is between-cluster
variation, ie: how spread apart the groups
are $$B = \sum_{k=1}^K |C_k| ||\overline{X}_k - \overline{X} ||_2^2,$$
where $|C_k|$ is the number of points in $C_k$, and $\overline{X}$ is
the grand mean of all observations:
$$\overline{X} = \frac{1}{n} \sum_{i=1}^n X_i.$$
Sadly, just like $W$ can be made arbitrarily small, $B$ will always
be increasing with increasing $K$.
## $CH$ index
Ideally, we would like our cluster assignment to
simultaneously have small $W$ and large
$B$.
This is the idea behind __$CH$ index__. For
clustering assignments coming from $K$ clusters, we record $CH$ score:
$$CH(K) = \frac{B(K)/(K-1)}{W(K)/(n-K)}$$ To choose $K$, pick some
maximum number of clusters to be considered ($K_{\max} = 20$, for
example) and choose the value of $K$ that
$$\hat K = \argmax_{K \in \{ 2,\ldots, K_{\max} \}} CH(K).$$
__Note:__ $CH$ is undefined for $K =1$ (see Calinski, Harabasz, 1974)
## Dumb example