Activity 3.3 - PCA implementation

SUBMISSION INSTRUCTIONS

  1. Render to html
  2. Publish your html to RPubs
  3. Submit a link to your published solutions

Problem 1

Consider the following 6 eigenvalues from a \(6\times 6\) correlation matrix:

\[\lambda_1 = 3.5, \lambda_2 = 1.0, \lambda_3 = 0.7, \lambda_4 = 0.4, \lambda_5 = 0.25, \lambda_6 = 0.15\]

If you want to retain enough principal components to explain at least 90% of the variability inherent in the data set, how many should you keep?

Eigenvalues add up to 6… 0.90*0.6 = 5.4

We need to find the number of eigenvalues that have a minimum sum of 5.4

\[\lambda_1 + \lambda_2 + \lambda_3 = 5.2, + \lambda_4 = 5.6\] We need 4 eigenvalues to explain at least 90% of variation

Problem 2

The iris data set is a classic data set often used to demonstrate PCA. Each iris in the data set contained a measurement of its sepal length, sepal width, petal length, and petal width. Consider the five irises below, following mean-centering and scaling:

library(tidyverse)
five_irises <- data.frame(
  row.names = 1:5,
  Sepal.Length = c(0.189, 0.551, -0.415, 0.310, -0.898),
  Sepal.Width  = c(-1.97, 0.786, 2.62, -0.590, 1.70),
  Petal.Length = c(0.137, 1.04, -1.34, 0.534, -1.05),
  Petal.Width  = c(-0.262, 1.58, -1.31, 0.000875, -1.05)
) %>% as.matrix

Consider also the loadings for the first two principal components:

# Create the data frame
pc_loadings <- data.frame(
  PC1 = c(0.5210659, -0.2693474, 0.5804131, 0.5648565),
  PC2 = c(-0.37741762, -0.92329566, -0.02449161, -0.06694199),
  row.names = c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")
) %>% as.matrix

A plot of the first two PC scores for these five irises is shown in the plot below.

Match the ID of each iris (1-5) to the correct letter of its score coordinates on the plot.

scores <- five_irises %*% pc_loadings
round(scores, 3)
     PC1    PC2
1  0.561  1.762
2  1.572 -1.065
3 -2.440 -2.142
4  0.631  0.415
5 -2.128 -1.135

Iris 1 = B
Iris 2 = D
Iris 3 = A
Iris 4 = C
Iris 5 = E

Problem 3

These data are taken from the Places Rated Almanac, by Richard Boyer and David Savageau, copyrighted and published by Rand McNally. The nine rating criteria used by Places Rated Almanac are:

  • Climate & Terrain
  • Housing
  • Health Care & Environment
  • Crime
  • Transportation
  • Education
  • The Arts
  • Recreation
  • Economics

For all but two of the above criteria, the higher the score, the better. For Housing and Crime, the lower the score the better. The scores are computed using the following component statistics for each criterion (see the Places Rated Almanac for details):

  • Climate & Terrain: very hot and very cold months, seasonal temperature variation, heating- and cooling-degree days, freezing days, zero-degree days, ninety-degree days.
  • Housing: utility bills, property taxes, mortgage payments.
  • Health Care & Environment: per capita physicians, teaching hospitals, medical schools, cardiac rehabilitation centers, comprehensive cancer treatment centers, hospices, insurance/hospitalization costs index, flouridation of drinking water, air pollution.
  • Crime: violent crime rate, property crime rate.
  • Transportation: daily commute, public transportation, Interstate highways, air service, passenger rail service.
  • Education: pupil/teacher ratio in the public K-12 system, effort index in K-12, accademic options in higher education.
  • The Arts: museums, fine arts and public radio stations, public television stations, universities offering a degree or degrees in the arts, symphony orchestras, theatres, opera companies, dance companies, public libraries.
  • Recreation: good restaurants, public golf courses, certified lanes for tenpin bowling, movie theatres, zoos, aquariums, family theme parks, sanctioned automobile race tracks, pari-mutuel betting attractions, major- and minor- league professional sports teams, NCAA Division I football and basketball teams, miles of ocean or Great Lakes coastline, inland water, national forests, national parks, or national wildlife refuges, Consolidated Metropolitan Statistical Area access.
  • Economics: average household income adjusted for taxes and living costs, income growth, job growth.

In addition to these, latitude and longitude, population and state are also given, but should not be included in the PCA.

