Group Part I: Machine Learning

Q4: Clustering Analysis (Any one) A. Implement K-Means clustering on the Iris CSV dataset. Determine the number of clusters using the elbow method. Dataset link: https://www.kaggle.com/datasets/uciml/iris B. Implement the K-Medoid algorithm on a credit card dataset. Determine the number of clusters using the silhouette method. Dataset link: https://www.kaggle.com/datasets/arjunbhasin2013/ccdata

Clustering Analysis (Any one)

Solution and implementation for Q4 from Machine Learning (ml).

4A_kmeans_iris_elbow.ipynb Download

ML Practical 4: K-Means Clustering on Iris Dataset

Implement K-Means clustering on the Iris dataset. Determine the optimal number of clusters using the Elbow method (WCSS) and visualize the resulting clusters.

Code Cell 1
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
Code Cell 2
# Load dataset
df = pd.read_csv("Iris.csv")
print("Dataset Shape:", df.shape)
print("\nFirst 5 rows:")
print(df.head())

# Features are columns 1 to 5 (SepalLengthCm, SepalWidthCm, PetalLengthCm, PetalWidthCm)
X = df.iloc[:, 1:5]
print("\nSelected Feature Columns:", list(X.columns))
Dataset Shape: (150, 6)

First 5 rows:
   Id  SepalLengthCm  SepalWidthCm  PetalLengthCm  PetalWidthCm      Species
0   1            5.1           3.5            1.4           0.2  Iris-setosa
1   2            4.9           3.0            1.4           0.2  Iris-setosa
2   3            4.7           3.2            1.3           0.2  Iris-setosa
3   4            4.6           3.1            1.5           0.2  Iris-setosa
4   5            5.0           3.6            1.4           0.2  Iris-setosa

Selected Feature Columns: ['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm']
Code Cell 3
# Elbow Method: find optimal k
wcss = [
    KMeans(n_clusters=k, n_init=10, random_state=42).fit(X).inertia_
    for k in range(1, 11)
]

plt.figure(figsize=(7, 4))
plt.plot(range(1, 11), wcss, marker='o', color="#8b5cf6", linewidth=2, markersize=6)
plt.title("Elbow Method for Optimal k", fontsize=13, fontweight="bold")
plt.xlabel("Number of Clusters (k)", fontsize=10)
plt.ylabel("WCSS (Within-Cluster Sum of Squares)", fontsize=10)
plt.grid(True, linestyle="--", alpha=0.6)
plt.tight_layout()
plt.show()
Cell 3 output
<Figure size ...>
Code Cell 4
# Apply K-Means clustering with optimal k = 3
kmeans = KMeans(n_clusters=3, n_init=10, random_state=42)
df["Cluster"] = kmeans.fit_predict(X)
print("Clustering finished. Cluster distribution:\n", df["Cluster"].value_counts())
Clustering finished. Cluster distribution:
 Cluster
