import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import seaborn as sns
# To ignore warnings
import warnings
warnings.filterwarnings("ignore")
customer_data = pd.read_csv("Mall_Customers.csv")
customer_data.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 200 entries, 0 to 199 Data columns (total 5 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 CustomerID 200 non-null int64 1 Gender 200 non-null object 2 Age 200 non-null int64 3 Annual Income (k$) 200 non-null int64 4 Spending Score (1-100) 200 non-null int64 dtypes: int64(4), object(1) memory usage: 7.9+ KB
customer_data.head()
| CustomerID | Gender | Age | Annual Income (k$) | Spending Score (1-100) | |
|---|---|---|---|---|---|
| 0 | 1 | Male | 19 | 15 | 39 |
| 1 | 2 | Male | 21 | 15 | 81 |
| 2 | 3 | Female | 20 | 16 | 6 |
| 3 | 4 | Female | 23 | 16 | 77 |
| 4 | 5 | Female | 31 | 17 | 40 |
plt.scatter(customer_data['Age'],customer_data['Spending Score (1-100)'])
plt.xlabel('Age')
plt.ylabel('Spending Score')
plt.show()
km_sample = KMeans(n_clusters=3)
km_sample.fit(customer_data[['Age','Spending Score (1-100)']])
KMeans(n_clusters=3)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
KMeans(n_clusters=3)
labels_sample = km_sample.labels_
customer_data['label'] = labels_sample
sns.scatterplot(x=customer_data['Age'],y=customer_data['Spending Score (1-100)'],hue=customer_data['label'],palette='Set1')
<Axes: xlabel='Age', ylabel='Spending Score (1-100)'>
km_sample1 = KMeans(n_clusters=3)
km_sample1.fit(customer_data[['Annual Income (k$)','Spending Score (1-100)']])
KMeans(n_clusters=3)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
KMeans(n_clusters=3)
labels_sample1 = km_sample1.labels_
customer_data['label'] = labels_sample1
sns.scatterplot(x=customer_data['Annual Income (k$)'],y=customer_data['Spending Score (1-100)'],hue=customer_data['label'],palette='Set1')
<Axes: xlabel='Annual Income (k$)', ylabel='Spending Score (1-100)'>
WCSS= []
K = range(1,9)
for i in K:
Kmeanmodel=KMeans(n_clusters=i, init='k-means++', max_iter=300, n_init=10, random_state=42)
Kmeanmodel.fit(customer_data[['Age','Spending Score (1-100)']])
WCSS.append(Kmeanmodel.inertia_)
plt.plot(range(1,9),WCSS)
plt.xlabel('Number of clusters')
plt.ylabel('WCSS')
plt.show()