image_output_1.png
from sklearn.cluster import KMeans

import matplotlib.pyplot as plt

import pandas as pd

import seaborn as sns

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

df.isna().sum()

df_copy = df.copy()

df1 = df.drop(['CustomerID', 'Gender'], axis=1)
df1

df2 = df['Gender']
df2

x = df1['Annual Income (k$)']
y = df1['Spending Score (1-100)']

kmeans = KMeans(n_clusters=4, max_iter=1000)
kmeans.fit(df1)

kmeans.cluster_centers_

clusters = kmeans.predict(df1)
clusters[50:60]

x = df1['Annual Income (k$)']
y = df1['Spending Score (1-100)']

plt.figure(figsize=(20, 9))
x = df1['Annual Income (k$)']
y = df1['Spending Score (1-100)']
plt.subplot(321)
plt.title('K-means Predictions')
sns.scatterplot(data=df, x=x, y=y, hue=clusters)
plt.subplot(322)
plt.title('Actual Clusters')
sns.scatterplot(data=df, x=x, y=y, hue=df2)
x = df1['Age']
y = df1['Spending Score (1-100)']
plt.subplot(323)
plt.title('K-means Predictions')
sns.scatterplot(data=df, x=x, y=y, hue=clusters)
plt.subplot(324)
plt.title('Actual Clusters')
sns.scatterplot(data=df, x=x, y=y, hue=df2)
x = df1['Age']
y = df1['Annual Income (k$)']
plt.subplot(325)
plt.title('K-means Predictions')
sns.scatterplot(data=df, x=x, y=y, hue=clusters)
plt.subplot(326)
plt.title('Actual Clusters')
sns.scatterplot(data=df, x=x, y=y, hue=df2)
plt.tight_layout()