Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Machine Learning · Learn / Refresh

← PCA lessonsQUESTIONS · MODELS · EVIDENCE
Reading a representation · ML-P-K1 · 25–35 MIN

PCA checkpoint

Retrieval 1

Exercises within this concept

  1. Retrieval 1Retrieve and applyCurrent exercise
Retrieval 1 · penguins

Fit Penguin PCA, retain at least 90% variance, label weights and report the separate 2D view.

This practice: Fit Penguin PCA, retain at least 90% variance, label weights and report the separate 2D view. Next: Choose and Explain Models. Continue to Choose and Explain Models →

Given data · penguins

333 observations. One measured penguin. The dataframe df is supplied afresh for each Run.

Download source CSV · Source and original dictionary

Reference labels are omitted from this preview and must remain outside fitting.

penguins · first 8 prepared 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

Column meanings and units

Bill length/depth and flipper length: mm. Body mass: grams. Year and island: sampling context.

ML uses 333 complete cases. Removing incomplete records may change the represented population. Geographic context may not generalise to new islands.

Input schema
ColumnStored type
islandstr
bill_length_mmfloat64
bill_depth_mmfloat64
flipper_length_mmint64
body_mass_gint64
sexstr
yearint64

Supporting concepts: Two dimensions are a view →

Remember the idea

This checkpoint combines previously taught skills. Assemble the workflow; help remains available when needed.

Fit Penguin PCA, retain at least 90% variance, label weights and report the separate 2D view.Training XScale numbersEncode categoriesFit estimatorEach fold learns its own preparation.
Schematic · Fit Penguin PCA, retain at least 90% variance, label weights and report the separate 2D view.Scroll the diagram horizontally if needed.

Required Python variables and evidence

Use these names so Check can inspect your workflow. Each meaning is shown beside its name.

Workflow evidence contract
VariableMeaning
XFeature dataframe for the declared population, preserving row indices.
cumulativeCumulative sum of ratios.
pcaPCA fitted on scaled measurements.
ratiosExplained variance ratios in descending component order.
reducedScores for the retained component prefix.
retainedSmallest number of components reaching at least 90% variance.
scaledStandardised features in the same row/column order as X.
scores2Row-by-two component scores, with signs consistent with weights.
weightsFeature-by-two dataframe of PC1/PC2 axis weights, labelled by feature and component.
Hint 1 — Think

Reconstruct the distinction between retained representation and a convenient picture.

Hint 2 — Tools

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

Hint 3 — 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
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))
ax.scatter(scores2[:,0],scores2[:,1],s=12)
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.

Helpful prior knowledge: PCA retrieval These links are guidance, not locks.

Sources and API context

Examples run with this Playground’s scikit-learn 1.4.2 / Pyodide 0.26.4 runtime.

Your task · Retrieval 1

Fit Penguin PCA, retain at least 90% variance, label weights and report the separate 2D view.

ratioscumulativeretainedreducedweightsscores2

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.

What does the two-dimensional Penguin view omit from the retained PCA representation?

Use your Run output as evidence. This response is optional, not machine-graded or saved.