image_output_1.png
from sklearn.cluster import KMeans

from sklearn.preprocessing import StandardScaler

import matplotlib.pyplot as plt

import pandas as pd

dataset = pd.read_csv('../input/Mall_Customers.csv')
pd.set_option('display.max_columns', 10)

scaler = StandardScaler()
df = pd.DataFrame(scaler.fit_transform(dataset[['Age', 'Annual Income (k$)', 'Spending Score (1-100)']]))
df.columns = ['age', 'income', 'spending']
df.insert(0, 'gender', dataset['Gender_code'])

# Histograms
plot_gender = sns.distplot(df["gender"], label="gender",color="grey")
plot_age = sns.distplot(df["age"], label="age",color="blue")
plot_income = sns.distplot(df["income"], label="income",color="lightgreen")
plot_spend = sns.distplot(df["spending"], label="spend",color="orange")
plt.xlabel('')
plt.legend()
plt.show()

# Violin plot
f, axes = plt.subplots(2,2, figsize=(12,6), sharex=True, sharey=True)
v1 = sns.violinplot(data=df, x="gender", color="gray",ax=axes[0,0])
v2 = sns.violinplot(data=df, x="age", color="skyblue",ax=axes[0,1])
v3 = sns.violinplot(data=df, x="income",color="lightgreen", ax=axes[1,0])
v4 = sns.violinplot(data=df, x="spending",color="pink", ax=axes[1,1])

wcss = []
k_s = [i * i for i in range(1, 8)]
for i in k_s:
    km = KMeans(n_clusters=i, init='k-means++', max_iter=300, n_init=10, random_state=0)
    km.fit(df)
    wcss.append(km.inertia_)

wcss = []
k_s = [4, 7, 9]
for i in k_s:
    km = KMeans(n_clusters=i, init='k-means++', max_iter=300, n_init=10, random_state=0)
    km.fit(df)
    wcss.append(km.inertia_)

wcss = []
k_s = [4, 6, 7]
print(k_s)
for i in k_s:
    km = KMeans(n_clusters=i, init='k-means++', max_iter=300, n_init=10, random_state=0)
    km.fit(df)
    wcss.append(km.inertia_)
plt.plot(k_s, wcss)
plt.title('Elbow Method')
plt.xlabel('Number of clusters')
plt.ylabel('wcss')
plt.show()