PythonPlaza - Python & AI

K-means clustering (unsupervised learning algorithm)


An unsupervised machine learning technique called K-Means Clustering assists in assembling data points into clusters according to their innate similarity.K-Mean is utilized when we have unlabeled data and the objective is to find hidden patterns or structures, as opposed to supervised learning, where models are trained using labeled data.

An online retailer, for instance, can divide its clientele into groups like ""Big Spenders," "Frequent Buyers," and "Budget Shoppers" according to their past purchases
"k" stands for the number of clusters or groups into which we wish to divide our objects.












Let's see an example with a sample data..













USE CASE 1: Healthcare Patient Grouping using K-Means Clustering: Hospitals often need to group patients with similar characteristics to: Identify high-risk patients, Personalize treatment plans, Optimize resource allocation, Improve healthcare management

import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans

## Load data
#download from
#https://www.pythonplaza.com/healthcare_patient_dataset.html
df = pd.read_csv("patients_data.csv")

# Features used for clustering
X = df[['Age',
        'BMI',
        'Blood_Pressure',
        'Cholesterol',
        'Hospital_Visits']]

# Scale data
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# Train model
kmeans = KMeans(n_clusters=3, random_state=42, n_init=10)
kmeans.fit(X_scaled)

# New patient?
new_patient = [[33, 28.0, 139, 210, 4]]

# Apply SAME scaling
new_patient_scaled = scaler.transform(new_patient)

# Predict cluster
cluster = kmeans.predict(new_patient_scaled)

print("Patient belongs to Cluster:", cluster[0])
#Example Output
Patient belongs to Cluster: 1


USE CASE 2: Use K-means clustering for customer segmentation in Market Basket Analysis. Instead of finding which products are purchased together (like Apriori or FP-Growth),use K-means to group customers based on their purchasing behavior. Once customers are clustered, you can create targeted promotions and personalized recommendations for each segment.




import pandas as pd
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler

# ----------------------------------
 # Step 1: Sample Market Basket Data 
# ----------------------------------
data = pd.DataFrame({
    'Customer': ['C001','C002','C003','C004','C005','C006','C007','C008'],
    'Bread': [12,10,11,1,0,2,6,5],
    'Milk': [10,8,9,2,1,1,5,6],
    'Eggs': [8,7,6,1,2,0,4,5],
    'Beer': [0,1,0,10,12,9,4,5],
    'Chips': [1,0,1,8,10,7,3,4]
})

#Load data
#You can also download from
#https://www.pythonplaza.com/sample_customer_shopping.html
data = pd.read_csv("customer_shopping.csv")

print("Original Data")
print(data)

# ----------------------------------
# Step 2: Select Features
# ----------------------------------
X = data[['Bread', 'Milk', 'Eggs', 'Beer', 'Chips']]


# ----------------------------------
# Step 3: Scale Features
# ----------------------------------
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)


# ----------------------------------
# Step 4: Train K-Means Model
# ----------------------------------

kmeans = KMeans(
    n_clusters=3,
    random_state=42,
    n_init=10
)

kmeans.fit(X_scaled)


# ----------------------------------
# Step 5: Assign Clusters
# ----------------------------------

data['Cluster'] = kmeans.labels_

print("\nCluster Assignments")
print(data[['Customer', 'Cluster']])


# ----------------------------------
# Step 6: Cluster Profiles
# ----------------------------------

print("\nCluster Centers (Original Scale)")

centers = scaler.inverse_transform(kmeans.cluster_centers_)

cluster_profiles = pd.DataFrame(
    centers,
    columns=['Bread','Milk','Eggs','Beer','Chips']
)

print(cluster_profiles.round(2))


# ----------------------------------
# Step 7: Test New Customer
# ----------------------------------

new_customer = pd.DataFrame({
    'Bread': [11],
    'Milk': [9],
    'Eggs': [7],
    'Beer': [1],
    'Chips': [1]
})

# Scale using same scaler
new_customer_scaled = scaler.transform(new_customer)

# Predict cluster
predicted_cluster = kmeans.predict(new_customer_scaled)

print("\nNew Customer")
print(new_customer)

print(f"\nPredicted Cluster: {predicted_cluster[0]}")


# ----------------------------------
# Step 8: Recommendation Logic
# ----------------------------------

if predicted_cluster[0] == 0:
    print("Recommendation: Bread, Milk, Eggs promotions")
elif predicted_cluster[0] == 1:
    print("Recommendation: Beer and Chips promotions")
else:
    print("Recommendation: Mixed basket offers")



About Us  | Contact Us | Sitemap  | Privacy Policy