-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathchapter_03.html
More file actions
1629 lines (1494 loc) · 68.8 KB
/
Copy pathchapter_03.html
File metadata and controls
1629 lines (1494 loc) · 68.8 KB
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<title>Chapter 3: FPCA</title>
<script src="site_libs/header-attrs-2.25/header-attrs.js"></script>
<script src="site_libs/jquery-3.6.0/jquery-3.6.0.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/cosmo.min.css" rel="stylesheet" />
<script src="site_libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<style>h1 {font-size: 34px;}
h1.title {font-size: 38px;}
h2 {font-size: 30px;}
h3 {font-size: 24px;}
h4 {font-size: 18px;}
h5 {font-size: 16px;}
h6 {font-size: 12px;}
code {color: inherit; background-color: rgba(0, 0, 0, 0.04);}
pre:not([class]) { background-color: white }</style>
<script src="site_libs/jqueryui-1.13.2/jquery-ui.min.js"></script>
<link href="site_libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />
<script src="site_libs/tocify-1.9.1/jquery.tocify.js"></script>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<link href="site_libs/highlightjs-9.12.0/default.css" rel="stylesheet" />
<script src="site_libs/highlightjs-9.12.0/highlight.js"></script>
<link href="site_libs/font-awesome-6.4.2/css/all.min.css" rel="stylesheet" />
<link href="site_libs/font-awesome-6.4.2/css/v4-shims.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" />
<script defer src="https://use.fontawesome.com/releases/v5.0.3/js/all.js"></script>
<script defer src="https://use.fontawesome.com/releases/v5.0.0/js/v4-shims.js"></script>
<!-- Global site tag (gtag.js) - Google Analytics
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-151578452-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-151578452-1');
</script>
-->
<style type="text/css">
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
</style>
<style type="text/css">code{white-space: pre;}</style>
<script type="text/javascript">
if (window.hljs) {
hljs.configure({languages: []});
hljs.initHighlightingOnLoad();
if (document.readyState && document.readyState === "complete") {
window.setTimeout(function() { hljs.initHighlighting(); }, 0);
}
}
</script>
<link rel="stylesheet" href="styles.css" type="text/css" />
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
img {
max-width:100%;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
summary {
display: list-item;
}
details > summary > p:only-child {
display: inline;
}
pre code {
padding: 0;
}
</style>
<style type="text/css">
.dropdown-submenu {
position: relative;
}
.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
display: block;
}
.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #cccccc;
margin-top: 5px;
margin-right: -10px;
}
.dropdown-submenu:hover>a:after {
border-left-color: #adb5bd;
}
.dropdown-submenu.pull-left {
float: none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
border-radius: 6px 0 6px 6px;
}
</style>
<script type="text/javascript">
// manage active state of menu based on current page
$(document).ready(function () {
// active menu anchor
href = window.location.pathname
href = href.substr(href.lastIndexOf('/') + 1)
if (href === "")
href = "index.html";
var menuAnchor = $('a[href="' + href + '"]');
// mark the anchor link active (and if it's in a dropdown, also mark that active)
var dropdown = menuAnchor.closest('li.dropdown');
if (window.bootstrap) { // Bootstrap 4+
menuAnchor.addClass('active');
dropdown.find('> .dropdown-toggle').addClass('active');
} else { // Bootstrap 3
menuAnchor.parent().addClass('active');
dropdown.addClass('active');
}
// Navbar adjustments
var navHeight = $(".navbar").first().height() + 15;
var style = document.createElement('style');
var pt = "padding-top: " + navHeight + "px; ";
var mt = "margin-top: -" + navHeight + "px; ";
var css = "";
// offset scroll position for anchor links (for fixed navbar)
for (var i = 1; i <= 6; i++) {
css += ".section h" + i + "{ " + pt + mt + "}\n";
}
style.innerHTML = "body {" + pt + "padding-bottom: 40px; }\n" + css;
document.head.appendChild(style);
});
</script>
<!-- tabsets -->
<style type="text/css">
.tabset-dropdown > .nav-tabs {
display: inline-table;
max-height: 500px;
min-height: 44px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 4px;
}
.tabset-dropdown > .nav-tabs > li.active:before, .tabset-dropdown > .nav-tabs.nav-tabs-open:before {
content: "\e259";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li.active:before {
content: "\e258";
font-family: 'Glyphicons Halflings';
border: none;
}
.tabset-dropdown > .nav-tabs > li.active {
display: block;
}
.tabset-dropdown > .nav-tabs > li > a,
.tabset-dropdown > .nav-tabs > li > a:focus,
.tabset-dropdown > .nav-tabs > li > a:hover {
border: none;
display: inline-block;
border-radius: 4px;
background-color: transparent;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li {
display: block;
float: none;
}
.tabset-dropdown > .nav-tabs > li {
display: none;
}
</style>
<!-- code folding -->
<style type="text/css">
#TOC {
margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
position: relative;
width: 100%;
}
}
@media print {
.toc-content {
/* see https://github.com/w3c/csswg-drafts/issues/4434 */
float: right;
}
}
.toc-content {
padding-left: 30px;
padding-right: 40px;
}
div.main-container {
max-width: 1200px;
}
div.tocify {
width: 20%;
max-width: 260px;
max-height: 85%;
}
@media (min-width: 768px) and (max-width: 991px) {
div.tocify {
width: 25%;
}
}
@media (max-width: 767px) {
div.tocify {
width: 100%;
max-width: none;
}
}
.tocify ul, .tocify li {
line-height: 20px;
}
.tocify-subheader .tocify-item {
font-size: 0.90em;
}
.tocify .list-group-item {
border-radius: 0px;
}
</style>
</head>
<body>
<div class="container-fluid main-container">
<!-- setup 3col/9col grid for toc_float and main content -->
<div class="row">
<div class="col-xs-12 col-sm-4 col-md-3">
<div id="TOC" class="tocify">
</div>
</div>
<div class="toc-content col-xs-12 col-sm-8 col-md-9">
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-bs-toggle="collapse" data-target="#navbar" data-bs-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">FDA with R</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="about_authors.html">About the Authors</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Datasets
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="dataset_nhanes.html">NHANES</a>
</li>
<li>
<a href="dataset_covid19.html">COVID-19</a>
</li>
<li>
<a href="dataset_cd4.html">CD4</a>
</li>
<li>
<a href="dataset_content.html">Content</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Chapters
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="chapter_01.html">Chapter 1</a>
</li>
<li>
<a href="chapter_02.html">Chapter 2</a>
</li>
<li>
<a href="chapter_03.html">Chapter 3: FPCA</a>
</li>
<li>
<a href="chapter_04.html">Chapter 4: SoFR</a>
</li>
<li>
<a href="chapter_05.html">Chapter 5: FoSR</a>
</li>
<li>
<a href="chapter_06.html">Chapter 6: FoFR</a>
</li>
<li>
<a href="chapter_07.html">Chapter 7</a>
</li>
<li>
<a href="chapter_08.html">Chapter 8</a>
</li>
<li>
<a href="chapter_09.html">Chapter 9</a>
</li>
</ul>
</li>
<li>
<a href="scripts.html">Scripts</a>
</li>
<li>
<a href="https://github.com/FDAwithR">
<span class="fa fa-github"></span>
</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div id="header">
<h1 class="title toc-ignore">Chapter 3: FPCA</h1>
</div>
<div id="defining-fpca-and-connections-to-pca" class="section level2">
<h2>Defining FPCA and Connections to PCA</h2>
<p>This section illustrates functional principal component analysis
(fPCA) using both simulations. It is associated with Chapter 3 of the
book Functional Data Analysis with R. We use dense and dense with
missing observations data structures.</p>
<p>Functional PCA is closely related to multivariate PCA, but uses the
ordering of the observed data and smoothness of the underlying signal to
reduce the rank of the approximation and increase interpretability of
results. The idea is to find a small set of orthonormal functions that
explain most of the variability of the observed signal.</p>
</div>
<div id="simulations" class="section level2">
<h2>Simulations</h2>
<div id="dense-single-level-functional-data" class="section level3">
<h3>Dense single-level functional data</h3>
<p>We start by simulating dense functional data from a set of
orthonormal functions. In practice these functions are unknown and would
need to be estimated from the data. In simulations the orthonormal
functions are known. All functions are generated on an equally spaced
grid between <span class="math inline">\(0\)</span> and <span
class="math inline">\(1\)</span> from the model <span
class="math display">\[W_i(t)=\sum_{k=1}^K\xi_{ik}\phi_k(t)+\epsilon_{i}(t)\;,\]</span>
where <span class="math inline">\(K=4\)</span>, <span
class="math inline">\(\xi_{ik}\sim N(0,\lambda_K)\)</span>, <span
class="math inline">\(\epsilon_{i}(t)\sim N(0,\sigma^2)\)</span>, <span
class="math inline">\(\xi_{ik}\)</span> and <span
class="math inline">\(\epsilon_i(t)\)</span> are mutually independent
for all <span class="math inline">\(i\)</span>, <span
class="math inline">\(k\)</span>, and <span
class="math inline">\(t\)</span>. For illustration purposes we set <span
class="math inline">\(\lambda_k=0.5^{k-1}\)</span> for <span
class="math inline">\(k=1,\ldots,4\)</span> and <span
class="math inline">\(\sigma=2\)</span>, which corresponds to high
noise. The number of study participants is set to <span
class="math inline">\(n=50\)</span> and the number grid points is set to
<span class="math inline">\(p=3000\)</span> to illustrate a case of high
dimensional data. We start by simulating data that are completely
observed for every study participant. We use the Fourier orthonormal
functions <span class="math inline">\(\phi_k(t)\)</span>:<span
class="math display">\[\phi_1(t)=\sqrt{2}\sin(2\pi t); \;
\phi_2(t)=\sqrt{2}\cos(2\pi t);\; \phi_3(t)=\sqrt{2}\sin(4\pi t);\;
\phi_4(t)=\sqrt{2}\cos(4\pi t)\]</span></p>
<p>Below we display the R code for simulating the data.</p>
<pre class="r"><code>set.seed(5242022)
#### settings (I-->n,J-->p,N-->K)
n <- 50 # number of subjects
p <- 3000 # dimension of the data
t <- (1:p) / p # a regular grid on [0,1]
K <- 4 #number of eigenfunctions
sigma <- 2 ##standard deviation of the random noise
lambdaTrue <- c(1, 0.5, 0.5 ^ 2, 0.5 ^ 3) # True eigenvalues
# True eigenfunctions stored in a p by K dimensional matrix
#Each column corresponds to one eigenfunction
phi <- sqrt(2) * cbind(sin(2 * pi * t), cos(2 * pi * t),
sin(4 * pi * t), cos(4 * pi * t))</code></pre>
<p>Note that the functions <span
class="math inline">\(\phi_k(\cdot)\)</span> are orthonormal in <span
class="math inline">\(L_2\)</span>. However, we cannot work directly
with the functions and, instead, we work with a vector of observations
along the functions <span
class="math inline">\(\phi_k=\{\phi_k(t_1),\ldots,\phi_k(t_p)\}\)</span>,
which is in <span class="math inline">\({\mathcal{R}^p}\neq
L_2\)</span>. Even though we have started with orthonormal functions in
<span class="math inline">\(L_2\)</span> these vectors are not
orthonormal in <span class="math inline">\(\mathcal{R}^p\)</span>.
Indeed, they need to be normalized by <span
class="math inline">\(1/\sqrt{p}\)</span> and the cross products are
close to, but not exactly, zero because of numerical approximations.
However, after normalization the approximation to orthonormality in
<span class="math inline">\({\mathcal{R}^p}\)</span> is very good</p>
<pre class="r"><code>round(t(phi) %*% phi / p, digits = 5)
## [,1] [,2] [,3] [,4]
## [1,] 1 0 0 0
## [2,] 0 1 0 0
## [3,] 0 0 1 0
## [4,] 0 0 0 1</code></pre>
<p>To better explain this consider the <span
class="math inline">\(L_2\)</span> norm of any of the functions. It can
be shown that <span
class="math inline">\(\int_0^1\phi_k^2(t)dt=1\)</span> for every <span
class="math inline">\(k\)</span>, which indicates that the function has
norm <span class="math inline">\(1\)</span> in <span
class="math inline">\(L_2\)</span>. The integral can be approximated by
the Riemann sum <span
class="math display">\[1=\int_0^1\phi_k^2(t)dt\approx \sum_{j=1}^p
(t_j-t_{j-1})\phi_k^2(t_j)=\frac{1}{p}\sum_{j=1}^p\phi_k^2(t_j)=\frac{1}{p}||\phi_k||^2=\{\phi_k/\sqrt{p}\}^t\{\phi_k/\sqrt{p}\}\;.\]</span>
Here <span class="math inline">\(t_j=j/p\)</span> for <span
class="math inline">\(j=0,\ldots,p\)</span> and <span
class="math inline">\(||\phi_k||^2=\sum_{j=1}^p\phi_k^2(t_j)\)</span> is
the <span class="math inline">\(L_2\)</span> norm of the vector <span
class="math inline">\(\{\phi_k(t_1),\ldots,\phi_k(t_p)\}^t\)</span> in
<span class="math inline">\(\mathcal{R}^p\)</span>. This is different,
though closely related to, the <span class="math inline">\(L_2\)</span>
norm in the functional space on <span
class="math inline">\([0,1]\)</span>. The norm in the vector space is
the Riemann sum approximation to the integral of the square of the
function. The two have the same interpretation when the observed vectors
are divided by <span class="math inline">\(\sqrt{p}\)</span> (when data
are equally spaced and the distance between grid points is <span
class="math inline">\(1/p\)</span>). Slightly different constants are
necessary if functional data are on an interval that is not <span
class="math inline">\([0,1]\)</span> or observations have different
spacing.</p>
</div>
<div id="plots-of-functions-used-to-generate-the-data"
class="section level3">
<h3>Plots of functions used to generate the data</h3>
<p>Below we illustrate the eigenfunctions <span
class="math inline">\(\phi_k(t)\)</span>, <span
class="math inline">\(k=1,\ldots,4\)</span> used to generate the data.
Lighter colors corresponding to larger <span
class="math inline">\(k\)</span>, the index of the function in the
basis. The first two eigenfunctions (darker shades of blue) have a
period of one (lower frequency) and the second eigenfunctions (lighter
shades of blue) have a period of two (higher frequency).</p>
<pre class="r"><code>col.me <- c("darkblue", "royalblue", "cadetblue", "deepskyblue")
plot(NULL, xlim = c(0, 1), ylim = c(-1.5, 3.5),
xlab = "Functional domain", ylab = "Functional values",
bty = "n")
for(i in 1:4){
lines(t, phi[,i], lwd = 2.5, col = col.me[i])
}
legend(0.7, 3, legend = c(expression(phi[1](s)), expression(phi[2](s)), expression(phi[3](s)), expression(phi[4](s))),
col = col.me, lty = c(1, 1, 1, 1), lwd = c(3, 3, 3, 3), cex = 1, bty = "n")</code></pre>
<p><img src="chapter_03_files/figure-html/unnamed-chunk-2-1.png" width="90%" /></p>
</div>
<div id="data-generation-and-plotting" class="section level3">
<h3>Data generation and plotting</h3>
<p>Given the data generation mechanism structure it is important to see
how data are actually obtained and what types of structures can be
generated. This highlights the fact that fPCA provides a data generating
mechanism. The general recipe is to simulate the scores independently,
multiply them with the eigenfunctions, and add noise.</p>
<pre class="r"><code>#Generate independent N(0,1) in an nxK matrix
xi <- matrix(rnorm(n * K), n, K)
#Make scores on column k have variance lambda_k
xi <- xi %*% diag(sqrt(lambdaTrue))
#Obtain the signal by mutliplying the scores with the eigenvectors
X <- xi %*% t(phi); # of size I by J
#Add independent noise
Y <- X + sigma * matrix(rnorm(n * p), n, p)</code></pre>
<p>We now visualize the results of the simulations. First we plot the
first two functions. As over plotting all functions would make the plot
unreadable, in the second plot we use a heatmap. Heatmaps can be
misleading, especially when data are noisy and the signal to noise ratio
is low.</p>
<pre class="r"><code>#Plot the first two functions simulated
par(mar = c(4.5, 4, 0, 1))
plot(t, Y[1,], type = "l",
col = rgb(0, 0, 1, alpha = 0.5), ylim = c(-10, 10),
xlab = "Functional domain", ylab = "Functional values",
bty = "n")
lines(t, Y[2,], col = rgb(1, 0, 0, alpha = 0.5))</code></pre>
<p><img src="chapter_03_files/figure-html/unnamed-chunk-4-1.png" width="90%" /></p>
<pre class="r"><code>library(colorRamps)
library(viridis)
library(RColorBrewer)
colme <- colorRampPalette(brewer.pal(10, "RdYlBu"),bias=1)(100)
#Display the heatmap of all the functions
par(mar = c(4.5, 4, 0.5, 1))
image(t(Y), xlab = "Functional domain (Time)", ylab = "Study participants",
axes = FALSE, col = colme)
mtext(text = 5 * (1:10), side = 2, line = 0.3, at = seq(1 / 10, 1, length = 10), las = 1, cex = 0.8)
mtext(text = seq(1 / 10, 1, length = 10), side = 1, line = 0.3, at = seq(1 / 10, 1, length = 10), las = 1, cex = 0.8)</code></pre>
<p><img src="chapter_03_files/figure-html/unnamed-chunk-5-1.png" width="90%" /></p>
</div>
<div id="obtaining-the-fpca-results" class="section level3">
<h3>Obtaining the FPCA results</h3>
<p>Given the data generated and displayed we would like to apply
standard (raw) and functional (smooth) PCA and compare the results
obtained.</p>
<p>First conduct direct PCA analysis on the raw data without
smoothing</p>
<pre class="r"><code>results_raw <- prcomp(Y)
#Obtain the estimated eigenvalues
raw_eigenvalues <- results_raw$sdev ^ 2 / p
#Obtain the estimated eigenvectors
#Normalize to match with the eigenfunctions
raw_eigenvectors <- sqrt(p) * results_raw$rotation
#Eigenvectors are unique up to sign
#If eigenvectors are negative correlated with the true eigenvectors
#Change their sign
for(k in 1:K){
if(raw_eigenvectors[,k] %*% phi[,k] < 0)
raw_eigenvectors[,k] <- -raw_eigenvectors[,k]
}</code></pre>
<p>Now apply the fpca.face smoothing and display the results. The
function uses one argument, the <span class="math inline">\(n\times
p\)</span> dimensional matrix of data, where each row corresponds to one
study participant and each column corresponds to a location on the
domain (e.g., time).</p>
<pre class="r"><code>library(refund)
#Here we use more parameters for illustration purposes
results <- fpca.face(Y,center = TRUE, argvals = t, knots = 100, pve = 0.9999, var = TRUE)
#These are re-scaled to appear on the scale of the original functions
Phi <- sqrt(p) * results$efunctions
eigenvalues <- results$evalues / p
#If eigenvectors are negative correlated with the true eigenvectors
#Change their sign
for(k in 1:K){
if(Phi[,k] %*% phi[,k] < 0)
Phi[,k] <- -Phi[,k]
}</code></pre>
<p>Plot the true eigenfunctions versus estimated eigenfunctions using
raw and smooth PCA. The plot indicates that raw PCA results in highly
variable estimates of the true PCA. In contrast smooth PCA provides
smooth estimators that are more interpretable and reasonable. Smooth PCA
eigenvectors seem to track pretty closely to the mean of the
eigenvectors estimated from raw data. Both estimators do not overlap
perfectly over the true eigenvectors. This is reasonable to observe in
one simulation. However, checking whether the estimators are biased
would require multiple simulations and taking the average over these
simulations.</p>
<pre class="r"><code>par(mar = c(4.5, 4.5, 2, 2))
par(mfrow = c(K / 2, 2))
seq <- (1:(p / 10)) * 10
for(k in 1:K){
plot(t, raw_eigenvectors[,k], type = "l", col = "grey70", lwd = 0.2,
ylim = c(-3, 3), ylab = paste("Eigenfunction ", k, sep = ""), xlab = "Time", bty = "n")
lines(t[seq], phi[seq, k], lwd = 3, col = "blue", lty = 1)
lines(t[seq], Phi[seq, k], lwd = 3, col = "red", lty = 3)
}</code></pre>
<p><img src="chapter_03_files/figure-html/unnamed-chunk-8-1.png" width="90%" /></p>
</div>
<div id="compare-the-estimated-eigenvalues-using-pca-and-fpca"
class="section level3">
<h3>Compare the estimated eigenvalues using PCA and FPCA</h3>
<p>We next compare the true eigenvalues (blue line) with the estimated
eigenvalues using raw PCA (gray dotted line) and using smooth PCA (red
dotted line). Notice that the smooth estimated eigenvalues are very
close to the true eigenvalues. In contrast, eigenvalues estimated from
raw PCA overestimate the true eigenvalues by quite a margin. This is
especially true when the true eigenvalues are zero (no signal). Raw PCA
continues to assign signal when there is none. Moreover, the estimated
eigenvalues using raw PCA decrease slowly to zero forming almost a
straight line. This feature can be observed in many applications. If
observed, it could suggest that data are noisier than what standard PCA
assumes (no noise, just smaller signals as the principal component
number increases).</p>
<pre class="r"><code>true_eigenvalues <- c(lambdaTrue, rep(0, 46))
results <- fpca.face(Y, center = TRUE, argvals = t, knots = 100, pve = 0.9999, var = TRUE)
smooth_eigenvalues <- rep(0, 50)
ll <- length(results$evalues)
smooth_eigenvalues[1:ll] <- results$evalues / p
par(mar = c(4.5, 4, 0.5, 1))
plot(1:50, true_eigenvalues, lwd = 3, col = "blue", bty = "n", type = "l",
xlab = "Index", ylab = "Eigenvalues")
lines(1:50, raw_eigenvalues, lwd = 3, xlab = "Index", ylab = "Eigenvalues", col = "grey70", lty = 3)
lines(1:50, smooth_eigenvalues, col = "red", lwd = 3, lty = 3)
legend(30, 1, legend = c("True", "Raw", "Smooth"),
col = c("blue", "grey70", "red"), lty = c(1, 3, 3), lwd = c(3, 3, 3), cex = 1, bty = "n")</code></pre>
<p><img src="chapter_03_files/figure-html/unnamed-chunk-9-1.png" width="90%" /></p>
</div>
<div id="show-how-fpca.face-works-with-nas" class="section level3">
<h3>Show how fpca.face works with NAs</h3>
<p>We now show how to use smooth functional PCA even with substantial
amount of missing observations. Start by generating a matrix of the same
dimension with Y, but containing <span
class="math inline">\(80\)</span>% missing observations</p>
<pre class="r"><code>#Missing data percentage
miss_perc <- 0.8
#Randomly assign what data are missing
NA_mat <- matrix(rbinom(p * n, 1, miss_perc), ncol = p)
Y_w_NA <- Y
#Build the matrix with missing observations
Y_w_NA[NA_mat == 1] <- NA
#Conduct fPCA on the matrix with missing data
results_NA <- fpca.face(Y_w_NA, center = TRUE, argvals = t, knots = 100, pve = 0.99)
#Obtain the fPCA estimtors of eigenfunctions
ef_NA <- sqrt(p) * results_NA$efunctions
#If eigenvectors are negative correlated with the true eigenvectors
#Change their sign
for(k in 1:K){
if(ef_NA[,k] %*% phi[,k] < 0)
ef_NA[,k] <- -ef_NA[,k]
}</code></pre>
<pre class="r"><code>par(mar = c(4.5, 4.5, 2, 2))
par(mfrow = c(K / 2, 2))
seq <- (1:(p / 10)) * 10
for(k in 1:K){
plot(t[seq], phi[seq, k], ylim = c(-3, 3), type = "l", col = "blue",
ylab = paste("Eigenfunction ", k, sep = ""), xlab = "Time", bty = "n", lwd = 2)
lines(t[seq], ef_NA[seq, k], type = "l", col = "red", lty = 3, lwd = 3)
} </code></pre>
<p><img src="chapter_03_files/figure-html/unnamed-chunk-11-1.png" width="90%" /></p>
<p>Note that even with <span class="math inline">\(80\)</span>% missing
data, the estimated eigenvectors using fPCA (red dotted line) are very
close to the true eigenvectors (blue solid lines). These estimators
start to degrade when the missing data becomes extrem and only a few
observations are available per function.</p>
</div>
</div>
<div id="application-to-nhanes" class="section level2">
<h2>Application to NHANES</h2>
<p>We begin by by reading in of the subject-level NHANES data
(nhanes_fda_with_r.rds). Note that we restrict the sample to
participants aged 5 to 80.</p>
<pre class="r"><code>## read in the data (assumes data are in the current working directory)
df_subj <- read_rds(here::here("data","nhanes_fda_with_r.rds"))
## filter out participants 80+ and younger than 5
df_subj <-
df_subj %>%
filter(age >= 5, age < 80)</code></pre>
<div id="functional-principal-components-analysis"
class="section level3">
<h3>Functional Principal Components Analysis</h3>
<p>Next, we compare FPCA to PCA on the minute level MIMS profiles
(subject average MIMS across days). For FPCA, we apply the FACE method
(<em>refund::fpca.face</em>) using the package defaults. For PCA we
estimate the principal components using the connection between SVD and
eigen decomposition of the empirical covariance matrix.</p>
<pre class="r"><code>## Do fPCA on the subject-average MIMS profiles
MIMS_mat <- unclass(df_subj$MIMS)
fpca_MIMS_subj <- fpca.face(MIMS_mat)
## Do PCA on the subject-average MIMS profiles
# subtract column (minute) means to center the "varianbles"
MIMS_mn <- colMeans(MIMS_mat)
MIMS_mat_cn <- sweep(MIMS_mat, MARGIN=2, STATS=MIMS_mn, FUN="-")
# then do SVD
svd_MIMS_subj <- svd(MIMS_mat_cn)</code></pre>
<p>We can then plot the first four principal components from each
approach.</p>
<pre class="r"><code>## plot the results of PCA vs fpca
sind <- seq(0,1,len=1440)
xinx <- (c(1,6,12,18,23)*60+1)/1440
xinx_lab <- c("01:00","06:00","12:00","18:00","23:00")
df_plt <-
data.frame("PC" = rep(paste0("PC",1:4), each=1440),
"time" = rep(sind, 4),
"fPCA" = as.vector(fpca_MIMS_subj$efunctions[,1:4]),
"PCA" = -as.vector(svd_MIMS_subj$v[,1:4]))
df_plt <-
df_plt %>%
pivot_longer(cols=c("fPCA","PCA"))
fpca_vs_pca_NHANES <-
df_plt %>%
mutate(name = factor(name, levels=c("fPCA","PCA"),labels=c("(A) fPCA","(B) PCA"))) %>%
ggplot() +
geom_line(aes(x=time, y=value, color=PC), lwd=1.25) +
facet_grid(~name) +
theme_minimal(base_size=18) +
xlab("Time of Day (s)") +
ylab(expression("Estimated Eigenfunctions (" ~ phi[k](s) ~ ")")) +
scale_x_continuous(breaks=xinx, labels=xinx_lab) +
theme(legend.position=c(.9,.9),
panel.grid.major.y = element_blank(),
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.minor.y = element_blank(),
axis.line.x = element_line(linewidth = 1, linetype = "solid", colour = "black"),
axis.line.y = element_line(linewidth = 1, linetype = "solid", colour = "black"),
strip.text = element_text(face="bold", size=18, hjust=0.03),
axis.ticks.x = element_line(linewidth = 1),
axis.ticks.y = element_line(linewidth = 1)) +
labs(color="Eigenfunction") +
guides(color=guide_legend(ncol=2))
fpca_vs_pca_NHANES</code></pre>
<p><img src="chapter_03_files/figure-html/plot_fpca_vs_pca-1.png" width="90%" /></p>
<p>Interpreting the functional PCs may be challenging, particularly for
PCs which explain a relatively low proportion of variance. One
visualization technique is to plot the distribution of curves which load
lowest/highest on a particular PC. Here, we plot the individuals in the
bottom and top 10% of scores for the first four PCs. The code below
calculates these quantities.</p>
<pre class="r"><code>## plot individual curves loading highly/lowly on the first 4 PCs
# set the seed for reproducibility
set.seed(1983)
# number of eigenfunctions to plot
K <- 4
# number of sample curves to plot for each PC
n_plt <- 10
# create container data frame for storing/plotting the individual curves
# for high/low loadings on each of the K PCs
# this data frame will have
# 2 * K * n_plt * 1440 rows
# 2 = high/low
# K = # of PCs
# n_plt = number of individual curves to plot
# 1440 = minutes in a day
df_plt_ind <- expand.grid("sind" = sind,
"id" = 1:n_plt,
"high" = c("high","low"),
"PC" = paste0("PC ",1:4)) %>%
mutate(high = relevel(high, ref="low"))
# create container data frame for storing/plotting the average curves
# for high/ow loadings on each of the first K PCs
# this data frame will have
# 2 * K * 1440 rows
# 2 = high/low
# K = # of PCs
# 1440 = minutes in a day
df_plt_ind_mu <- expand.grid("sind" = sind,
"high" = c("high","low"),
"PC" = paste0("PC ",1:4),
"value" = NA)%>%
mutate(high = relevel(high, ref="low"))
# NOTE: the code below assumes an ordering of rows implied by the construction
# used by the expand.grid function
# create empty vectors to store the average and individual curves, respectively
mu_vec <- c()
ind_vec <- c()
# loop over eigenfunctions
for(k in 1:K){
# get the 10th and 90th percentiles of the scores
q_k <- quantile(fpca_MIMS_subj$scores[,k],c(0.1,0.9))
# get indices associated with low/high scores
inx_low_k <- which(fpca_MIMS_subj$scores[,k] <= q_k[1])
inx_high_k <- which(fpca_MIMS_subj$scores[,k] > q_k[2])
# get the average curves in each quantile: 0-.1, .9-1
mu_low_k <- colMeans(fpca_MIMS_subj$Yhat[inx_low_k,])
mu_high_k <- colMeans(fpca_MIMS_subj$Yhat[inx_high_k,])
# concatenate with existing mean vector
mu_vec <- c(mu_vec, mu_low_k, mu_high_k)
# get individual curves for the n_plt randomly selected participants
val_low_k <- as.vector(t(fpca_MIMS_subj$Yhat[sample(inx_low_k, size=n_plt),]))
val_high_k <- as.vector(t(fpca_MIMS_subj$Yhat[sample(inx_high_k, size=n_plt),]))
# concatenate with existing individual vector
ind_vec <- c(ind_vec, val_low_k, val_high_k)
}
# add the mean and individual vectors into the data frames constructed before the loop
df_plt_ind_mu$value <- mu_vec
df_plt_ind$value <- ind_vec</code></pre>
<p>We can then plot the average and individual curves. We do see the
individual curves which load highly on each of the first four PCs do, on
average, largely reflect the shapes of the PCs, with this visual effect
most strong for the first three PCs.</p>
<pre class="r"><code>plt_ind <-
df_plt_ind %>%
mutate(id = factor(id),
id_high = paste0(id,"_",high)) %>%
ggplot() +
geom_line(aes(x=sind, y=value, group=id_high, color=high),alpha=0.5) +
facet_wrap(~PC,ncol=2) +
theme_minimal(base_size=18) +
scale_x_continuous(breaks=xinx, labels=xinx_lab) +
theme(legend.position="none",
panel.grid.major.y = element_blank(),
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.minor.y = element_blank(),
axis.line.x = element_line(size = 1, linetype = "solid", colour = "black"),
axis.line.y = element_line(size = 1, linetype = "solid", colour = "black"),
strip.text = element_text(face="bold", size=18, hjust=0.03),
axis.ticks.x = element_line(size = 1),
axis.ticks.y = element_line(size = 1)) +
xlab("Time of Day (s)") + ylab(expression("MIMS: " ~ W[i](s))) +
geom_line(aes(x=sind, y=value, group=high, color=high),
data=df_plt_ind_mu, lwd=2)
## Warning: The `size` argument of `element_line()` is deprecated as of ggplot2 3.4.0.
## ℹ Please use the `linewidth` argument instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
plt_ind</code></pre>
<p><img src="chapter_03_files/figure-html/plt_high_low-1.png" width="90%" /></p>
</div>
</div>
<div id="generalized-functional-principal-components-analysis-gfpca"
class="section level2">
<h2>Generalized Functional Principal Components Analysis (GFPCA)</h2>
<p>Functional data come in many forms. For many types of continuous
functional data, the Gaussian assumption may not be reasonable. In this
case, it may be be possible to apply a set of transformations <span
class="math inline">\(g_s:\mathbb{R}\rightarrow\mathbb{R}\)</span> such
that <span class="math inline">\(g_s\{W_i(s)\}\)</span> is approximately
Gaussian for every <span class="math inline">\(s\in S\)</span>. In this
case PCA and FPCA can be applied to the transformed data. However are
not be always available or desirable. Moreover, when data are not
continuous (e.g., binary) transformations do not solve the underlying
problem. However, we can still apply the principals of FPCA if we assume
a the data are generated from a latent Gaussian process.</p>
<p>Suppose <span class="math inline">\(W_i(s)\)</span>, <span
class="math inline">\(s\in S\)</span> are non-Gaussian observed data. We
assume that <span class="math inline">\(W_i(s_j)\)</span> have a
distribution with mean <span
class="math inline">\(E\{W_i(s_j)\}=\mu_i(s_j)\)</span>, where <span
class="math display">\[\begin{equation*}
\eta_i(s_j)=h\{\mu_i(s_j)\}=X_i(s_j)=\beta_0(s_j) +
\sum_{k=1}^K\xi_{ik}\phi_k(s_j)\;,
\end{equation*}\]</span> <span
class="math inline">\(\eta_i(\cdot)\)</span> is the linear predictor,
<span class="math inline">\(h(\cdot)\)</span> is a link function, <span
class="math inline">\(\beta_0(\cdot)\)</span> is a function that varies
smoothly along the domain <span class="math inline">\(S\)</span>, <span
class="math inline">\(\phi_k(\cdot)\)</span> are assumed to be
orthonormal functions in the <span class="math inline">\(L_2\)</span>
norm, and <span class="math inline">\(\xi_{ik}\)</span> are mutually
uncorrelated random variables. The distribution of <span
class="math inline">\(W_i(s_j)\)</span> could belong to the exponential
family or any type of non-Gaussian distribution. The expectation is that
the number of orthonormal functions, <span
class="math inline">\(K\)</span>, is not too large and the functions
<span class="math inline">\(\phi_k(\cdot)\)</span>, <span
class="math inline">\(k=1,\ldots,K\)</span>, are unknown and will be
estimated from the data. The advantage of this conceptual model is that,
once the functions <span class="math inline">\(\phi_k(\cdot)\)</span>
are estimated, the model becomes a generalized linear mixed model (GLMM)
with a small number of uncorrelated random effects. This transforms the
high-dimensional functional model with non-Gaussian measurements into a
low-dimensional GLMM that can be used for estimation and inference.</p>
<div id="application-to-nhanes-1" class="section level3">
<h3>Application to NHANES</h3>
<p>The fast GFPCA method is first shown as presented in the book, as a
4-step procedure estimated manually using mase <strong>R</strong>
functions in combination with <strong>mgcv</strong>. Afterward, we show
how to fit the same GFPCA model using the <strong>fastGFPCA</strong>
package, which wraps this code into a single estimation function.</p>
<p>The GFPCA method decribed in the book is applied to binarized
physical activity (active/inactive) profiles. There are many possible
ways to define such a profile. For the purposes of this application, we
chose to first binarize the day-level data, then take the median across
days (rounding up in the event of a tie). To do this we first read in
the multi-level (day-level) physical activity data.</p>
<pre class="r"><code>df_gfpca_subj_day <- read_rds(here::here("data","nhanes_fda_with_r_ml.rds"))</code></pre>
<p>The next step is to binarize the day level data, then take the median
across days. Here we use a threshold of 10.558 which was suggested by a
recently published paper comparing MIMS to activity counts.</p>
<pre class="r"><code>## Y_ij(s)
# extract the day-level activity data
Ymat <- unclass(df_gfpca_subj_day$MIMS)
## Y_ij^B(s)
# binarize the data (this vectorizes the matrix), then put back in matrix format
YBmat <- matrix(as.numeric(Ymat >= 10.558), nrow(Ymat), ncol(Ymat), byrow=FALSE)
## Create X_i(s)
# get unique IDs for all participants and their corresponding row indices
uid <- unique(df_gfpca_subj_day$SEQN)
nid <- length(uid)
inx_rows <- split(1:nrow(YBmat), factor(df_gfpca_subj_day$SEQN, levels=uid))
# calculate X_i(s)
Xmat <- t(vapply(inx_rows, function(x) round(colMeans(YBmat[x,,drop=FALSE])),
numeric(1440)))
rm(Ymat, YBmat)</code></pre>
<p>Having created our binarized activity profiles, we then set up a long
data matrix which will be used for estimation.</p>
<pre class="r"><code>## Put the data in long format
sind <- 1:1440
df_gfpca <- data.frame(SEQN = as.factor(rep(uid, each=1440)),
X = as.vector(t(Xmat)),
sind = sind)</code></pre>
<p>To show what these binarized activity profiles look like, we plot
profiles for four randomly selected participants.</p>
<pre class="r"><code>## plot 4 profiles
set.seed(191)
n_plt <- 4
ids_plt <- sample(uid, size=n_plt, replace=F)
plt_profiles_gfpca <-
df_gfpca %>%
# filter(SEQN %in% paste0("SEQN ", ids_plt)) %>%
filter(SEQN %in% as.character(ids_plt)) %>%
mutate(sind_bin = floor(sind/60)) %>%
group_by(SEQN, sind_bin) %>%
mutate(sind_bin = mean(sind),
X_bin = mean(X)) %>%
ungroup() %>%
ggplot() +
geom_point(aes(x=sind, y=X), alpha=0.25) +
geom_line(aes(x=sind_bin, y=X_bin),linewidth=1.5,color="red") +