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

# <h2> <b>Lab 5: Unsupervised Learning - Clustering with K-Means  </b><h2>

# <h4 align="justify"> Unsupervised machine learning algorithms do not have any supervisor to provide any sort of guidance. In unsupervised learning, there would be no correct answer and no teacher for the guidance. Algorithms need to discover the interesting pattern in data for learning.</h4>
# <h4 align="justify">
# Clustering is a type of unsupervised learning method and a common technique for statistical data analysis used in many fields.
# Clustering mainly is a task of dividing the set of observations into subsets, called clusters, in such a way that observations in the same cluster are similar in one sense and they are dissimilar to the observations in other clusters. In simple words, we can say that the main goal of clustering is to group the data on the basis of similarity and dissimilarity.</h4>

# ![Clustering](clustering.jpg)

# <h3> We will use a library called scikit-learn to build our model </h3>

#import the numpy, pandas and scikit-learn library as follows
import numpy as np
import sklearn
import pandas as pd
import matplotlib.pyplot as plt

# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# <h4 align='justify'>The input data is located in the same directory in
# a file named "malls_customer.csv". We will use pandas read_csv function to read the csv file.
# </h4>
# -

dataset = pd.read_csv("mall_customers.csv")

#display the first 3 rows of the dataset
dataset.head(3)

#display the rows and columns in the dataset
dataset.shape

#display the information about dataset
dataset.info()

# <h4>We can see that there are no missing values in the dataset.</h4>

# <h4 align='justify'>We now select the features upon which we want to cluster the dataset. Let us select Annual Income and Spending Score.</h4>

X= dataset.iloc[:, [3,4]].values

X.shape

type(X)

# <h4>We will use KMeans from sklearn.cluster</h4>

# +
from sklearn.cluster import KMeans
wcss = []

for i in range(1, 11):
    model = KMeans(n_clusters=i, init="k-means++", random_state=42)
    model.fit(X)
    wcss.append(model.inertia_)
# -

# <h4 align="justify">Now we initialize the inertia of various values of k and use elbow method to obtain optimal k.</h4>

plt.plot(range(1,11), wcss)
plt.title('The Elbow Method')
plt.xlabel('No of Clusters')
plt.ylabel('wcss')
plt.show()

# <h4 align="justify">We can see that the elbow is at k = 5. Now we will
# use k = 5 to cluster our data.<h4>

finalModel = KMeans(n_clusters= 5, init='k-means++', random_state=42)
finalModel.fit(X)
y_out = finalModel.predict(X)

type(y_out)

# +
plt.scatter(X[:, 0], X[:, 1], c=y_out, s=50, cmap='viridis')

centers = finalModel.cluster_centers_
plt.scatter(centers[:, 0], centers[:, 1], c='black', s=200, alpha=0.5)

StarcoderdataJupyterScriptsDedupFiltered