Path: blob/master/Part 4 - Clustering/K-Means Clustering/kmeans.py
1009 views
# K-Means Clustering12# Importing the libraries3import numpy as np4import matplotlib.pyplot as plt5import pandas as pd67# Importing the dataset8dataset = pd.read_csv('Mall_Customers.csv')9X = dataset.iloc[:, [3, 4]].values10# y = dataset.iloc[:, 3].values1112# Splitting the dataset into the Training set and Test set13"""from sklearn.cross_validation import train_test_split14X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)"""1516# Feature Scaling17"""from sklearn.preprocessing import StandardScaler18sc_X = StandardScaler()19X_train = sc_X.fit_transform(X_train)20X_test = sc_X.transform(X_test)21sc_y = StandardScaler()22y_train = sc_y.fit_transform(y_train)"""2324# Using the elbow method to find the optimal number of clusters25from sklearn.cluster import KMeans26wcss = []27for i in range(1, 11):28kmeans = KMeans(n_clusters = i, init = 'k-means++', random_state = 42)29kmeans.fit(X)30wcss.append(kmeans.inertia_)31plt.plot(range(1, 11), wcss)32plt.title('The Elbow Method')33plt.xlabel('Number of clusters')34plt.ylabel('WCSS')35plt.show()3637# Fitting K-Means to the dataset38kmeans = KMeans(n_clusters = 5, init = 'k-means++', random_state = 42)39y_kmeans = kmeans.fit_predict(X)4041# Visualising the clusters42plt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s = 100, c = 'red', label = 'Cluster 1')43plt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s = 100, c = 'blue', label = 'Cluster 2')44plt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s = 100, c = 'green', label = 'Cluster 3')45plt.scatter(X[y_kmeans == 3, 0], X[y_kmeans == 3, 1], s = 100, c = 'cyan', label = 'Cluster 4')46plt.scatter(X[y_kmeans == 4, 0], X[y_kmeans == 4, 1], s = 100, c = 'magenta', label = 'Cluster 5')47plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s = 300, c = 'yellow', label = 'Centroids')48plt.title('Clusters of customers')49plt.xlabel('Annual Income (k$)')50plt.ylabel('Spending Score (1-100)')51plt.legend()52plt.show()5354