Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Machine Learning · Learn / Refresh

← All challenges
ML-X19 · PCA · 30–45 minutes

Retain information without confusing it with a picture

pca · discovery · profiles

Complete workflow and evidence

The question

Reduce all 30 Breast measurements with PCA. Retain at least 90% variance and distinguish the reduced representation from a separate two-dimensional view.

data/ml-learning/ML-X19.csv Complete workflow and evidence

Your inputs

Challenge input · ML-X19

569 observations. One tumour sample represented by cell-nucleus image measurements. Load the CSV file yourself.

Download challenge input CSV · Original source dataset · Source and original dictionary

Ready to load: comma-delimited UTF-8, header row, no saved index. No filtering or target construction is required. Fitting input contains measurements only; species/diagnosis reference labels are not supplied or required.

ML-X19 · first 8 prepared rows
radius_meantexture_meanperimeter_meanarea_meansmoothness_meancompactness_meanconcavity_meanconcave_points_meansymmetry_meanfractal_dimension_meanradius_setexture_seperimeter_searea_sesmoothness_secompactness_seconcavity_seconcave_points_sesymmetry_sefractal_dimension_seradius_worsttexture_worstperimeter_worstarea_worstsmoothness_worstcompactness_worstconcavity_worstconcave_points_worstsymmetry_worstfractal_dimension_worst
17.9910.38122.810010.11840.27760.30010.14710.24190.078711.0950.90538.589153.40.0063990.049040.053730.015870.030030.00619325.3817.33184.620190.16220.66560.71190.26540.46010.1189
20.5717.77132.913260.084740.078640.08690.070170.18120.056670.54350.73393.39874.080.0052250.013080.01860.01340.013890.00353224.9923.41158.819560.12380.18660.24160.1860.2750.08902
19.6921.2513012030.10960.15990.19740.12790.20690.059990.74560.78694.58594.030.006150.040060.038320.020580.02250.00457123.5725.53152.517090.14440.42450.45040.2430.36130.08758
11.4220.3877.58386.10.14250.28390.24140.10520.25970.097440.49561.1563.44527.230.009110.074580.056610.018670.059630.00920814.9126.598.87567.70.20980.86630.68690.25750.66380.173
20.2914.34135.112970.10030.13280.1980.10430.18090.058830.75720.78135.43894.440.011490.024610.056880.018850.017560.00511522.5416.67152.215750.13740.2050.40.16250.23640.07678
12.4515.782.57477.10.12780.170.15780.080890.20870.076130.33450.89022.21727.190.007510.033450.036720.011370.021650.00508215.4723.75103.4741.60.17910.52490.53550.17410.39850.1244
18.2519.98119.610400.094630.1090.11270.0740.17940.057420.44670.77323.1853.910.0043140.013820.022540.010390.013690.00217922.8827.66153.216060.14420.25760.37840.19320.30630.08368
13.7120.8390.2577.90.11890.16450.093660.059850.21960.074510.58351.3773.85650.960.0088050.030290.024880.014480.014860.00541217.0628.14110.68970.16540.36820.26780.15560.31960.1151

Column meanings and units

Computed image features, with mean, standard-error and worst summaries as defined by the source. Diagnosis is a category.

This is a historical teaching classification dataset, not a clinical decision system. Measurements are assumed available before prediction.

Ready to load: comma-delimited UTF-8, header row, no saved index. No filtering or target construction is required. Fitting input contains measurements only; species/diagnosis reference labels are not supplied or required.

Input schema
ColumnStored type
radius_meanfloat64
texture_meanfloat64
perimeter_meanfloat64
area_meanfloat64
smoothness_meanfloat64
compactness_meanfloat64
concavity_meanfloat64
concave_points_meanfloat64
symmetry_meanfloat64
fractal_dimension_meanfloat64
radius_sefloat64
texture_sefloat64
perimeter_sefloat64
area_sefloat64
smoothness_sefloat64
compactness_sefloat64
concavity_sefloat64
concave_points_sefloat64
symmetry_sefloat64
fractal_dimension_sefloat64
radius_worstfloat64
texture_worstfloat64
perimeter_worstfloat64
area_worstfloat64
smoothness_worstfloat64
compactness_worstfloat64
concavity_worstfloat64
concave_points_worstfloat64
symmetry_worstfloat64
fractal_dimension_worstfloat64

