-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy patheda.Rmd
1668 lines (1153 loc) · 48.2 KB
/
eda.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
\providecommand{\E}{\operatorname{E}}
\providecommand{\V}{\operatorname{Var}}
\providecommand{\Cov}{\operatorname{Cov}}
\providecommand{\cov}{\operatorname{cov}}
\providecommand{\se}{\operatorname{se}}
\providecommand{\logit}{\operatorname{logit}}
\providecommand{\iid}{\; \stackrel{\text{iid}}{\sim}\;}
\providecommand{\asim}{\; \stackrel{.}{\sim}\;}
\providecommand{\xs}{x_1, x_2, \ldots, x_n}
\providecommand{\Xs}{X_1, X_2, \ldots, X_n}
\providecommand{\bB}{\boldsymbol{B}}
\providecommand{\bb}{\boldsymbol{\beta}}
\providecommand{\bx}{\boldsymbol{x}}
\providecommand{\bX}{\boldsymbol{X}}
\providecommand{\by}{\boldsymbol{y}}
\providecommand{\bY}{\boldsymbol{Y}}
\providecommand{\bz}{\boldsymbol{z}}
\providecommand{\bZ}{\boldsymbol{Z}}
\providecommand{\be}{\boldsymbol{e}}
\providecommand{\bE}{\boldsymbol{E}}
\providecommand{\bs}{\boldsymbol{s}}
\providecommand{\bS}{\boldsymbol{S}}
\providecommand{\bP}{\boldsymbol{P}}
\providecommand{\bI}{\boldsymbol{I}}
\providecommand{\bD}{\boldsymbol{D}}
\providecommand{\bd}{\boldsymbol{d}}
\providecommand{\bW}{\boldsymbol{W}}
\providecommand{\bw}{\boldsymbol{w}}
\providecommand{\bM}{\boldsymbol{M}}
\providecommand{\bPhi}{\boldsymbol{\Phi}}
\providecommand{\bphi}{\boldsymbol{\phi}}
\providecommand{\bN}{\boldsymbol{N}}
\providecommand{\bR}{\boldsymbol{R}}
\providecommand{\bu}{\boldsymbol{u}}
\providecommand{\bU}{\boldsymbol{U}}
\providecommand{\bv}{\boldsymbol{v}}
\providecommand{\bV}{\boldsymbol{V}}
\providecommand{\bO}{\boldsymbol{0}}
\providecommand{\bOmega}{\boldsymbol{\Omega}}
\providecommand{\bLambda}{\boldsymbol{\Lambda}}
\providecommand{\bSig}{\boldsymbol{\Sigma}}
\providecommand{\bSigma}{\boldsymbol{\Sigma}}
\providecommand{\bt}{\boldsymbol{\theta}}
\providecommand{\bT}{\boldsymbol{\Theta}}
\providecommand{\bpi}{\boldsymbol{\pi}}
\providecommand{\argmax}{\text{argmax}}
\providecommand{\KL}{\text{KL}}
\providecommand{\fdr}{{\rm FDR}}
\providecommand{\pfdr}{{\rm pFDR}}
\providecommand{\mfdr}{{\rm mFDR}}
\providecommand{\bh}{\hat}
\providecommand{\dd}{\lambda}
\providecommand{\q}{\operatorname{q}}
```{r, message=FALSE, echo=FALSE, cache=FALSE}
source("./customization/knitr_options.R")
```
```{r, message=FALSE, echo=FALSE, cache=FALSE}
library("datasets")
library("animation")
library("gganimate")
```
# (PART) Expoloratory Data Analysis {-}
# Exploratory Data Analysis
## What is EDA?
Exploratory data analysis (EDA) is the process of analzying data to uncover their key features.
John Tukey pioneered this framework, writing a seminal book on the topic (called *Exploratory Data Analysis*).
EDA involves calculating numerical summaries of data, visualizing data in a variety of ways, and considering interesting data points.
Before any model fitting is done to data, some exploratory data analysis should always be performed.
*Data science seems to focus much more on EDA than traditional statistics.*
## Descriptive Statistics Examples
- Facebook's [Visualizing Fake Friendships](https://www.facebook.com/note.php?note_id=469716398919) (side note: [a discussion](http://flowingdata.com/2010/12/13/facebook-worldwide-friendships-mapped/))
- [Hans Rosling: Debunking third-world myths with the best stats you've ever seen](https://www.youtube.com/watch?v=RUwS1uAdUcI&t=3m22s&version=3)
- Flowing Data's [A Day in the Life of Americans](http://flowingdata.com/2015/12/15/a-day-in-the-life-of-americans/)
## Components of EDA
EDA involves calculating quantities and visualizing data for:
- Checking the *n*'s
- Checking for missing data
- Characterizing the distributional properties of the data
- Characterizing relationships among variables and observations
- Dimension reduction
- Model formulation
- Hypothesis generation
... and there are possible many more activities one can do.
## Data Sets
For the majority of this chapter, we will use some simple data sets to demonstrate the ideas.
### Data `mtcars`
Load the `mtcars` data set:
```{r}
library("tidyverse") # why load tidyverse?
data("mtcars", package="datasets")
mtcars <- as_tibble(mtcars)
head(mtcars)
```
### Data `mpg`
Load the `mpg` data set:
```{r, cache=FALSE, message=FALSE}
data("mpg", package="ggplot2")
head(mpg)
```
### Data `diamonds`
Load the `diamonds` data set:
```{r, cache=FALSE, message=FALSE}
data("diamonds", package="ggplot2")
head(diamonds)
```
### Data `gapminder`
Load the `gapminder` data set:
```{r, cache=FALSE, message=FALSE}
library("gapminder")
data("gapminder", package="gapminder")
gapminder <- as_tibble(gapminder)
head(gapminder)
```
# Numerical Summaries of Data
## Useful Summaries
- **Center**: mean, median, mode
- **Quantiles**: percentiles, five number summaries
- **Spread**: standard deviation, variance, interquartile range
- **Outliers**
- **Shape**: skewness, kurtosis
- **Concordance**: correlation, quantile-quantile plots
## Measures of Center
Suppose we have data points $x_1, x_2, \ldots, x_n$.
**Mean**: $$\overline{x} = \frac{x_1 + x_2 + \cdots + x_n}{n}$$
**Median**: Order the points $x_{(1)} \leq x_{(2)} \leq \cdots \leq x_{(n)}$. The median is the middle value:
- $x_{((n+1)/2)}$ if $n$ is odd
- $(x_{(n/2)} + x_{(n/2+1)})/2$ if $n$ is even
**Mode**: The most frequently repeated value among the data (if any). If there are ties, then there is more than one mode.
## Mean, Median, and Mode in R
Let's calculate these quantities in R.
```{r}
mean(mtcars$mpg)
median(mtcars$mpg)
sample_mode <- function(x) {
as.numeric(names(which(table(x) == max(table(x)))))
}
sample_mode(round(mtcars$mpg))
```
It appears there is no R base function for calculating the mode.
## Quantiles and Percentiles
The $p$th **percentile** of $x_1, x_2, \ldots, x_n$ is a number such that $p$% of the data are less than this number.
The 25th, 50th, and 75th percentiles are called 1st, 2nd, and 3rd "quartiles", respectively. These are sometimes denoted as Q1, Q2, and Q3. The median is the 50th percentile aka the 2nd quartile aka Q2.
In general, $q$-**quantiles** are cut points that divide the data into $q$ approximately equally sized groups. The cut points are the percentiles $1/q, 2/q, \ldots, (q-1)/q.$
## Five Number Summary
The "five number summary" is the minimum, the three quartiles, and the maximum. This can be calculated via `fivenum()` and `summary()`. [They can produce different values.](https://chemicalstatistician.wordpress.com/2013/08/12/exploratory-data-analysis-the-5-number-summary-two-different-methods-in-r-2/) Finally, `quantile()` extracts any set of percentiles.
```{r}
fivenum(mtcars$mpg)
summary(mtcars$mpg)
quantile(mtcars$mpg, prob=seq(0, 1, 0.25))
```
## Measures of Spread
The variance, standard deviation (SD), and interquartile range (IQR) measure the "spread" of the data.
**Variance**:
$$s^2 = \frac{\sum_{i=1}^n \left(x_i - \overline{x}\right)^2}{n-1}$$
**Standard Deviation**: $s = \sqrt{s^2}$
**Iterquartile Range**: IQR $=$ Q3 $-$ Q1
The SD and IQR have the same units as the observed data, but the variance is in squared units.
## Variance, SD, and IQR in R
Variance:
```{r}
var(mtcars$mpg)
```
Standard deviation:
```{r}
sd(mtcars$mpg)
```
Interquartile range:
```{r}
IQR(mtcars$mpg)
diff(fivenum(mtcars$mpg)[c(2,4)])
```
## Identifying Outliers
An **outlier** is an unusual data point. Outliers can be perfectly valid but they can also be due to errors (as can non-outliers).
One must define what is meant by an outlier.
One definition is a data point that less than Q1 or greater than Q3 by 1.5 $\times$ IQR or more.
Another definition is a data point whose difference from the mean is greater than 3 $\times$ SD or more. For Normal distributed data (bell curve shaped), the probability of this is less than 0.27%.
## Application to `mtcars` Data
```{r}
sd_units <- abs(mtcars$wt - mean(mtcars$wt))/sd(mtcars$wt)
sum(sd_units > 3)
max(sd_units)
iqr_outlier_cuts <- fivenum(mtcars$wt)[c(2,4)] +
c(-1.5, 1.5)*diff(fivenum(mtcars$wt)[c(2,4)])
sum(mtcars$wt < iqr_outlier_cuts[1] |
mtcars$wt > iqr_outlier_cuts[2])
```
## Measuring Symmetry
The **skewness** statistic measures symmetry of the data. It is calculated by:
$$
\gamma = \frac{\sum_{i=1}^n (x_i - \overline{x})^3/n}{s^3}
$$
A negative number is left-skewed, and a positive number is right-skewed.
Note: Use of $n$ vs. $n-1$ may vary -- check the code.
## `skewness()` Function
In R, there is a function call `skewness()` from the `moments` package for calculating this statistic on data.
```{r}
library(moments)
gapminder %>% filter(year==2007) %>% select(gdpPercap) %>%
skewness()
gapminder %>% filter(year==2007) %>% select(gdpPercap) %>%
log() %>% skewness()
rnorm(10000) %>% skewness()
```
## Measuring Tails
The tails of a distribution are often described as being heavy or light depending on how slowly they descend.
This can be measured through statistic called **kurtosis**:
$$
\kappa = \frac{\sum_{i=1}^n (x_i - \overline{x})^4/n}{s^4}
$$
As with skewness $\gamma$, use of $n$ vs $n-1$ may vary.
## Excess Kurtosis
For a standard Normal distribution (mean 0 and standard deviation 1), the kurtosis is on average 3.
Therefore, a measure called "excess kurtosis" is defined to be $\kappa - 3$. A positive value implies heavier tails and a negative value implies lighter tails.
## `kurtosis()` Function
In R, there is a function call `kurtosis()` from the `moments` package for calculating this statistic on data.
```{r}
library(moments)
gapminder %>% filter(year==2007) %>% select(gdpPercap) %>%
kurtosis()
gapminder %>% filter(year==2007) %>% select(gdpPercap) %>%
log() %>% kurtosis()
rnorm(10000) %>% kurtosis()
```
## Visualizing Skewness and Kurtosis
```{r, echo=FALSE}
y <- gapminder %>% filter(year==2007) %>% select(gdpPercap) %>%
unlist()
hist(y, freq=FALSE, main=" ", ylab=" ", xlab="gdpPercap", nclass=20, col="lightgray")
x <- seq(min(y), max(y), length.out=200)
lines(x, dnorm(x, mean=mean(y), sd=sd(y)), lw=3)
```
```{r, echo=FALSE}
y <- gapminder %>% filter(year==2007) %>% select(gdpPercap) %>%
unlist()
y <- log(y)
hist(y, freq=FALSE, main=" ", ylab=" ", xlab="gdpPercap", nclass=20, col="lightgray")
x <- seq(min(y), max(y), length.out=200)
lines(x, dnorm(x, mean=mean(y), sd=sd(y)), lw=3)
```
## Covariance and Correlation
- It is often the case that two or more quantitative variables are measured on each unit of observation (such as an individual).
- We are then often interested in characterizing how pairs of variables are associated or how they vary together.
- Two common measures for this are called "covariance" and "correlation", both of which are most well suited for measuring linear associations
### Covariance
Suppose we observe $n$ pairs of data $(x_1, y_1), (x_2, y_2), \ldots, (x_n, y_n)$. Their sample covariance is
$$
\cov_{xy} = \frac{\sum_{i=1}^n (x_i - \overline{x}) (y_i - \overline{y})}{(n-1)},
$$
which meausers how the two variables "covary" about their respective means. Large positive numbers indicate concordance of deviations from the mean, and large negative numbers indicated discordance (so opposite sides of the mean).
### Pearson Correlation
Pearson correlation is sample covariance scaled by the variables' standard deviations, meaning correlation is a unitless measure of variation about the mean. It is defined by
\begin{eqnarray}
r_{xy} & = & \frac{\sum_{i=1}^n (x_i - \overline{x}) (y_i - \overline{y})}{\sqrt{\sum_{i=1}^n (x_i - \overline{x})^2 \sum_{i=1}^n (y_i - \overline{y})^2}} \\
\ & = & \frac{\sum_{i=1}^n (x_i - \overline{x}) (y_i - \overline{y})}{(n-1) s_x s_y} \\
\ & = & \frac{ \operatorname{cov}_{xy}}{s_x s_y}
\end{eqnarray}
where $s_x$ and $s_y$ are the sample standard deviations of each measured variable. Note that $-1 \leq r_{xy} \leq 1$.
### Spearman Correlation
There are other ways to measure correlation that are less reliant on linear trends in covariation and are also more robust to outliers. Specifically, one can convert each measured variable to ranks by size (1 for the smallest, $n$ for the largest) and then use a formula for correlation designed for these ranks. One popular measure of rank-based correlation is the [Spearman correlation](https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient).
```{r, echo=FALSE}
set.seed(508)
```
```{r}
x <- rnorm(500)
y <- x + rnorm(500)
cor(x, y, method="pearson")
cor(x, y, method="spearman")
```
```{r, echo=FALSE}
plot(x, y, pch=20)
```
```{r, echo=FALSE}
set.seed(508)
```
```{r}
x <- rnorm(500)
y <- x + rnorm(500, sd=2)
cor(x, y, method="pearson")
cor(x, y, method="spearman")
```
```{r, echo=FALSE}
plot(x, y, pch=20)
```
```{r, echo=FALSE}
set.seed(508)
```
```{r}
x <- c(rnorm(499), 100)
y <- c(rnorm(499), 100)
cor(x, y, method="pearson")
cor(x, y, method="spearman")
```
```{r, echo=FALSE, fig.width=10, small.mar=FALSE}
par(mfrow=c(1,2))
plot(x, y, pch=20)
plot(x^(1/3), y^(1/3), pch=20)
```
# Data Visualization Basics
## Plots
- Single variables:
- Barplot
- Boxplot
- Histogram
- Density plot
- Two or more variables:
- Side-by-Side Boxplots
- Stacked Barplot
- Scatterplot
## R Base Graphics
- We'll first plodding through "R base graphics", which means graphics functions that come with R.
- By default they are very simple. However, they can be customized *a lot*, but it takes *a lot* of work.
- Also, the syntax varies significantly among plot types and some think the syntax is not user-friendly.
- We will consider a very highly used graphics package next week, called `ggplot2` that provides a "grammar of graphics". It hits a sweet spot of "flexibility vs. complexity" for many data scientists.
## Read the Documentation
For all of the plotting functions covered below, read the help files.
```{r, eval=FALSE}
?barplot
?boxplot
?hist
?density
?plot
?legend
```
## Barplot
```{r, eval=FALSE}
cyl_tbl <- table(mtcars$cyl)
barplot(cyl_tbl, xlab="Cylinders", ylab="Count")
```
```{r, echo=FALSE}
cyl_tbl <- table(mtcars$cyl)
barplot(cyl_tbl, xlab="Cylinders", ylab="Count", ylim=c(0,16))
```
## Boxplot
```{r}
boxplot(mtcars$mpg, ylab="MPG", col="lightgray")
```
## Constructing Boxplots
- The top of the box is Q3
- The line through the middle of the box is the median
- The bottom of the box is Q1
- The top whisker is the minimum of Q3 + 1.5 $\times$ IQR or the largest data point
- The bottom whisker is the maximum of Q1 - 1.5 $\times$ IQR or the smallest data point
- Outliers lie outside of (Q1 - 1.5 $\times$ IQR) or (Q3 + 1.5 $\times$ IQR), and they are shown as points
- Outliers are calculated using the `fivenum()` function
## Boxplot with Outliers
```{r}
boxplot(mtcars$wt, ylab="Weight (1000 lbs)",
col="lightgray")
```
## Histogram
```{r}
hist(mtcars$mpg, xlab="MPG", main="", col="lightgray")
```
## Histogram with More Breaks
```{r}
hist(mtcars$mpg, breaks=12, xlab="MPG", main="", col="lightgray")
```
## Density Plot
```{r}
plot(density(mtcars$mpg), xlab="MPG", main="")
polygon(density(mtcars$mpg), col="lightgray", border="black")
```
## Boxplot (Side-By-Side)
```{r}
boxplot(mpg ~ cyl, data=mtcars, xlab="Cylinders",
ylab="MPG", col="lightgray")
```
## Stacked Barplot
```{r}
counts <- table(mtcars$cyl, mtcars$gear)
counts
```
```{r, eval=FALSE}
barplot(counts, main="Number of Gears and Cylinders",
xlab="Gears", col=c("blue","red", "lightgray"))
legend(x="topright", title="Cyl",
legend = rownames(counts),
fill = c("blue","red", "lightgray"))
```
```{r, echo=FALSE, small.mar=FALSE}
par(mar = c(4, 4, 1, 1))
counts <- table(mtcars$cyl, mtcars$gear)
barplot(counts, main="Number of Gears and Cylinders",
xlab="Gears", col=c("blue","red", "lightgray"), ylim=c(0,16))
legend(x="topright", title="Cyl",
legend = rownames(counts),
fill = c("blue","red", "lightgray"))
```
## Scatterplot
```{r}
plot(mtcars$wt, mtcars$mpg, xlab="Weight (1000 lbs)",
ylab="MPG")
```
## Quantile-Quantile Plots
Quantile-quantile plots display the [quantiles](#/quantiles-and-percentiles) of:
1. two samples of data
2. a sample of data vs a theoretical distribution
The first type allows one to assess how similar the distributions are of two samples of data.
The second allows one to assess how similar a sample of data is to a theoretical distribution (often Normal with mean 0 and standard deviation 1).
```{r}
qqnorm(mtcars$mpg, main=" ")
qqline(mtcars$mpg) # line through Q1 and Q3
```
```{r}
before1980 <- gapminder %>% filter(year < 1980) %>%
select(lifeExp) %>% unlist()
after1980 <- gapminder %>% filter(year > 1980) %>%
select(lifeExp) %>% unlist()
qqplot(before1980, after1980); abline(0,1)
```
```{r}
ggplot(mtcars) + stat_qq(aes(sample = mpg))
```
```{r}
ggplot(gapminder) + stat_qq(aes(sample=lifeExp))
```
```{r}
ggplot(gapminder) +
stat_qq(aes(sample=lifeExp, color=continent))
```
## A Grammar of Graphics
There are many advanced graphics packages and extensions of R. One popular example is `ggplot2`, which is a grammar based graphics framework. An introduction to `ggplot2` is provided in (*YARP, Yet Another R Primer*)[https://jdstorey.org/yarp/a-grammar-of-graphics.html].
# EDA of High-Dimensional Data
## Definition
**High-dimensional data** (HD data) typically refers to data sets where *many variables* are simultaneously measured on any number of observations.
The number of variables is often represented by $p$ and the number of observations by $n$.
HD data are collected into a $p \times n$ or $n \times p$ matrix.
Many methods exist for "large $p$, small $n$" data sets.
## Examples
- Clinical studies
- Genomics (e.g., gene expression)
- Neuroimaging (e.g., fMRI)
- Finance (e.g., time series)
- Environmental studies
- Internet data (e.g., Netflix movie ratings)
## Big Data vs HD Data
"Big data" are data sets that cannot fit into a standard computer's memory.
HD data were defined above.
They are not necessarily equivalent.
## Definition of HD Data
**High-dimesional data** is a data set where the number of variables measured is many.
**Large same size** data is a data set where few variables are measured, but many observations are measured.
**Big data** is a data set where there are so many data points that it cannot be managed straightforwardly in memory, but must rather be stored and accessed elsewhere. Big data can be high-dimensional, large sample size, or both.
We will abbreviate high-dimensional with **HD**.
## Rationale
Exploratory data analysis (EDA) of high-dimensional data adds the additional challenge that many variables must be examined simultaneously. Therefore, in addition to the EDA methods we discussed earlier, methods are often employed to organize, visualize, or numerically capture high-dimensional data into lower dimensions.
Examples of EDA approaches applied to HD data include:
- Traditional EDA methods covered earlier
- Cluster analysis
- Dimensionality reduction
# Cluster Analysis
## Definition
**Cluster analysis** is the process of grouping objects (variables or observations) into groups based on measures of similarity.
Similar objects are placed in the same cluster, and dissimilar objects are placed in different clusters.
Cluster analysis methods are typically described by algorithms (rather than models or formulas).
## Types of Clustering
Clustering can be categorized in various ways:
- Hard vs. soft
- Top-down vs bottom-up
- Partitioning vs. hierarchical agglomerative
## Top-Down vs Bottom-Up
We will discuss two of the major clustering methods -- *hierarchical clustering* and *K-means clustering*.
Hierarchical clustering is an example of *bottom-up* clustering in that the process begings with each object being its own cluster and then objects are joined in a hierarchical manner into larger and larger clusters.
$K$-means clustering is an example of *top-down* clustering in that the number of clusters is chosen beforehand and then object are assigned to one of the $K$ clusters.
## Challenges {#clustering-challenges}
- Cluster analysis method
- Distance measure
- Number of clusters
- Convergence issues
## Illustrative Data Sets
### Simulated `data1`
```{r, echo=FALSE}
set.seed(201)
x <- c(rnorm(50, mean=2, sd=0.3), rnorm(50, mean=2, sd=0.3), rnorm(50, mean=4, sd=0.3))
y <- c(rnorm(50, mean=2, sd=0.3), rnorm(50, mean=4, sd=0.3), rnorm(50, mean=3, sd=0.3))
data1 <- data.frame(x=x, y=y, true_clusters=factor(c(rep(1,50), rep(2, 50), rep(3, 50))))
ggplot(data1) + geom_point(aes(x=x,y=y), size=2)
```
### "True" Clusters `data1`
```{r, echo=FALSE}
ggplot(data1) + geom_point(aes(x=x,y=y, col=true_clusters), size=2) +
scale_color_manual(values=c("red", "blue", "gray47"))
```
### Simulated `data2`
```{r, echo=FALSE}
set.seed(201)
x <- c(rnorm(60, mean=2, sd=0.3), rnorm(80, mean=4, sd=0.3))
y <- c(rnorm(60, mean=2, sd=0.3), rnorm(80, mean=runif(80, min=1, max=3), sd=0.3))
data2 <- data.frame(x=x, y=y, true_clusters=factor(c(rep(1,60), rep(2, 80))))
ggplot(data2) + geom_point(aes(x=x,y=y), size=2)
```
### "True" Clusters `data2`
```{r, echo=FALSE}
ggplot(data2) + geom_point(aes(x=x,y=y, col=true_clusters), size=2) +
scale_color_manual(values=c("red", "blue"))
```
## Distance Measures
### Objects
Most clustering methods require calculating a "distance" between two objects.
Let $\pmb{a} = (a_1, a_2, \ldots, a_n)$ be one object and $\pmb{b} = (b_1, b_2, \ldots, b_n)$ be another object.
We will assume both objects are composed of real numbers.
### Euclidean
Euclidean distance is the shortest spatial distance between two objects in Euclidean space.
Euclidean distance is calculated as:
$$d(\pmb{a}, \pmb{b}) = \sqrt{\sum_{i=1}^n \left(a_i - b_i \right)^2}$$
### Manhattan
Manhattan distance is sometimes called taxicab distance. If you picture two locations in a city, it is the distance a taxicab must travel to get from one location to the other.
Manhattan distance is calculated as:
$$d(\pmb{a}, \pmb{b}) = \sum_{i=1}^n \left| a_i - b_i \right|$$
### Euclidean vs Manhattan
<center></center>
<font size=3em>
Green is Euclidean. All others are Manhattan (and equal). Figure from [*Exploratory Data Analysis with R*](https://leanpub.com/exdata).
</font>
### `dist()`
A distance matrix -- which is the set of values resulting from a distance measure applied to all pairs of objects -- can be obtained through the function `dist()`.
Default arguments for `dist()`:
```{r}
str(dist)
```
The key argument for us is `method=` which can take values `method="euclidean"` and `method="manhattan"` among others. See `?dist`.
### Distance Matrix `data1`
```{r}
sub_data1 <- data1[1:4, c(1,2)]
sub_data1
mydist <- dist(sub_data1)
print(mydist)
```
```{r}
(sub_data1[1,] - sub_data1[2,])^2 %>% sum() %>% sqrt()
```
## Hierarchical Clustering
### Strategy
Hierarchical clustering is a hierarchical agglomerative, bottom-up clustering method that strategically joins objects into larger and larger clusters, until all objects are contained in a single cluster.
Hierarchical clustering results are typically displayed as a [dendrogram](https://en.wikipedia.org/wiki/Dendrogram).
The number of clusters does not necessarily need to be known or chosen by the analyst.
### Example: Cancer Subtypes
<center></center>
<font size=3em>
Figure from [Alizadeh et al. (2000) *Nature*](http://www.nature.com/nature/journal/v403/n6769/abs/403503a0.html).
</font>
### Algorithm
The algorithm for hierarchical clustering works as follows.
1. Start with each object assigned as its own cluster.
2. Calculate a distance between all pairs of clusters.
3. Join the two clusters with the smallest distance.
4. Repeat steps 2--3 until there is only one cluster.
At the very first iteration of the algorithm, all we need is some distance function (e.g., Euclidean or Manhattan) to determine the two objects that are closest. But once clusters with more than one object are present, how do we calculate the distance between two clusters? This is where a key choice called the *linkage method or criterion* is needed.
### Linkage Criteria
Suppose there are two clusters $A$ and $B$ and we have a distance function $d(\pmb{a}, \pmb{b})$ for all objects $\pmb{a} \in A$ and $\pmb{b} \in B$. Here are three ways (among many) to calculate a distance between clusters $A$ and $B$:
\begin{eqnarray}
\mbox{Complete: } & \max \{d(\pmb{a}, \pmb{b}): \pmb{a} \in A, \pmb{b} \in B\} \\
\mbox{Single: } & \min \{d(\pmb{a}, \pmb{b}): \pmb{a} \in A, \pmb{b} \in B\} \\
\mbox{Average: } & \frac{1}{|A| |B|} \sum_{\pmb{a} \in A} \sum_{\pmb{b} \in B} d(\pmb{a}, \pmb{b})
\end{eqnarray}
### `hclust()`
The `hclust()` function produces an R object that contains all of the information needed to create a complete hierarchical clustering.
Default arguments for `hclust()`:
```{r}
str(hclust)
```
The primary input for `hclust()` is the `d` argument, which is a distance matrix (usually obtained from `dist()`). The `method` argument takes the linkage method, which includes `method="complete"`, `method="single"`, `method="average"`, etc. See `?hclust`.
### Hierarchical Clustering of `data1`
```{r, echo=FALSE}
ggplot(data1) + geom_point(aes(x=x,y=y), size=2)
```
### Standard `hclust()` Usage
```{r}
mydist <- dist(data1, method = "euclidean")
myhclust <- hclust(mydist, method="complete")
plot(myhclust)
```
### `as.dendrogram()`
```{r}
plot(as.dendrogram(myhclust))
```
### Modify the Labels
```{r, message=FALSE, warning=FALSE}
library(dendextend)
dend1 <- as.dendrogram(myhclust)
labels(dend1) <- data1$true_clusters
labels_colors(dend1) <-
c("red", "blue", "gray47")[as.numeric(data1$true_clusters)]
plot(dend1, axes=FALSE, main=" ", xlab=" ")
```
### Color the Branches
```{r}
dend2 <- as.dendrogram(myhclust)
labels(dend2) <- rep(" ", nrow(data1))
dend2 <- color_branches(dend2, k = 3, col=c("red", "blue", "gray47"))
plot(dend2, axes=FALSE, main=" ", xlab=" ")
```
### Cluster Assignments ($K = 3$)
```{r}
est_clusters <- cutree(myhclust, k=3)
est_clusters
```
```{r, eval=FALSE}
est_clusters <- factor(est_clusters)
p <- data1 %>%
mutate(est_clusters=est_clusters) %>%
ggplot()
p + geom_point(aes(x=x, y=y, color=est_clusters))
```
### Cluster Assignments ($K = 3$)
```{r, echo=FALSE}
rm(est_clusters)
p <- data1 %>%
mutate(est_clusters=factor(cutree(myhclust, k=3))) %>%
ggplot()
p + geom_point(aes(x=x, y=y, color=est_clusters))
```
### Cluster Assignments ($K = 2$)
```{r}
(data1 %>%
mutate(est_clusters=factor(cutree(myhclust, k=2))) %>%
ggplot()) + geom_point(aes(x=x, y=y, color=est_clusters))
```
### Cluster Assignments ($K = 4$)
```{r}
(data1 %>%
mutate(est_clusters=factor(cutree(myhclust, k=4))) %>%
ggplot()) + geom_point(aes(x=x, y=y, color=est_clusters))
```
### Cluster Assignments ($K = 6$)
```{r}
(data1 %>%
mutate(est_clusters=factor(cutree(myhclust, k=6))) %>%
ggplot()) + geom_point(aes(x=x, y=y, color=est_clusters))
```
### Linkage: Complete (Default)
```{r}
data1 %>% dist() %>% hclust(method="complete") %>%
as.dendrogram() %>% plot(axes=FALSE)
```
### Linkage: Average
```{r}
data1 %>% dist() %>% hclust(method="average") %>%
as.dendrogram() %>% plot(axes=FALSE)
```
### Linkage: Single
```{r}
data1 %>% dist() %>% hclust(method="single") %>%
as.dendrogram() %>% plot(axes=FALSE)
```
### Linkage: Ward
```{r}
data1 %>% dist() %>% hclust(method="ward.D") %>%
as.dendrogram() %>% plot(axes=FALSE)
```
### Hierarchical Clustering of `data2`
```{r, echo=FALSE}
ggplot(data2) + geom_point(aes(x=x,y=y), size=2)
```
### `as.dendrogram()`
```{r}
mydist <- dist(data2, method = "euclidean")
myhclust <- hclust(mydist, method="complete")
plot(as.dendrogram(myhclust))
```
### Modify the Labels
```{r, message=FALSE, warning=FALSE}
library(dendextend)
dend1 <- as.dendrogram(myhclust)
labels(dend1) <- data2$true_clusters
labels_colors(dend1) <-
c("red", "blue")[as.numeric(data2$true_clusters)]
plot(dend1, axes=FALSE, main=" ", xlab=" ")
```
### Color the Branches
```{r}
dend2 <- as.dendrogram(myhclust)
labels(dend2) <- rep(" ", nrow(data2))
dend2 <- color_branches(dend2, k = 2, col=c("red", "blue"))
plot(dend2, axes=FALSE, main=" ", xlab=" ")
```
### Cluster Assignments ($K = 2$)
```{r}
(data2 %>%
mutate(est_clusters=factor(cutree(myhclust, k=2))) %>%
ggplot()) + geom_point(aes(x=x, y=y, color=est_clusters))
```
### Cluster Assignments ($K = 3$)
```{r}
(data2 %>%
mutate(est_clusters=factor(cutree(myhclust, k=3))) %>%
ggplot()) + geom_point(aes(x=x, y=y, color=est_clusters))
```
### Cluster Assignments ($K = 4$)
```{r}
(data2 %>%