Online-Academy
Look, Read, Understand, Apply

Data Analytics

KMeans

Clustering is the process of creating groups of objects based on the closeness (similarity) of the objects. K-means, DBSCAN, are some of the clustering algorithms.

Example below generates 2 clusters using kmeans algorithm. In the example income and spending are part of dictionary named "data". DataFrame is created using dictionary "data". KMeans is a python method, it is passed n_clusters (number of clusters) = 2, and random_state = 42. (random_state sets the random seed so that K-Means gives consistent and repeatable results across multiple runs. It ensures that the algorithm produces the same clustering result every time the program is run. Using a fixed value (e.g., random_state=42) makes the results reproducible, which is useful for experiments and debugging.)

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

if __name__ == "__main__":
    data = {
        'Income': [15, 16, 17, 18, 19, 20, 70, 75, 80, 85],
        'Spending': [39, 40, 42, 43, 45, 47, 60, 65, 70, 75]
    }

    df = pd.DataFrame(data)
    print(df)
    #KMeans() creates a K-Means clustering model. n_clusters=2 tells the algorithm to divide the data into 2 clusters.
    kmeans = KMeans(n_clusters=2, random_state=42)

    #df[['Income', 'Spending']] selects the Income and Spending columns as input features.
    #fit_predict() performs two tasks:
    #fit(): Finds the cluster centers (centroids).
    #predict(): Assigns each data point to the nearest cluster.
    #The assigned cluster labels (0 or 1) are stored in a new column named Cluster in the DataFrame.

    df['Cluster'] = kmeans.fit_predict(df[['Income', 'Spending']])

    print("Cluster Centers:")
    print(kmeans.cluster_centers_)

    plt.scatter(df['Income'], df['Spending'], c=df['Cluster'])
    plt.scatter(
        kmeans.cluster_centers_[:, 0],
        kmeans.cluster_centers_[:, 1],
        s=200,
        marker='X'
    )
    
    #   : means select all rows.
    #   0 means select the first column.
    #   : means all rows.
    #   1 means the second column.

    plt.xlabel('Income')
    plt.ylabel('Spending Score')
    plt.title('K-Means Clustering')
    plt.show()