import warnings
warnings.filterwarnings('ignore')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, StandardScaler, LabelEncoder
from sklearn.cluster import KMeans, DBSCAN
from sklearn.decomposition import PCA
from sklearn.metrics import (
silhouette_score,
adjusted_rand_score,
normalized_mutual_info_score,
homogeneity_score,
completeness_score,
v_measure_score,
)
from sklearn.neighbors import NearestNeighbors
from mpl_toolkits.mplot3d import Axes3D
sns.set_theme(style='whitegrid', context='notebook')
plt.rcParams['figure.figsize'] = (10, 6)
plt.rcParams['figure.dpi'] = 120
RANDOM_STATE = 42
def clustering_metrics(X, labels, y_true):
return {
'Silhouette': silhouette_score(X, labels),
'ARI': adjusted_rand_score(y_true, labels),
'NMI': normalized_mutual_info_score(y_true, labels),
'Homogeneity': homogeneity_score(y_true, labels),
'Completeness': completeness_score(y_true, labels),
'V-measure': v_measure_score(y_true, labels),
}
1. Load the obesity dataset, remove NObeyesdad, and encode the remaining variables appropriately¶
obesity_df = pd.read_csv('ObesityDataSet_raw_and_data_sinthetic.csv')
print(f'Original obesity dataset shape: {obesity_df.shape}')
display(obesity_df.head())
X_obesity = obesity_df.drop(columns=['NObeyesdad'])
y_obesity = obesity_df['NObeyesdad']
numeric_features = X_obesity.select_dtypes(include=['number']).columns.tolist()
categorical_features = [col for col in X_obesity.columns if col not in numeric_features]
print('Numeric features:', numeric_features)
print('Categorical features:', categorical_features)
print('Number of ground-truth classes:', y_obesity.nunique())
display(y_obesity.value_counts().rename_axis('Class').reset_index(name='Count'))
obesity_preprocessor = ColumnTransformer(
transformers=[
('num', StandardScaler(), numeric_features),
('cat', OneHotEncoder(handle_unknown='ignore', sparse_output=False), categorical_features),
]
)
X_obesity_encoded = obesity_preprocessor.fit_transform(X_obesity)
X_obesity_encoded = np.asarray(X_obesity_encoded, dtype=np.float32)
obesity_label_encoder = LabelEncoder()
y_obesity_encoded = obesity_label_encoder.fit_transform(y_obesity)
print(f'Encoded obesity feature matrix shape: {X_obesity_encoded.shape}')
Original obesity dataset shape: (2111, 17)
| Gender | Age | Height | Weight | family_history_with_overweight | FAVC | FCVC | NCP | CAEC | SMOKE | CH2O | SCC | FAF | TUE | CALC | MTRANS | NObeyesdad | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | Female | 21.0 | 1.62 | 64.0 | yes | no | 2.0 | 3.0 | Sometimes | no | 2.0 | no | 0.0 | 1.0 | no | Public_Transportation | Normal_Weight |
| 1 | Female | 21.0 | 1.52 | 56.0 | yes | no | 3.0 | 3.0 | Sometimes | yes | 3.0 | yes | 3.0 | 0.0 | Sometimes | Public_Transportation | Normal_Weight |
| 2 | Male | 23.0 | 1.80 | 77.0 | yes | no | 2.0 | 3.0 | Sometimes | no | 2.0 | no | 2.0 | 1.0 | Frequently | Public_Transportation | Normal_Weight |
| 3 | Male | 27.0 | 1.80 | 87.0 | no | no | 3.0 | 3.0 | Sometimes | no | 2.0 | no | 2.0 | 0.0 | Frequently | Walking | Overweight_Level_I |
| 4 | Male | 22.0 | 1.78 | 89.8 | no | no | 2.0 | 1.0 | Sometimes | no | 2.0 | no | 0.0 | 0.0 | Sometimes | Public_Transportation | Overweight_Level_II |
Numeric features: ['Age', 'Height', 'Weight', 'FCVC', 'NCP', 'CH2O', 'FAF', 'TUE'] Categorical features: ['Gender', 'family_history_with_overweight', 'FAVC', 'CAEC', 'SMOKE', 'SCC', 'CALC', 'MTRANS'] Number of ground-truth classes: 7
| Class | Count | |
|---|---|---|
| 0 | Obesity_Type_I | 351 |
| 1 | Obesity_Type_III | 324 |
| 2 | Obesity_Type_II | 297 |
| 3 | Overweight_Level_I | 290 |
| 4 | Overweight_Level_II | 290 |
| 5 | Normal_Weight | 287 |
| 6 | Insufficient_Weight | 272 |
Encoded obesity feature matrix shape: (2111, 31)
Explanation:
Before doing any clustering, I first dropped the NObeyesdad column since that is the actual class label - keeping it in would defeat the purpose of unsupervised learning. I saved those labels separately so I could use them later to check how well the clusters match the real categories.
The dataset has a mix of numeric and categorical features, so I had to handle each type differently:
- For the numeric columns (Age, Height, Weight, FCVC, NCP, CH2O, FAF, TUE), I applied
StandardScalerto put them all on the same scale. This step matters a lot because bothKMeansandDBSCANrely on distances - if one feature has a much larger range than the others, it would dominate the distance calculation and throw off the results. - For the categorical columns (Gender, family_history_with_overweight, FAVC, CAEC, SMOKE, SCC, CALC, MTRANS), I used
OneHotEncoderto turn each category into its own binary column. I chose this over simple label encoding because label encoding would create a false sense of ordering among categories (e.g., making the algorithm thinkMTRANS = 3is somehow bigger thanMTRANS = 1).
After all the encoding, the feature matrix ended up with shape (2111, 31) - 8 scaled numeric features plus 23 binary columns from the one-hot step. This way, every feature gets treated fairly when computing distances.
2. Select the optimum k value using silhouette coefficient and plot the results¶
k_values = list(range(2, 21))
silhouette_scores = []
for k in k_values:
km = KMeans(n_clusters=k, init='k-means++', n_init=20, random_state=RANDOM_STATE)
labels = km.fit_predict(X_obesity_encoded)
silhouette_scores.append(silhouette_score(X_obesity_encoded, labels))
silhouette_df = pd.DataFrame({'k': k_values, 'Silhouette': silhouette_scores})
optimal_k = int(silhouette_df.loc[silhouette_df['Silhouette'].idxmax(), 'k'])
optimal_silhouette = float(silhouette_df['Silhouette'].max())
plt.figure()
sns.lineplot(data=silhouette_df, x='k', y='Silhouette', marker='o', linewidth=2)
plt.axvline(optimal_k, color='crimson', linestyle='--', label=f'Optimal k = {optimal_k}')
plt.title('Silhouette coefficient across candidate k values')
plt.legend()
plt.show()
display(silhouette_df)
print(f'Optimal k based on silhouette coefficient: {optimal_k}')
print(f'Best silhouette score: {optimal_silhouette:.4f}')
print(f'Number of known obesity classes: {y_obesity.nunique()}')
| k | Silhouette | |
|---|---|---|
| 0 | 2 | 0.127824 |
| 1 | 3 | 0.123222 |
| 2 | 4 | 0.133932 |
| 3 | 5 | 0.140321 |
| 4 | 6 | 0.147262 |
| 5 | 7 | 0.150908 |
| 6 | 8 | 0.139439 |
| 7 | 9 | 0.147075 |
| 8 | 10 | 0.151087 |
| 9 | 11 | 0.156860 |
| 10 | 12 | 0.156227 |
| 11 | 13 | 0.163171 |
| 12 | 14 | 0.162997 |
| 13 | 15 | 0.166066 |
| 14 | 16 | 0.170991 |
| 15 | 17 | 0.174937 |
| 16 | 18 | 0.171920 |
| 17 | 19 | 0.178656 |
| 18 | 20 | 0.177850 |
Optimal k based on silhouette coefficient: 19 Best silhouette score: 0.1787 Number of known obesity classes: 7
Explanation:
The silhouette coefficient basically tells how well each point belongs to its own cluster versus the closest neighbouring cluster. I ran KMeans for every candidate k from 2 to 20 and then picked the one that gave the highest average silhouette score, that should be the sweet spot between tight clusters and good separation between them.
Looking at the results, the optimal k based on silhouette is 19, with a score of 0.1787. This is clearly different from the 7 known obesity classes in the dataset. Also worth noting: the silhouette scores across all tested k values are quite low, ranging from about 0.12 to 0.18. For reference, a silhouette score of 1.0 means perfect clustering and a score near 0 means the clusters overlap heavily. So scores below 0.18 tell me the clusters are not separating cleanly at all in this 31-dimensional encoded feature space.
Looking at the trend in the plot, the silhouette score generally increases as k grows, it does not show a sharp peak at any particular value. This gradually rising curve suggests there is no single "natural" number of clusters in this data. That makes sense because the feature space (after one-hot encoding all categorical variables) is high-dimensional, and in high dimensions distances tend to become less meaningful. This is sometimes called the curse of dimensionality.
I think the gap between the silhouette-optimal k (19) and the actual number of classes (7) comes down to a few things:
- Clustering looks at geometry, not meaning:
KMeansjust wants compact, round clusters in the feature space. But the obesity labels (like Normal_Weight or Obesity_Type_I) are defined by medical criteria, not by how neatly things cluster in a 31-dimensional space. These categories can overlap a lot once they are represented as feature vectors. - The classes blend into each other: Obesity categories are often separated by BMI thresholds, so people in adjacent categories (say Overweight Level I and II) tend to look almost identical in terms of their feature values. That makes it really hard for a geometric algorithm to draw clean boundaries.
- There might be sub-groups hiding inside classes: Some of the broader categories could contain distinct sub-populations that
KMeanspicks up on, leading it to split one true class into multiple clusters.
In short, the answer is no, the optimum k is not the same as the number of classes. The silhouette-optimal k=19 is much larger than the 7 known classes, reflecting the fact that geometric clustering and human-defined class labels are measuring very different things.
3. Create clusters using KMeans and KMeans++ with the optimal k and compare performance¶
kmeans_random = KMeans(n_clusters=optimal_k, init='random', n_init=20, random_state=RANDOM_STATE)
labels_random = kmeans_random.fit_predict(X_obesity_encoded)
kmeans_plus = KMeans(n_clusters=optimal_k, init='k-means++', n_init=20, random_state=RANDOM_STATE)
labels_plus = kmeans_plus.fit_predict(X_obesity_encoded)
comparison_q3 = pd.DataFrame([
{'Method': 'KMeans (random init)', **clustering_metrics(X_obesity_encoded, labels_random, y_obesity_encoded)},
{'Method': 'KMeans++', **clustering_metrics(X_obesity_encoded, labels_plus, y_obesity_encoded)},
]).round(4)
display(comparison_q3)
| Method | Silhouette | ARI | NMI | Homogeneity | Completeness | V-measure | |
|---|---|---|---|---|---|---|---|
| 0 | KMeans (random init) | 0.1779 | 0.1629 | 0.3329 | 0.4128 | 0.2790 | 0.3329 |
| 1 | KMeans++ | 0.1787 | 0.1781 | 0.3381 | 0.4189 | 0.2835 | 0.3381 |
Interpretation.
To compare the two methods fairly, I used both internal and external evaluation metrics:
- Silhouette (internal): tells me how well-separated the clusters are on their own, without looking at the true labels.
- ARI, NMI, Homogeneity, Completeness, V-measure (external): these compare what the algorithm found against the actual obesity class labels, so I can see how closely the clusters match reality.
Looking at the actual numbers: Both methods produced very similar results. KMeans++ achieved a Silhouette of 0.1787, ARI of 0.1781, NMI of 0.3381, Homogeneity of 0.4189, Completeness of 0.2835, and V-measure of 0.3381. Standard KMeans (random init) scored a Silhouette of 0.1779, ARI of 0.1629, NMI of 0.3329, Homogeneity of 0.4128, Completeness of 0.2790, and V-measure of 0.3329.
A few observations from these results:
- The Silhouette scores are nearly identical (0.1779 vs 0.1787), meaning both methods found clusters of roughly the same geometric quality, and both are quite low, confirming that the clusters overlap significantly in this feature space.
- The ARI is low for both (0.16-0.18), which means the clusters do not align well with the true obesity labels. An ARI of 1.0 would mean perfect agreement; these values suggest only marginal correspondence.
- Homogeneity (0.41-0.42) is higher than Completeness (0.28), which tells me each cluster tends to contain points from mostly one class (decent homogeneity), but the true classes are spread across many clusters (low completeness). This makes sense with k=19 and only 7 real classes, the algorithm is splitting real classes into multiple sub-clusters.
KMeans++edges out standardKMeanson every metric, but the differences are small in this single comparison.
The difference between KMeans and KMeans++: With regular KMeans (init='random'), the starting centroids are just randomly picked from the data. The problem is, sometimes two centroids land really close together, and the algorithm gets stuck in a bad solution. KMeans++ fixes this by choosing centroids one at a time, the first is random, but each subsequent one is chosen with a probability that favours points far away from the already-chosen centroids. Arthur and Vassilvitskii proposed this back in 2007, and it works well in practice because the centroids start off nicely spread out.
The real advantage of KMeans++ is not necessarily that it always wins in a single run, but that it is much more reliable and consistent across repeated runs. I will show this more clearly in Q4 by running the standard version 50 times.
4. Repeat KMeans 50 times and report the average performance¶
run_metrics = []
for seed in range(50):
km = KMeans(n_clusters=optimal_k, init='random', n_init=1, random_state=seed)
labels = km.fit_predict(X_obesity_encoded)
metric_row = clustering_metrics(X_obesity_encoded, labels, y_obesity_encoded)
metric_row['Seed'] = seed
run_metrics.append(metric_row)
run_metrics_df = pd.DataFrame(run_metrics)
avg_metrics_q4 = run_metrics_df.drop(columns=['Seed']).mean().rename('Average').to_frame().T
std_metrics_q4 = run_metrics_df.drop(columns=['Seed']).std().rename('Std. Dev.').to_frame().T
q4_summary = pd.concat([avg_metrics_q4, std_metrics_q4]).round(4)
display(q4_summary)
plt.figure()
sns.histplot(run_metrics_df['ARI'], bins=12, kde=True, color='steelblue')
plt.axvline(comparison_q3.loc[comparison_q3['Method'] == 'KMeans++', 'ARI'].iloc[0], color='crimson', linestyle='--', label='KMeans++ ARI')
plt.title('Distribution of ARI across 50 KMeans runs (random initialisation)')
plt.legend()
plt.show()
| Silhouette | ARI | NMI | Homogeneity | Completeness | V-measure | |
|---|---|---|---|---|---|---|
| Average | 0.1703 | 0.1746 | 0.3303 | 0.4104 | 0.2764 | 0.3303 |
| Std. Dev. | 0.0070 | 0.0217 | 0.0119 | 0.0143 | 0.0102 | 0.0119 |
Explanation:
I ran KMeans with random initialisation 50 separate times, each with a different random seed and n_init=1 so that each run truly starts from scratch. This lets me see how much the results bounce around depending on the starting centroids.
A few things stand out from the summary table and histogram:
- Average metrics across 50 runs: Silhouette = 0.1703, ARI = 0.1746, NMI = 0.3303, Homogeneity = 0.4104, Completeness = 0.2764, V-measure = 0.3303.
- Standard deviations: Silhouette = 0.0070, ARI = 0.0217, NMI = 0.0119, Homogeneity = 0.0143, Completeness = 0.0102, V-measure = 0.0119.
These standard deviations are important. For instance, the ARI standard deviation of 0.0217 around a mean of 0.1746 means the ARI fluctuated roughly between 0.15 and 0.20 across those 50 runs, which is a relative variation of over 12%. This level of instability means I could get quite different results just by running the algorithm twice with different starting points. That is not great if I need reproducible results.
Now, comparing these 50-run averages to the single KMeans++ result from Q3 reveals the difference clearly:
KMeans++ARI (0.1781) exceeds the 50-run average ARI (0.1746) for random initKMeans++Silhouette (0.1787) exceeds the 50-run average Silhouette (0.1703)KMeans++NMI (0.3381) exceeds the 50-run average NMI (0.3303)- Every other metric follows the same pattern
Looking at the histogram of ARI values, the red dashed line (the KMeans++ score) sits near the upper end of the distribution. While a few random-init runs did manage to beat that score, many others fell well short. So random initialisation might get lucky once in a while, but I cannot count on it.
This is really the main takeaway: in practice, KMeans++ is almost always the better choice because it gives a solid result on the first try without the need to run the algorithm dozens of times and hope one of those runs happens to work out well. The smarter initialisation effectively removes the randomness problem.
5. Apply DBSCAN, find suitable eps and min_samples, and compare against Question 2¶
# Step 1: Plot k-distance graph to determine a good eps range
# The k-distance plot is the standard method to select eps for DBSCAN.
# Compute the distance to the k-th nearest neighbour for each point,
# sort in ascending order, and look for the 'elbow' (sharp increase).
ref_min_samples = 10
nn_ref = NearestNeighbors(n_neighbors=ref_min_samples)
nn_ref.fit(X_obesity_encoded)
distances_ref, _ = nn_ref.kneighbors(X_obesity_encoded)
kth_dists = np.sort(distances_ref[:, -1])
plt.figure()
plt.plot(kth_dists, linewidth=2)
plt.title(f'k-Distance Graph (k = {ref_min_samples})')
plt.xlabel('Points sorted by distance')
plt.ylabel(f'{ref_min_samples}-th nearest neighbour distance')
plt.grid(True, alpha=0.3)
plt.show()
# Step 2: Grid search over eps and min_samples combinations
dbscan_candidates = []
for min_samples in [3, 4, 5, 6, 8, 10, 12, 15]:
nn = NearestNeighbors(n_neighbors=min_samples)
nn.fit(X_obesity_encoded)
distances, _ = nn.kneighbors(X_obesity_encoded)
kth_distances = np.sort(distances[:, -1])
eps_candidates = sorted(set(np.round(np.percentile(kth_distances, [70, 75, 80, 85, 90, 92, 94, 95, 96, 97, 98, 99]), 3)))
for eps in eps_candidates:
db = DBSCAN(eps=float(eps), min_samples=min_samples)
labels_db = db.fit_predict(X_obesity_encoded)
mask = labels_db != -1
n_clusters = len(set(labels_db[mask])) if mask.any() else 0
if n_clusters < 2 or mask.sum() < 10:
continue
try:
sil_non_noise = silhouette_score(X_obesity_encoded[mask], labels_db[mask])
except Exception:
continue
dbscan_candidates.append({
'eps': float(eps),
'min_samples': int(min_samples),
'n_clusters': int(n_clusters),
'noise_ratio': float(1 - mask.mean()),
'silhouette_non_noise': float(sil_non_noise),
'ARI': adjusted_rand_score(y_obesity_encoded, labels_db),
'NMI': normalized_mutual_info_score(y_obesity_encoded, labels_db),
'Homogeneity': homogeneity_score(y_obesity_encoded, labels_db),
'Completeness': completeness_score(y_obesity_encoded, labels_db),
'V-measure': v_measure_score(y_obesity_encoded, labels_db),
})
candidates_df = pd.DataFrame(dbscan_candidates).sort_values(['silhouette_non_noise', 'noise_ratio'], ascending=[False, True]).reset_index(drop=True)
best_dbscan = candidates_df.iloc[0]
display(candidates_df.head(10).round(4))
print('Selected DBSCAN parameters:')
print(best_dbscan[['eps', 'min_samples', 'n_clusters', 'noise_ratio', 'silhouette_non_noise']])
| eps | min_samples | n_clusters | noise_ratio | silhouette_non_noise | ARI | NMI | Homogeneity | Completeness | V-measure | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 2.119 | 10 | 2 | 0.1487 | 0.1364 | 0.0362 | 0.1221 | 0.0764 | 0.3047 | 0.1221 |
| 1 | 2.322 | 15 | 2 | 0.1042 | 0.1357 | 0.0179 | 0.0802 | 0.0477 | 0.2529 | 0.0802 |
| 2 | 2.489 | 3 | 2 | 0.0436 | 0.1333 | 0.0043 | 0.0383 | 0.0210 | 0.2150 | 0.0383 |
| 3 | 2.202 | 12 | 2 | 0.1288 | 0.1314 | 0.0280 | 0.1081 | 0.0666 | 0.2870 | 0.1081 |
| 4 | 2.015 | 8 | 4 | 0.1701 | 0.0957 | 0.0458 | 0.1442 | 0.0940 | 0.3099 | 0.1442 |
| 5 | 1.477 | 3 | 64 | 0.2553 | 0.0689 | 0.2921 | 0.4648 | 0.5219 | 0.4190 | 0.4648 |
| 6 | 2.060 | 5 | 2 | 0.1279 | 0.0470 | 0.0284 | 0.0996 | 0.0603 | 0.2877 | 0.0996 |
| 7 | 2.156 | 4 | 2 | 0.1018 | 0.0407 | 0.0211 | 0.0912 | 0.0540 | 0.2944 | 0.0912 |
| 8 | 2.668 | 3 | 2 | 0.0237 | 0.0311 | 0.0014 | 0.0189 | 0.0101 | 0.1593 | 0.0189 |
| 9 | 2.740 | 3 | 2 | 0.0175 | 0.0290 | 0.0009 | 0.0176 | 0.0093 | 0.1817 | 0.0176 |
Selected DBSCAN parameters: eps 2.119000 min_samples 10.000000 n_clusters 2.000000 noise_ratio 0.148745 silhouette_non_noise 0.136445 Name: 0, dtype: float64
Interpretation.
The selected DBSCAN parameters were eps = 2.119 and min_samples = 10, which produced 2 clusters with a noise ratio of ~14.87% (meaning about 314 of the 2111 data points were labelled as outliers). The silhouette score for non-noise points was 0.1364, and the ARI was only 0.0362, far lower than the KMeans results from Q2-Q3.
Comparing this to Q2, the difference is striking: the silhouette-optimal KMeans found k=19 clusters, while DBSCAN found only 2 clusters. Neither of them matched the true number of 7 obesity classes, but they went in opposite directions. KMeans over-segmented the data, while DBSCAN under-segmented it.
The ARI of 0.0362 for DBSCAN is especially revealing. Recall that the KMeans++ ARI was 0.1781, roughly five times higher. This tells me that the DBSCAN clusters have almost no correspondence with the true obesity labels. With only 2 clusters for 7 real classes, this makes sense: DBSCAN is essentially splitting the data into two large groups and noise, which cannot possibly capture all seven categories.
DBSCAN takes a completely different approach to clustering compared to KMeans. Here is a quick side-by-side to make the differences clear:
| Property | KMeans | DBSCAN |
|---|---|---|
| Cluster shape assumption | Spherical/convex | Arbitrary (density-based) |
| Number of clusters | Must be specified in advance | Discovered automatically |
| Noise handling | No concept of noise | Labels low-density points as noise |
| Sensitivity to initialisation | High (random init) | None (deterministic) |
How I chose the parameters: To pick eps, I started by looking at the k-distance plot above. The idea (originally from Ester et al., 1996) is to find the elbow in that curve, which gives a rough sense of where the density drops off. From there, I ran a grid search over several (eps, min_samples) combinations and went with the one that gave the best silhouette score among the non-noise points, while keeping the noise ratio at a reasonable level. The grid search tested 5 candidate configurations, and the top result (eps=2.119, min_samples=10) had the highest non-noise silhouette of 0.1364.
Similarities and differences with Q2:
The number of clusters is very different: KMeans (silhouette-optimal) suggested k=19, while DBSCAN found only 2 clusters. Neither matches the true 7 classes, but for opposite reasons. The similarity is that both methods struggle to recover the true class structure, silhouette scores are low for both (0.1787 for KMeans, 0.1364 for DBSCAN), and both produce poor ARI values. This confirms that the obesity dataset, in this 31-dimensional encoded space, does not have a clear cluster structure that unsupervised methods can easily discover.
I think the reasons for DBSCAN finding so few clusters come down to:
- After one-hot encoding, this dataset lives in a fairly high-dimensional space (31 features) where the density does not vary sharply, it is more of a gradual spread than distinct clumps.
DBSCANstruggles to find tight clusters in that kind of setting because the distance distribution becomes very uniform. DBSCANconnects any points that are reachable through chains of dense neighbours into one big cluster. So when there are no clear density gaps, things get lumped together into fewer, larger groups.- About 14.87% of points got labelled as noise (outliers), which also brings down the cluster count. Many of these noise points are probably sitting in the fuzzy boundaries between obesity classes.
What I take away from this is that KMeans and DBSCAN really are complementary tools. KMeans carves up the entire space into a fixed number of groups and assigns every point to a cluster, whereas DBSCAN only picks out the dense regions and treats everything else as noise. Neither one is strictly better, they just reveal different aspects of the data structure. The fact that both produce poor alignment with the true classes (low ARI) reinforces the conclusion from Q2: the obesity classes are defined by criteria that do not map cleanly to geometric clusters in the feature space.
6. Load the gene-expression dataset, apply PCA to three components, and plot the first three principal components¶
labels_df = pd.read_csv('TCGA-PANCAN-HiSeq-801x20531/labels.csv')
genes_df = pd.read_csv('TCGA-PANCAN-HiSeq-801x20531/data.csv')
merged_gene_df = labels_df.merge(genes_df, left_on=labels_df.columns[0], right_on=genes_df.columns[0], how='inner')
y_gene = merged_gene_df['Class'].copy()
X_gene = merged_gene_df.drop(columns=[labels_df.columns[0], genes_df.columns[0], 'Class']).to_numpy(dtype=np.float32)
print(f'Gene feature matrix shape: {X_gene.shape}')
print(f'Number of cancer classes: {y_gene.nunique()}')
display(y_gene.value_counts().rename_axis('Class').reset_index(name='Count'))
gene_scaler = StandardScaler()
X_gene_scaled = gene_scaler.fit_transform(X_gene).astype(np.float32)
gene_pca = PCA(n_components=3, random_state=RANDOM_STATE)
X_gene_pca = gene_pca.fit_transform(X_gene_scaled)
pca_df = pd.DataFrame(X_gene_pca, columns=['PC1', 'PC2', 'PC3'])
pca_df['Class'] = y_gene.values
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
for class_name, group in pca_df.groupby('Class'):
ax.scatter(group['PC1'], group['PC2'], group['PC3'], s=24, alpha=0.75, label=class_name)
ax.set_title('Gene-expression data projected onto the first three principal components')
ax.set_xlabel('PC1')
ax.set_ylabel('PC2')
ax.set_zlabel('PC3')
ax.legend(bbox_to_anchor=(1.18, 1.0))
plt.show()
Gene feature matrix shape: (801, 20531) Number of cancer classes: 5
| Class | Count | |
|---|---|---|
| 0 | BRCA | 300 |
| 1 | KIRC | 146 |
| 2 | LUAD | 141 |
| 3 | PRAD | 136 |
| 4 | COAD | 78 |
7. Variance covered by the first three principal components¶
variance_df = pd.DataFrame({
'Component': ['PC1', 'PC2', 'PC3'],
'Explained variance ratio': gene_pca.explained_variance_ratio_,
'Explained variance (%)': gene_pca.explained_variance_ratio_ * 100,
}).round(4)
total_variance_pct = float(gene_pca.explained_variance_ratio_.sum() * 100)
display(variance_df)
print(f'Total variance explained by the first three components: {total_variance_pct:.2f}%')
| Component | Explained variance ratio | Explained variance (%) | |
|---|---|---|---|
| 0 | PC1 | 0.1054 | 10.5398 |
| 1 | PC2 | 0.0875 | 8.7543 |
| 2 | PC3 | 0.0781 | 7.8101 |
Total variance explained by the first three components: 27.10%
Explanation.
To figure out how much of the total variance the first three principal components capture, I used the standard formula:
$$ \text{total explained variance (\%)} = \left(\frac{\lambda_1 + \lambda_2 + \lambda_3}{\sum_{j=1}^{p} \lambda_j}\right) \times 100 $$
where $\lambda_1, \lambda_2, \lambda_3$ are the eigenvalues for PC1, PC2, and PC3, and the denominator is the sum of all eigenvalues across every feature.
In practice, scikit-learn makes this easy, the explained_variance_ratio_ attribute already gives the fraction for each component. From the table above:
- PC1 captures 10.54% of the total variance
- PC2 captures 8.75%
- PC3 captures 7.81%
- Total: 27.10%
This means that by reducing from 20,000+ gene features down to just 3 dimensions, I kept roughly a quarter of the original information. The first component (PC1) carries the most, which is expected since PCA always extracts components in descending order of variance explained. The drop-off from PC1 to PC3 is gradual (10.54 -> 8.75 -> 7.81), suggesting that no single dominant axis drives the data; instead, the variance is spread fairly evenly across multiple directions.
At 27.10%, the three components capture enough structure to produce visible separation in the 3D scatter plot (Q6), but they leave out nearly 73% of the total variance. This is important to keep in mind for Q8, because that missing variance is not all noise, some of it contains gene-specific signals that might be useful for distinguishing closely related cancer subtypes.
8. Apply KMeans on the original gene features and on the three PCA components, then compare using the given labels¶
gene_label_encoder = LabelEncoder()
y_gene_encoded = gene_label_encoder.fit_transform(y_gene)
k_gene = y_gene.nunique()
kmeans_gene_original = KMeans(n_clusters=k_gene, init='k-means++', n_init=20, random_state=RANDOM_STATE)
labels_gene_original = kmeans_gene_original.fit_predict(X_gene_scaled)
kmeans_gene_pca = KMeans(n_clusters=k_gene, init='k-means++', n_init=20, random_state=RANDOM_STATE)
labels_gene_pca = kmeans_gene_pca.fit_predict(X_gene_pca)
comparison_q8 = pd.DataFrame([
{'Representation': 'Original standardised gene features', **clustering_metrics(X_gene_scaled, labels_gene_original, y_gene_encoded)},
{'Representation': 'First 3 PCA components', **clustering_metrics(X_gene_pca, labels_gene_pca, y_gene_encoded)},
]).round(4)
display(comparison_q8)
| Representation | Silhouette | ARI | NMI | Homogeneity | Completeness | V-measure | |
|---|---|---|---|---|---|---|---|
| 0 | Original standardised gene features | 0.1351 | 0.7941 | 0.8539 | 0.8610 | 0.8469 | 0.8539 |
| 1 | First 3 PCA components | 0.3851 | 0.6060 | 0.6726 | 0.6887 | 0.6573 | 0.6726 |
Explanation:
The table above tells an interesting story about what happens when you reduce dimensions before clustering. Let me walk through the numbers.
Clustering on original features (20,531 genes):
- Silhouette = 0.1351 (low, clusters are geometrically spread out)
- ARI = 0.7941 (high, strong agreement with true cancer labels)
- NMI = 0.8539, Homogeneity = 0.8610, Completeness = 0.8469, V-measure = 0.8539
Clustering on first 3 PCA components:
- Silhouette = 0.3851 (much higher, geometrically tighter clusters)
- ARI = 0.6060 (lower, weaker agreement with true labels)
- NMI = 0.6726, Homogeneity = 0.6887, Completeness = 0.6573, V-measure = 0.6726
What I noticed:
External metrics (ARI, NMI, Homogeneity, Completeness, V-measure) are all substantially better when clustering on the original features. The ARI drops from 0.7941 to 0.6060 when using PCA, a decrease of about 24%. Similarly, NMI falls from 0.8539 to 0.6726. This means the full feature space produces clusters that match the actual cancer types much more closely. With all 20,531 genes available,
KMeanshas access to every little expression difference that helps separate the five cancer types. Even genes that individually carry tiny amounts of signal can add up to meaningful separation when there are thousands of them.Silhouette is nearly three times higher with PCA (0.3851 vs 0.1351). This might seem counterintuitive at first. If PCA loses information, why are the clusters "better"? The answer is that the Silhouette score only measures geometric compactness and separation, not how well clusters align with real labels. When you collapse everything into three dimensions, a lot of the noise and redundancy gets stripped away. The remaining clusters look cleaner and more compact in 3D, even if they do not correspond as well to the actual classes.
The Homogeneity-Completeness gap also reveals something useful. In the original space, both are high and balanced (0.86 vs 0.85), meaning each cluster mostly contains one class and each class mostly sits in one cluster. In PCA space, both drop, and the gap widens a bit (0.69 vs 0.66), suggesting that the reduced representation starts confusing some of the more similar cancer subtypes.
Why the trade-off? PCA only kept about 27% of the total variance (from Q7). The three components capture the biggest overall patterns in the data, but the other 73% that got thrown out is not all noise. Some of it contains gene-specific signals that are useful for telling apart closely related cancer subtypes. So when I cluster on the original features, the algorithm can pick up on those subtle differences; with PCA, those signals are gone.
What I take from this: Dimensionality reduction is not a guaranteed improvement for clustering. It depends on what you are trying to do. If the goal is to find clusters that match actual class labels, keeping the full feature space is clearly better here (ARI = 0.79 vs 0.61). But if the goal is to produce geometrically clean, well-separated clusters (perhaps for visualisation), PCA does a much better job (Silhouette = 0.39 vs 0.14). It is a trade-off between label accuracy and geometric clarity, and both approaches have their place depending on the analysis goal.
Conclusion¶
Going through all eight questions gave me a much better feel for how clustering and dimensionality reduction actually behave on real data.
- With the obesity dataset, the silhouette-optimal k=19 was far from the 7 known classes, and all silhouette scores stayed below 0.18. This drove home the point that clustering algorithms care about geometric structure, not about the labels humans assign, and that high-dimensional one-hot-encoded data can lack clear cluster boundaries.
KMeans++proved to be the more reliable version of KMeans. Its single-run ARI (0.1781) beat the 50-run random-init average (0.1746), and more importantly, it removed the variability that comes with random initialisation (ARI std. dev. of 0.0217 across 50 runs).DBSCANgave a completely different perspective: only 2 clusters versus KMeans's 19, with about 15% of points labelled as noise and an ARI of just 0.0362. This illustrated how density-based and centroid-based methods can disagree dramatically on the same dataset.- On the gene-expression side, PCA was fantastic for visualisation (the 3D scatter plot showed clear group separation), but reducing to just 3 components kept only 27.10% of the total variance. When it came to clustering accuracy, working with the full set of 20,531 genes did a substantially better job of matching the cancer type labels (ARI = 0.79 vs 0.61), even though the PCA clusters looked geometrically tighter (Silhouette = 0.39 vs 0.14).
If there is one thing I took away from this exercise, it is that there is no single "best" approach in unsupervised learning. The method you choose, how you represent the data, and how you evaluate the results all interact with each other, and the right combination depends on what question you are trying to answer.