Menu

Exploring Unsupervised Learning with Clustering

Exploring Unsupervised Learning with Clustering

Unsupervised learning identifies patterns in data without requiring a predefined target variable. One common application is clustering, which groups observations based on their similarity.

Understanding K-Means Clustering

K-Means divides observations into a specified number of clusters. It repeatedly assigns observations to nearby cluster centers and updates those centers to reduce within-cluster squared distances.

Consider a customer dataset containing annual spending and purchase frequency.

import pandas as pd

from sklearn.cluster import KMeans

from sklearn.preprocessing import StandardScaler

df = pd.DataFrame({

"Annual_Spending": [10000, 12000, 15000, 50000, 55000, 60000],

"Purchases": [2, 3, 4, 15, 17, 18]

})

scaler = StandardScaler()

X_scaled = scaler.fit_transform(df)

model = KMeans(

n_clusters=2,

random_state=42,

n_init=10

)

df["Cluster"] = model.fit_predict(X_scaled)

print(df)

The model assigns each observation to a cluster. The resulting cluster numbers are arbitrary identifiers, not rankings or predefined customer categories.

Standardization is useful here because spending and purchase counts use different numerical scales. Without scaling, spending could dominate the distance calculation.

Interpreting Clusters

You can summarize each cluster to understand its characteristics.

print(

df.groupby("Cluster").agg(

Average_Spending=("Annual_Spending", "mean"),

Average_Purchases=("Purchases", "mean"),

Customer_Count=("Purchases", "count")

)

)

This summary helps compare the average spending and purchasing behavior of the discovered groups.

In a real project, choose the number of clusters carefully and evaluate whether the groups are meaningful. Clustering results depend on feature selection, scaling, initialization, and the chosen algorithm.


Python for Data Science

VA

Vishalini A



Learn via Video Course

undefined Logo

NaN hrs



Get in Touch For Details