# K-Means Clustering

# Importing the libraries
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

# Importing the dataset
dataset = pd.read_csv('Mall_Customers.csv')
X = dataset.iloc[:, [1,2,3, 4]].values

# Exploratory Data Analysis
dataset.isnull().sum()
sns.pairplot(dataset.drop(["CustomerID","Annual Income (k$)","Spending Score (1-100)"],axis=1))
from sklearn.preprocessing import LabelEncoder
labelencoder_X = LabelEncoder()
X[:, 0] = labelencoder_X.fit_transform(X[:, 0])

# Using the elbow method to find the optimal number of clusters
from sklearn.cluster import KMeans
wcss = []
for i in range(1, 11):
    kmeans = KMeans(n_clusters = i, init = 'k-means++', random_state = 0)
    kmeans.fit(X)
    wcss.append(kmeans.inertia_)
plt.plot(range(1, 11), wcss)
plt.title('The Elbow Method')
plt.xlabel('Number of clusters')
plt.ylabel('WCSS')
plt.show()

# Fitting K-Means to the dataset
kmeans = KMeans(n_clusters = 5, init = 'k-means++', random_state =0)
y_kmeans = kmeans.fit_predict(X)

# Visualising the clusters
plt.scatter(X[y_kmeans == 0, 2], X[y_kmeans == 0, 3], s = 50, c = 'red', label = 'Sensible Customers')
plt.scatter(X[y_kmeans == 1, 2], X[y_kmeans == 1, 3], s = 50, c = 'blue', label = 'Good Customers')
plt.scatter(X[y_kmeans == 2, 2], X[y_kmeans == 2, 3], s = 50, c = 'green', label = 'Target Customers')
plt.scatter(X[y_kmeans == 3, 2], X[y_kmeans == 3, 3], s = 50, c = 'cyan', label = 'Cautious Customers')
plt.scatter(X[y_kmeans == 4, 2], X[y_kmeans == 4, 3], s = 50, c = 'magenta', label = 'Careless Customers')
plt.scatter(kmeans.cluster_centers_[:, 2], kmeans.cluster_centers_[:, 3], s = 100, c = 'yellow', label = 'Centroids')
plt.title('Clusters of customers')
plt.xlabel('Annual Income (k$)')
plt.ylabel('Spending Score (1-100)')
plt.legend()
plt.show()