# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/patelkishan9286/Kishan_ML_K-MeansClustering/blob/master/Kishan_ML_K_MeansClustering.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# + id="UBJPZa7MH0Tk" colab_type="code" colab={}
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# + id="FuyDeoJiXjPa" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 72} outputId="d82c31f4-4b02-4cb9-db63-8003481d0bbe"
from sklearn.cluster import KMeans
from sklearn.preprocessing import MinMaxScaler
import seaborn as sns

# %matplotlib inline

# + id="gObnwhnFXk_9" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 402} outputId="63dbae23-cbe2-406e-fac7-a936c0f654b4"
cust = pd.read_csv("customers.csv")
cust

# + id="fN-r6nMXXm_2" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 122} outputId="5e5714a2-ad99-469b-957a-318d1a06f9b1"
cust.isnull().sum()

# + id="W7s1XXWjXpW8" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="78ec3699-969d-4a3c-c959-a0463b596d9b"
cust.duplicated().sum()

# + id="tdyE5n5FXq-q" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 122} outputId="668a2587-c567-43eb-bb57-bde2813a05a2"
cust.dtypes


# + id="A-29os0NXsrr" colab_type="code" colab={}
def statistics(variable):
    if variable.dtype == "int64" or variable.dtype == "float64":
        return pd.DataFrame([[variable.name, np.mean(variable), np.std(variable), np.median(variable), np.var(variable)]], 
                            columns = ["Variable", "Mean", "Standard Deviation", "Median", "Variance"]).set_index("Variable")
    else:
        return pd.DataFrame(variable.value_counts())


# + id="PU5AuygJXupd" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 106} outputId="af83c918-7e4d-46f8-90e6-1dc0612251fe"
spending = cust["Spending Score (1-100)"]
statistics(spending)

# + id="rLw0Z9k5XwjO" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 297} outputId="440c9b5b-a16d-429a-bec9-2bc33795415c"
sns.distplot(cust["Spending Score (1-100)"], bins=10, kde_kws={"lw": 1.5, "alpha":0.8, "color":list(map(float, np.random.rand(3,)))},
                       hist_kws={"linewidth": 1.5, "edgecolor": "grey",
                                "alpha": 0.4, "color":list(map(float, np.random.rand(3,)))})

# + id="OHgsqrZjXzUW" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 106} outputId="b3996a87-10b2-4f73-c63d-395605d31c30"
income = cust["Annual Income (k$)"]
statistics(income)

# + id="5v7tTrb_X3Ca" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 297} outputId="24d82de2-ace1-44d8-b9c9-e998dfdf0d70"
sns.distplot(cust["Annual Income (k$)"], bins=10, kde_kws={"lw": 1.5, "alpha":0.8, "color":list(map(float, np.random.rand(3,)))},
                       hist_kws={"linewidth": 1.5, "edgecolor": "grey",
                                "alpha": 0.4, "color":list(map(float, np.random.rand(3,)))})

# + id="WjbwUiiTX5Af" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 106} outputId="aec9c5c4-f747-4614-922f-7d342ff6fe6a"
gender = cust["Gender"]
statistics(gender)

# + id="G6J9bMdfX7FM" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 386} outputId="d3b576c6-ab5b-4126-cfa3-267d9185997a"
gender = pd.DataFrame(cust["Gender"])
sns.catplot(x=gender.columns[0], kind="count", palette="spring", data=gender)

# + id="GJX9IQ33X9sa" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 402} outputId="19e86692-cfee-46ef-9b6e-591f28372ebf"
dummies = pd.get_dummies(cust['Gender'])
dummies

# + id="dUrMGpTpX_ZD" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 402} outputId="68f56e0d-f4e6-4235-ba7d-c5810d192bd6"
cust = cust.merge(dummies, left_index=True, right_index=True)
cust

# + id="kx09neGaYDQu" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 402} outputId="3126c00d-7615-4608-e5ae-a7c73758811d"
new_cust = cust.iloc[:,2:]
new_cust

# + id="Z5BGbil6YIHV" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 299} outputId="e16cee9d-df3a-4869-c9ba-d4c043c10105"
wcss = []
for i in range(1,11):
    km = KMeans(n_clusters=i,init='k-means++', max_iter=300, n_init=10, random_state=0)
    km.fit(new_cust)
    wcss.append(km.inertia_)
plt.plot(range(1,11),wcss, c="#c51b7d")
plt.title('Elbow Method', size=14)
plt.xlabel('Number of clusters', size=12)
plt.ylabel('wcss', size=14)
plt.show()

# + id="1VeEw9GOYL14" colab_type="code" colab={}
kmeans = KMeans(n_clusters=5, init='k-means++', max_iter=10, n_init=10, random_state=0)

# + id="y3z9vjZkYO_l" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 70} outputId="d53ef0d7-ef42-4986-b124-fe0a0f8bbb61"
kmeans.fit(new_cust)

# + id="6234-E7WYTCF" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 195} outputId="12f15c10-0fa5-42ad-dcf8-665c14c2a31d"
centroids = pd.DataFrame(kmeans.cluster_centers_, columns = ["Age", "Annual Income", "Spending", "Male", "Female"])
centroids.index_name = "ClusterID"
centroids["ClusterID"] = centroids.index
centroids = centroids.reset_index(drop=True)
centroids

# + id="kGUMC3WoYWAu" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="e58365c9-6f78-4089-b06b-af13cadd22af"
X_new = np.array([[43, 76, 56, 0, 1]]) 
 
new_customer = kmeans.predict(X_new)
print(f"The new customer belongs to segment(Cluster) {new_customer[0]}")

# + id="WhJD_UpOYYCX" colab_type="code" colab={}


StarcoderdataJupyterScriptsDedupFiltered