0    62
1    50
2    38
Name: count, dtype: int64
Code Cell 5
# Visualize Clusters
plt.figure(figsize=(8, 5))
plt.scatter(X.iloc[:, 0], X.iloc[:, 1], c=df["Cluster"], cmap="viridis", edgecolors='k', s=60, alpha=0.85)
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=180, c='red', marker='X', label="Centroids", edgecolors='black')
plt.xlabel("Sepal Length (cm)", fontsize=10)
plt.ylabel("Sepal Width (cm)", fontsize=10)
plt.title("K-Means Clustering on Iris (k=3)", fontsize=13, fontweight="bold")
plt.legend()
plt.grid(True, linestyle="--", alpha=0.5)
plt.tight_layout()
plt.show()
Cell 5 output
<Figure size ...>
4B_kmedoids_credit_card_silhouette.ipynb Download
Code Cell 1
# Q4B: K-Medoids on the credit card dataset; choose k by silhouette score.
# Source: https://www.kaggle.com/datasets/arjunbhasin2013/ccdata
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.impute import SimpleImputer
from sklearn.metrics import pairwise_distances, silhouette_score
from sklearn.preprocessing import StandardScaler
Code Cell 2
# Read the downloaded CSV. Sample reproducibly because exact pairwise
# distances over all 8,950 customers would use substantial memory.
credit = pd.read_csv("CC GENERAL.csv")
sample = credit.sample(n=800, random_state=42).reset_index(drop=True)
numeric = sample.drop(columns=["CUST_ID"])
X = SimpleImputer(strategy="median").fit_transform(numeric)
X_scaled = StandardScaler().fit_transform(X)
distances = pairwise_distances(X_scaled, metric="euclidean")
print("Full dataset:", credit.shape, "Clustering sample:", sample.shape)
print("Missing values in full dataset:", credit.isna().sum().sum())
Full dataset: (8950, 18) Clustering sample: (800, 18)
Missing values in full dataset: 314
Code Cell 3
# Alternating K-Medoids: each medoid is an actual customer record.
# Start with far-apart records, assign to nearest medoid, then minimize
# the sum of within-cluster distances. This uses no extra package.
def fit_kmedoids(distance_matrix, n_clusters, max_iter=30):
    n = len(distance_matrix)
    medoids = [int(np.argmin(distance_matrix.sum(axis=1)))]
    while len(medoids) < n_clusters:
        nearest = distance_matrix[:, medoids].min(axis=1)
        nearest[medoids] = -1
        medoids.append(int(np.argmax(nearest)))
    for _ in range(max_iter):
        labels = np.argmin(distance_matrix[:, medoids], axis=1)
        new_medoids = []
        for cluster in range(n_clusters):
            members = np.flatnonzero(labels == cluster)
            if len(members) == 0:
                raise ValueError("Empty cluster; try a smaller k")
            totals = distance_matrix[np.ix_(members, members)].sum(axis=1)
            new_medoids.append(int(members[np.argmin(totals)]))
        if new_medoids == medoids:
            break
        medoids = new_medoids
    labels = np.argmin(distance_matrix[:, medoids], axis=1)
    return labels, medoids
Code Cell 4
# The highest average silhouette score determines k for this sample.
k_values = range(2, 7)
scores = []
for k in k_values:
    labels, _ = fit_kmedoids(distances, k)
    score = silhouette_score(distances, labels, metric="precomputed")
    scores.append(score)
    print(f"k={k}: silhouette={score:.3f}")
best_k = list(k_values)[int(np.argmax(scores))]
plt.figure(figsize=(7, 4))
plt.plot(list(k_values), scores, marker="o")
plt.axvline(best_k, color="crimson", linestyle="--", label=f"Best k={best_k}")
plt.xlabel("Number of clusters (k)")
plt.ylabel("Average silhouette score")
plt.title("Credit card K-Medoids silhouette selection")
plt.legend()
plt.grid(alpha=0.3)
plt.show()
k=2: silhouette=0.812
k=3: silhouette=0.750
k=4: silhouette=0.312
k=5: silhouette=0.316
k=6: silhouette=0.295
Cell 4 output
<Figure size 700x400 with 1 Axes>
Code Cell 5
# Show the selected medoids and a two-dimensional view of the clusters.
labels, medoids = fit_kmedoids(distances, best_k)
print("Cluster sizes:", pd.Series(labels).value_counts().sort_index().to_dict())
print("Medoid customer IDs:", sample.loc[medoids, "CUST_ID"].tolist())
points_2d = PCA(n_components=2).fit_transform(X_scaled)
plt.figure(figsize=(7, 5))
plt.scatter(points_2d[:, 0], points_2d[:, 1], c=labels, cmap="tab10", s=15, alpha=0.7)
plt.scatter(points_2d[medoids, 0], points_2d[medoids, 1],
            c="black", marker="X", s=140, label="Medoids")
plt.xlabel("Principal component 1")
plt.ylabel("Principal component 2")
plt.title(f"Credit card customer clusters (k={best_k})")
plt.legend()
plt.show()
Cluster sizes: {0: 798, 1: 2}
Medoid customer IDs: ['C16594', 'C10574']
Cell 5 output
<Figure size 700x500 with 1 Axes>

Other Questions in Machine Learning

See All Available Questions
Download