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

# ## The Sparks Foundation

# ### Task 2: Prediction using Unsupervised ML

# #### Predicting the optimum number of clusters and represent it visually.

# #### Created by: <NAME>

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns 

# Sample Dataset: https://bit.ly/3kXTdox

df = pd.read_csv("Iris.csv")
df.head()

df.shape

# ### Viewing the Data

df.info()

df.describe()

df.isnull().sum()

df.columns

x=df[['Id', 'SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm']].values
y=df['Species'].values

sns.pairplot(df,hue='Species',diag_kind='hist')
plt.plot()

sns.heatmap(df.corr(),annot=True)
plt.plot()

# ### Elbow method to find the optimal number of clusters

from sklearn.cluster import KMeans
Range=range(1,10)
Sum_of_squared_errors=[]

for i in Range:
    km=KMeans(n_clusters=i)
    km.fit(x)
    Sum_of_squared_errors.append(km.inertia_)

plt.plot(range(1, 10), Sum_of_squared_errors)
plt.title('Elbow method')
plt.xlabel('No of clusters')
plt.ylabel('SSE')

# From point 3 onwards, the graph becomes almost constant, so the required value of the number of the clusters from the above graph is 3.

# #### Therefore, optimal number of clusters = 3

# ### K-means clustering with number of clusters = 3

kmeans_3=KMeans(n_clusters=3)
kmeans_3.fit(x)

print(kmeans_3.cluster_centers_)

predicted_clusters=kmeans_3.fit_predict(x)

predicted_clusters

# ### Visualization of Clustering

# +
plt.rcParams["figure.figsize"]=10,10
plt.scatter(x[predicted_clusters==0,0],x[predicted_clusters==0,1],s=100,c='red',label='lris-setosa')
plt.scatter(x[predicted_clusters==1,0],x[predicted_clusters==1,1],s=100,c='green',label='lris-versicolour')
plt.scatter(x[predicted_clusters==2,0],x[predicted_clusters==2,1],s=100,c='blue',label='lris-virginica')

plt.scatter(kmeans_3.cluster_centers_[:,0],kmeans_3.cluster_centers_[:,1],s=250,c='yellow',label='Centroids')
plt.legend()
plt.show
# -



StarcoderdataJupyterScriptsDedupFiltered