Use PCA to identify the major components of variation in the ratings among cities.

places <- read.csv('Data/Places.csv')
head(places)
                       City Climate Housing HlthCare Crime Transp Educ Arts
1                 AbileneTX     521    6200      237   923   4031 2757  996
2                   AkronOH     575    8138     1656   886   4883 2438 5564
3                  AlbanyGA     468    7339      618   970   2531 2560  237
4 Albany-Schenectady-TroyNY     476    7908     1431   610   6883 3399 4655
5             AlbuquerqueNM     659    8393     1853  1483   6558 3026 4496
6              AlexandriaLA     520    5819      640   727   2444 2972  334
  Recreat Econ      Long     Lat    Pop
1    1405 7633  -99.6890 32.5590 110932
2    2632 4350  -81.5180 41.0850 660328
3     859 5250  -84.1580 31.5750 112402
4    1617 5864  -73.7983 42.7327 835880
5    2612 5727 -106.6500 35.0830 419700
6    1018 5254  -92.4530 31.3020 135282

A.

If you want to explore this data set in lower dimensional space using the first \(k\) principal components, how many would you use, and what percent of the total variability would these retained PCs explain? Use a scree plot to help you answer this question.

library(factoextra)
Warning: package 'factoextra' was built under R version 4.5.2
Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
places_ratings <- places %>%
  select(-Lat, -Long, -Pop, -City)

# scale
places_scaled <- scale(places_ratings)

pca_places <- prcomp(places_scaled, center = TRUE, scale. = TRUE)

