Understand the idea
Production uses the smallest prefix reaching at least 90% cumulative variance. The threshold is a stated compression criterion, not a universal optimum.
What the syntax does
np.searchsorted(cumulative, 0.9)- Finds the first zero-based position reaching the variance threshold.
retained <= budget- Checks whether the smallest sufficient prefix fits a component storage limit; do not silently lower the stated variance requirement.
Supplied for this practice
These objects are prepared afresh before your editor runs.
X- Feature dataframe for the declared population, preserving row indices.
X = df.copy() scaler- Already fitted coordinate system learned from
X; transform reuses its statistics without fitting again. Fitted onX; reuse without refitting. scaled- Standardised features in the same row/column order as
X.scaled = scaler.fit_transform(X) pca- Already fitted on scaled.
PCAfitted on scaled measurements. Fitted on scaled; reuse without refitting. scores- Supplied scores; its definition below specifies the values and role.
scores = pca.transform(scaled)
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 |
- Keep the fewest leading
PCAcomponents that explain at least 90% variance. - Store that count in
retainedand the matching row scores inanswer.
answerHints
Think: The rule asks for the first cumulative total that reaches the threshold.
Tools: np.cumsum, np.searchsorted and score-column slicing.
Approach: Accumulate variance ratios, locate the first qualifying component count and retain that prefix of scores.
Explained solution
cumulative=np.cumsum(pca.explained_variance_ratio_)
retained=int(np.searchsorted(cumulative,.9)+1)
answer=scores[:,:retained]
Adding one converts a zero-based position into a dimension count; the prefix retains the required variation with the fewest leading axes.