text_plain_output_1.png
from sklearn.cluster import KMeans

import matplotlib.pyplot as plt

import numpy as np

import numpy as np # linear algebra

import pandas as pd

import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

import seaborn as sns

df = pd.read_csv('/kaggle/input/customer-segmentation-tutorial-in-python/Mall_Customers.csv')

f,axes=plt.subplots(1,3,figsize=(20,20))
sns.distplot(df['Annual Income (k$)'],color='red',label="nannualincome",ax=axes[0])

sns.distplot(df['Age'],color='yellow',label="age",ax=axes[1])
sns.distplot(df['Spending Score (1-100)'],color="skyblue", label="Spending Score",ax=axes[2])

f, axes = plt.subplots(1, 3, figsize=(20, 5)) #sharex=True)
sns.distplot(df['Annual Income (k$)'][df['Gender']=="Male"],color="salmon", label="Annual Income (k$)",ax=axes[0])
sns.distplot(df['Annual Income (k$)'][df['Gender']=="Female"],color="skyblue", label="Annual Income (k$)",ax=axes[0])
    
sns.distplot(df['Age'][df['Gender']=="Male"],color="salmon", label="Age",ax=axes[1])
sns.distplot(df['Age'][df['Gender']=="Female"],color="skyblue", label="Age",ax=axes[1])

sns.distplot(df['Spending Score (1-100)'][df['Gender']=="Male"],color="salmon", label="Spending Score",ax=axes[2])
sns.distplot(df['Spending Score (1-100)'][df['Gender']=="Female"],color="skyblue", label="Spending Score",ax=axes[2])

plt.show()

f, axes = plt.subplots(1, 2, figsize=(20, 10)) #sharex=True)
sns.scatterplot(x="Age", y="Spending Score (1-100)",hue="Gender", data=df, ax=axes[0])
sns.scatterplot(x="Age", y="Annual Income (k$)",hue="Gender", data=df, ax=axes[1])

x_k = df['Annual Income (k$)'].values
y_k = df['Spending Score (1-100)'].values

x_k2 = list(zip(x_k, y_k))
x_k2 = np.array(x_k2)
x_k2

model = KMeans(n_clusters=5)
model.fit(x_k2)
y_kmeans = model.predict(x_k2)
y_kmeans

label = model.labels_
label

unique_labels = set(model.labels_)
unique_labels

plt.figure(1, figsize=(17, 8))
plt.scatter(x_k2[y_kmeans == 0, 0], x_k2[y_kmeans == 0, 1], s=100, c='red', label='Standard people')
plt.scatter(x_k2[y_kmeans == 1, 0], x_k2[y_kmeans == 1, 1], s=100, c='yellow', label='Tightwad people')
plt.scatter(x_k2[y_kmeans == 2, 0], x_k2[y_kmeans == 2, 1], s=100, c='aqua', label='Normal people')
plt.scatter(x_k2[y_kmeans == 3, 0], x_k2[y_kmeans == 3, 1], s=100, c='violet', label='Careless people(TARGET)')
plt.scatter(x_k2[y_kmeans == 4, 0], x_k2[y_kmeans == 4, 1], s=100, c='lightgreen', label='Rich people(TARGET)')
plt.scatter(model.cluster_centers_[:, 0], model.cluster_centers_[:, 1], s=300, c='black', label='Centroids')
plt.title('Clusters of customers')
plt.xlabel('Annual Income (k$)')
plt.ylabel('Spending Score (1-100)')
plt.legend()
plt.show()