Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Machine Learning · Learn / Refresh

← PCA lessons
Reading a representation · ML-P-K1 · 25–35 MIN

PCA checkpoint

  1. Retrieval 1Retrieve and applyCurrent exercise

Outputs you create

ratios
  1. Explained variance ratios in descending component order.
cumulative
  1. Cumulative sum of ratios.
retained
  1. Smallest number of components reaching at least 90% variance.
reduced
  1. Scores for the retained component prefix.
weights
  1. Feature-by-two dataframe of PC1/PC2 axis weights, labelled by feature and component.
scores2
  1. Row-by-two component scores, with signs consistent with weights.
penguins · first 8 rows
islandbill_length_mmbill_depth_mmflipper_length_mmbody_mass_gsexyear
Torgersen39.118.71813750male2007
Torgersen39.517.41863800female2007
Torgersen40.3181953250female2007
Torgersen36.719.31933450female2007
Torgersen39.320.61903650male2007
Torgersen38.917.81813625female2007
Torgersen39.219.61954675male2007
Torgersen41.117.61823200female2007
Your task
  1. Fit PCA on exactly bill_length_mm, bill_depth_mm, flipper_length_mm and body_mass_g for every Penguin.
  2. Keep the smallest component prefix reaching 90%, label PC1/PC2 feature weights
  3. Report the separate two-coordinate scores2 view with a labelled scatter plot.
ratioscumulativeretainedreducedweightsscores2
Hints

Think: Reconstruct the distinction between retained representation and a convenient picture.

Tools: Measurement selection, scaling, PCA, cumulative variance and labelled weights/scores.

Approach: Fit the measurement representation, find the smallest 90% prefix and report it separately from the first-two-axis view.

Explained solution
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import seaborn as sns
X = df[['bill_length_mm','bill_depth_mm','flipper_length_mm','body_mass_g']]
scaler = StandardScaler()
scaled = scaler.fit_transform(X)
pca = PCA().fit(scaled)
scores = pca.transform(scaled)
ratios = pca.explained_variance_ratio_
cumulative = np.cumsum(ratios)
retained = int(np.searchsorted(cumulative,0.9)+1)
reduced = scores[:,:retained]
weights = pd.DataFrame(pca.components_[:2].T.copy(),index=X.columns,columns=['PC1','PC2'])
scores2 = scores[:,:2].copy()
fig, ax = plt.subplots(figsize=(6,4))
sns.scatterplot(x=scores2[:,0],y=scores2[:,1],s=12,ax=ax)
ax.set(title='Two-component view of measurements',xlabel='PC1 score',ylabel='PC2 score')
print('Retained dimensions:',retained,'; variance visible in 2D:',ratios[:2].sum())

The retained matrix fulfils the variance rule while the labelled two-dimensional display communicates only the variation its axes contain.

Ctrl/⌘+Enter: Run · Tab: indent · Esc then Tab: leave editor

Python loads when you run. Code and results stay in this activity only.

Run your code to inspect its output. Check uses that same run.