Module 16 · Principal component analysis · Lesson 57 of 66

Squeeze 30 columns into 2

Find the directions where data varies most, and use them to see high-dimensional data.

In this lesson · about 25 minutes

  • Explain what a principal component is
  • Reduce scaled data to two components with PCA
  • Read how much variance each component keeps, and what it's made of

The breast cancer data has 30 columns. Nobody can picture 30 dimensions. Principal component analysis (PCA) finds new axes, the principal components, ordered by how much of the data's spread they capture. The first points along the direction where the data varies most; the second is at a right angle to it and captures the most of what's left; and so on. Keep the first two or three and you have a small summary of the data you can plot.

PCA isn't a model that predicts anything. It's a transformation, often used to look at data, to speed up other models, or to remove noise.

Four panels: points with their two principal components drawn as arrows; the same points rotated so the components become the axes; the points with the second component dropped, lying on a line; and those points rotated back into the original space.
The idea in two dimensions: rotate the data so the main directions become the axes, drop the less important one, and you keep most of the shape with half the numbers.

Try it in two dimensions

Here's that picture made from random data. Change the 0.6 to make the cloud wider or thinner and run again: the first component always follows the long direction.

Scale first

PCA looks for the biggest spread, so a column measured in thousands would win just because of its units. Standardize the columns first so each has the same scale.

Exercise

Reduce to two components

The cancer data is scaled for you as scaled_data. Create PCA(n_components=2) called pca, fit it to scaled_data, and transform the data into x_pca. End with x_pca.shape.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
df = pd.DataFrame(cancer['data'], columns=cancer['feature_names'])
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
scaled_data = StandardScaler().fit_transform(df)

Exercise

See the two classes

Scatter the first component (x_pca[:, 0]) against the second, colored by cancer['target'] with the 'plasma' color map. Label the axes 'First principal component' and 'Second principal component'.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
df = pd.DataFrame(cancer['data'], columns=cancer['feature_names'])
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
scaled_data = StandardScaler().fit_transform(df)
pca = PCA(n_components=2)
pca.fit(scaled_data)
x_pca = pca.transform(scaled_data)

With just two numbers per tumor, malignant and benign already fall into two fairly separate clouds. A classifier trained on these two components alone would do well.

What the components are made of

pca.explained_variance_ratio_ says what share of the spread each component keeps. pca.components_ holds one row per component and one column per original feature: how much each feature contributes. A heat map makes that readable.

Exercise

How much did we keep?

End with the total share of variance the two components keep: the sum of pca.explained_variance_ratio_.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
df = pd.DataFrame(cancer['data'], columns=cancer['feature_names'])
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
scaled_data = StandardScaler().fit_transform(df)
pca = PCA(n_components=2)
pca.fit(scaled_data)
x_pca = pca.transform(scaled_data)

The first component draws on almost every feature at once: it's roughly "how big and irregular are the cells overall". That's why it separates the classes so well. A common next step is to feed components like these into a classifier such as logistic regression or an SVM.

Exercises solved: 0 of 3

Tip: solve each exercise first. Press Check to test your code.

Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.