Understand the idea
PCA rotates numeric measurements into component axes and can retain fewer axes. Components combine original features; they are not selected original columns or cluster assignments.
Illustrative data
| Column | Values |
|---|---|
x | 1, 2, 3, 4, 5, 6 |
y | 1, 3, 2, 5, 4, 6 |
Click the highlighted code to change the result.
scaled = StandardScaler().fit_transform(example[["x", "y"]])
example_pca = PCA(n_components=)
scores = example_pca.fit_transform(scaled)2 components retain 100% of variance. Output: 6 rows × 2 columns.
What the syntax does
PCA(n_components=2)- Creates a
PCAmodel that finds directions of greatest input variation.
n_components:2,None,0.9
- An integer
n_componentsrequests that many axes; no argument retains all available axes. - Fit scale and axes on the declared discovery population.
- Explained variance describes retained variation, not prediction accuracy.
- Creates a
pca.fit_transform(scaled)- Learns these axes and returns two coordinates per input row; it does not select two original columns.
Outputs you create
answer- The requested result, with the values, labels and row order described by this task.
a | b | c | d | e |
|---|---|---|---|---|
| 103.047 | 50.8622 | 22.7157 | 44.6184 | 0.906993 |
| 89.6002 | 44.3015 | 20.2703 | 40.1253 | -0.680116 |
| 107.505 | 53.9521 | 21.1565 | 41.7009 | 0.818161 |
| 109.406 | 54.2501 | 22.5252 | 44.9095 | 1.39291 |
| 80.4896 | 40.0557 | 14.1714 | 29.4087 | -3.27953 |
| 86.9782 | 44.1387 | 18.7213 | 37.5997 | -1.70077 |
| 101.278 | 50.4611 | 18.1185 | 36.0784 | -0.343557 |
| 96.8376 | 48.7875 | 17.4445 | 33.8533 | -0.987809 |
- Standardise the supplied measurements
- Create two
PCAcoordinates for every row, and store the coordinates inanswer.
answerHints
Think: Call fit_transform() to learn a representation and return coordinates in the new feature space.
Tools: Use StandardScaler().fit_transform(X), PCA(n_components=2), pca.fit_transform(scaled). Read the visible syntax meanings before editing.
Approach: Standardise the supplied measurements, create two PCA coordinates for every row, and store the coordinates in answer. Keep the supplied row order and inspect the named output after running.
Explained solution
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
X = df.select_dtypes(include='number')
scaled = StandardScaler().fit_transform(X)
pca = PCA(n_components=2)
answer = pca.fit_transform(scaled)
The output has one row per observation and two new coordinate columns. Each coordinate combines original measurements. This first two-axis picture introduces the API; later lessons use explained variance to decide how many components to retain.