Outputs you create
ratios- Explained variance
ratiosin descending component order.
- Explained variance
cumulative- Cumulative sum of
ratios.
- Cumulative sum of
retained- Smallest number of components reaching at least 90% variance.
reduced- Scores for the
retainedcomponent prefix.
- Scores for the
weights- Feature-by-two dataframe of
PC1/PC2axisweights, labelled by feature and component.
- Feature-by-two dataframe of
scores2- Row-by-two component scores, with signs consistent with
weights.
- Row-by-two component scores, with signs consistent with
island | bill_length_mm | bill_depth_mm | flipper_length_mm | body_mass_g | sex | year |
|---|---|---|---|---|---|---|
| Torgersen | 39.1 | 18.7 | 181 | 3750 | male | 2007 |
| Torgersen | 39.5 | 17.4 | 186 | 3800 | female | 2007 |
| Torgersen | 40.3 | 18 | 195 | 3250 | female | 2007 |
| Torgersen | 36.7 | 19.3 | 193 | 3450 | female | 2007 |
| Torgersen | 39.3 | 20.6 | 190 | 3650 | male | 2007 |
| Torgersen | 38.9 | 17.8 | 181 | 3625 | female | 2007 |
| Torgersen | 39.2 | 19.6 | 195 | 4675 | male | 2007 |
| Torgersen | 41.1 | 17.6 | 182 | 3200 | female | 2007 |
Your task
- Fit
PCAon exactlybill_length_mm,bill_depth_mm,flipper_length_mmandbody_mass_gfor every Penguin. - Keep the smallest component prefix reaching 90%, label
PC1/PC2featureweights - Report the separate two-coordinate
scores2view with a labelled scatter plot.
ratioscumulativeretainedreducedweightsscores2Hints
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.