# scree plot 
fviz_eig(pca_places, addlabels = TRUE)
Warning in geom_bar(stat = "identity", fill = barfill, color = barcolor, :
Ignoring empty aesthetic: `width`.

5-dimensions is a good start, as it explains 82.7% of variability.

B.

Interpret the retained principal components by examining the loadings (plot(s) of the loadings may be helpful). Which variables will be used to separate cities along the first and second principal axes, and how? Make sure to discuss the signs of the loadings, not just their contributions!

loadings <- pca_places$rotation  # matrix of loadings
round(loadings[,1:2], 2)         # first two PCs
          PC1   PC2
Climate  0.21  0.22
Housing  0.36  0.25
HlthCare 0.46 -0.30
Crime    0.28  0.36
Transp   0.35 -0.18
Educ     0.28 -0.48
Arts     0.46 -0.19
Recreat  0.33  0.38
Econ     0.14  0.47



PC1 is the general indicator of quality of life.
PC2 is independent from PC1. High values for cities are more economically and recreationally active, but these same cities might have less strong education or health care.

Low PC2 values for cities are stronger in education and health care, but might be lower on economy or recreation.

C.

Add the first two PC scores to the places data set. Create a biplot of the first 2 PCs, using repelled labeling to identify the cities. Which are the outlying cities and what characteristics make them unique?

library(ggplot2)
library(ggrepel)

places$PC1 <- pca_places$x[,1]
places$PC2 <- pca_places$x[,2]

ggplot(places, aes(x = PC1, y = PC2, label = City)) +
  geom_point() +
  geom_text_repel() +
  xlab("PC1") +
  ylab("PC2") +
  ggtitle("Biplot of First Two PCs")
Warning: ggrepel: 314 unlabeled data points (too many overlaps). Consider
increasing max.overlaps

The outliers are (arguably strictly) popular and recognizable cities such as New York, Los Angeles, and Chicago. These are only cities that an average person should know.

Problem 4

The data we will look at here come from a study of malignant and benign breast cancer cells using fine needle aspiration conducted at the University of Wisconsin-Madison. The goal was determine if malignancy of a tumor could be established by using shape characteristics of cells obtained via fine needle aspiration (FNA) and digitized scanning of the cells.

The variables in the data file you will be using are:

  • ID - patient identification number (not used in PCA)
  • Diagnosis determined by biopsy - B = benign or M = malignant
  • Radius: mean of distances from center to points on the perimeter
  • Texture: standard deviation of gray-scale values
  • Smoothness: local variation in radius lengths
  • Compactness: perimeter^2 / area - 1.0
  • Concavity: severity of concave portions of the contour
  • Concavepts: number of concave portions of the contour
  • Symmetry: measure of symmetry of the cell nucleus
  • FracDim: fractal dimension; “coastline approximation” - 1
bc_cells <- read.csv('Data/BreastDiag.csv')
head(bc_cells)
  Diagnosis Radius Texture Smoothness Compactness Concavity ConcavePts Symmetry
1         M  17.99   10.38    0.11840     0.27760    0.3001    0.14710   0.2419
2         M  20.57   17.77    0.08474     0.07864    0.0869    0.07017   0.1812
3         M  19.69   21.25    0.10960     0.15990    0.1974    0.12790   0.2069
4         M  11.42   20.38    0.14250     0.28390    0.2414    0.10520   0.2597
5         M  20.29   14.34    0.10030     0.13280    0.1980    0.10430   0.1809
6         M  12.45   15.70    0.12780     0.17000    0.1578    0.08089   0.2087
  FracDim
1 0.07871
2 0.05667
3 0.05999
4 0.09744
5 0.05883
6 0.07613

A.

My analysis suggests 3 PCs should be retained. Support or refute this suggestion. What percent of variability is explained by the first 3 PCs?

features <- bc_cells %>% select(Radius:FracDim)
features_scaled <- scale(features)  # center and scale

pca_bc <- prcomp(features_scaled, center = TRUE, scale. = TRUE)
summary(pca_bc)
Importance of components:
                          PC1    PC2    PC3     PC4     PC5     PC6    PC7
Standard deviation     2.0705 1.3504 0.9087 0.70614 0.61016 0.30355 0.2623
Proportion of Variance 0.5359 0.2279 0.1032 0.06233 0.04654 0.01152 0.0086
Cumulative Proportion  0.5359 0.7638 0.8670 0.92937 0.97591 0.98743 0.9960
                           PC8
Standard deviation     0.17837
Proportion of Variance 0.00398
Cumulative Proportion  1.00000

PC 1, 2 & 3 accounts for 86.7% of the variation. This is a good start, but if you want to be further confident, it doesn’t hurt to add PC4 into the mix for an almost 93% variation explanation.

B.

Interpret the first 3 principal components by examining the eigenvectors/loadings. Discuss.

loadings <- pca_bc$rotation[, 1:3]  # first 3 PCs
round(loadings, 2)
              PC1   PC2   PC3
Radius      -0.30  0.53  0.28
Texture     -0.14  0.35 -0.90
Smoothness  -0.35 -0.33  0.13
Compactness -0.46 -0.07 -0.03
Concavity   -0.45  0.13  0.04
ConcavePts  -0.45  0.23  0.17
Symmetry    -0.32 -0.28 -0.08
FracDim     -0.23 -0.58 -0.24

Like the previous question, PC1 measures the overall irregularity of the cell. Lower PC1 values indicate a “less normal” cell.

PC2 has both strong negative and positive loadings. A high PC2 score indicates larger cells with higher texture variation, and low PC2 scores indicate smaller cells with more complex shape

PC3 has one dominant loading, which is Texture. High PC3 score: smoother texture Low PC3 score: more uneven texture

C.

Examine a biplot of the first two PCs. Incorporate the third PC by sizing the points by this variable. (Hint: use fviz_pca to set up a biplot, but set col.ind='white'. Then use geom_point() to maintain full control over the point mapping.) Color-code by whether the cells are benign or malignant. Answer the following:

  • What characteristics distinguish malignant from benign cells?
  • Of the 3 PCs, which does the best job of differentiating malignant from benign cells?
bc_cells$PC1 <- pca_bc$x[,1]
bc_cells$PC2 <- pca_bc$x[,2]
bc_cells$PC3 <- pca_bc$x[,3]

# Empty biplot  
fviz_pca(pca_bc, col.ind = "white")  # keeps axes and arrows
Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
ℹ Please use `linewidth` instead.
ℹ The deprecated feature was likely used in the ggpubr package.
  Please report the issue at <https://github.com/kassambara/ggpubr/issues>.

# Plot 
ggplot(bc_cells, aes(x = PC1, y = PC2, 
                     color = Diagnosis, size = PC3)) +
  geom_point(alpha = 0.7) +
  scale_color_manual(values = c("B" = "blue", "M" = "red")) +
  xlab("PC1") +
  ylab("PC2") +
  ggtitle("Breast Cancer PCA") +
  theme_minimal()

Looking at the biplot, the radius, concavity, and texture are good starting points for deciding if a cancer cell is malignant or benign.
I could be looking at this wrong, but since PC1 will always capture the most variation, it will always be the best job of differentiating the two cell types.