The file is available in the Python working folder. Load it yourself.

Your task
  1. Reduce all 30 Breast measurements with PCA.
  2. Keep at least 90% variance and distinguish the reduced representation from a separate two-dimensional view.
  3. Plot the separate two-axis scores with PC1 and PC2 axis labels.
ratioscumulativeretainedreducedweightsscores2

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.

Deliverables

These conditions describe a complete workflow. Use the declared Python variables beside the editor; Check inspects evidence from your Run.

Python name key

Teal outlines name table columns. Violet left rules name Python objects. Dotted rules mark syntax, functions and parameters. Use each name exactly as shown.

  1. Measurement population

    1. Load all 30 supplied measurements and standardise them without diagnosis labels.
  2. Variance & retention

    1. Fit PCA and find the smallest component count keeping at least 90% variance
    2. Report ratios and cumulative variance.
  3. Representation & view

    1. Return the retained scores, consistent feature weights and a separate two-component score array
    2. Plot that separate PC1/PC2 view with labelled axes.
  4. Interpretation

    1. Distinguish retained information from the two-axis picture.
    2. Explain axis weights without claiming causal effects.

The playground workflow

Use the ML → Workflow discovery route: define the observations and measurements, explore and prepare them, fit the grouping or representation, inspect its evidence and explain what the result can support. There is no prediction target or reserved final test in this workflow.

  1. Choose what to discoverHow can I summarise variation in Breast Cancer Wisconsin (Diagnostic) · All features continuous rows with fewer coordinates from radius_mean, texture_mean, and 28 more selected inputs?
  2. Explore redundancyWhich selected inputs may overlap in Breast Cancer Wisconsin (Diagnostic) · All features continuous before they are replaced by principal-component coordinates?
  3. Scale the inputsWhy should radius_mean, texture_mean, and 28 more selected inputs share a common scale before PCA compares their variation?
  4. Fit PCA and inspect explained varianceHow much variation does each component represent for Breast Cancer Wisconsin (Diagnostic) · All features continuous, and where does adding another component become less useful?
  5. Select componentsHow many coordinates should represent Breast Cancer Wisconsin (Diagnostic) · All features continuous under the chosen variance-retention rule?
  6. Understand the component loadingsWhich original inputs shape the first axes for Breast Cancer Wisconsin (Diagnostic) · All features continuous, and how should their signs be read?
  7. Project the rowsHow many coordinates did you keep for Breast Cancer Wisconsin (Diagnostic) · All features continuous, how much variation do they preserve, and what do the first two axes describe?

Data policy Use only the supplied measurements for fitting. Keep group labels, scores and profiles aligned with the rows they describe.

Help Hints & explained solution

Choose the amount of help you need. Opening one hint does not reveal the others.

Hint 1 — Think

The picture and retained representation may have different dimensions.

Hint 2 — Tools

PCA, explained_variance_ratio_, components_ and transform.

Revisit: PCA checkpoint

Hint 3 — Approach

Choose retention from cumulative variance, label weights/scores and report the two-axis view separately.

Explained solution

This complete script replaces the editor contents. It includes the input setup and the workflow.

import numpy as np
import pandas as pd
df=pd.read_csv('data/ml-learning/ML-X19.csv')
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import seaborn as sns
X = df[[c for c in df.columns if c.endswith(('_mean','_se','_worst'))]]
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())
View input setup in this script

These opening lines are included in the complete script above. They load the challenge input.

import numpy as np
import pandas as pd
df=pd.read_csv('data/ml-learning/ML-X19.csv')

Why these steps exist

  • The primary input excludes diagnosis and contains all 30 measurements. PCA is fitted on their standardised representation; cumulative variance determines the smallest retained prefix. Feature-labelled weights and row-aligned scores support interpretation, while the separate two-axis view does not claim to show the full retained information.

Another valid approach

Equivalent ordinary Python is welcome. A defensible candidate or grouping need not match the solution’s choice; objective evidence must remain consistent.

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.