<jupyter_start><jupyter_text>Author: <NAME>  Task - 2: Prediction using Unsupervised ML Problem Statement : From the given ‘Iris’ dataset, predict the optimum number of clusters and represent it visually. The Sparks Foundation (Graduate Rotational Internship Program (GRIP) June 2021 Batch) Data Science & Business Analytics Tasks  Importing required libraries<jupyter_code>import pandas as pd
from sklearn import datasets
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline<jupyter_output><empty_output><jupyter_text>Loading the Datasets<jupyter_code>df = pd.read_csv('Iris.csv')<jupyter_output><empty_output><jupyter_text>Exploratory Data Analysis<jupyter_code>df.head()      
df.describe()      
df.shape     
df.info()    
df.isnull().any()<jupyter_output><empty_output><jupyter_text>Data Visualization<jupyter_code>plt.figure(figsize=(5,7))
plt.hist(df['SepalLengthCm'], color = "red")
plt.title('Distribution of Sepal length')
plt.xlabel('Sepal length')
plt.show()
plt.figure(figsize=(5,7))
plt.hist(df['PetalLengthCm'])
plt.title('Distribution of Petal length')
plt.xlabel('Petal length')
plt.show()
plt.figure(figsize=(5,7))
plt.hist(df['SepalWidthCm'],color = "red")
plt.title('Distribution of Sepal length')
plt.xlabel('Sepal length')
plt.show()
plt.figure(figsize=(5,7))
plt.hist(df['PetalWidthCm'])
plt.title('Distribution of Petal length')
plt.xlabel('Petal length')
plt.show()
df['Species'].unique().tolist()
sns.pairplot(df.drop("Id", axis=1), hue="Species")
plt.show()
no_id = df.copy()
no_id.drop("Id", axis = 1, inplace = True)
sns.heatmap( no_id.corr() , annot = True, linewidth = 4, linecolor= "blue", cbar = True, cmap = 'Greys' )  #shows the correlation relationship between variables
plt.show()      
df.drop("Id", axis=1).boxplot(by = "Species", figsize=(12, 6))
plt.show()
#PetalLength vs SepalLength
sns.scatterplot(x = 'PetalLengthCm', y = 'SepalLengthCm',edgecolor='k', data = df ,hue ='Species')
plt.title('Petal Length vs Sepal Length')
plt.show()
#PetalWidth vs SepalWidth
sns.scatterplot(x = 'PetalWidthCm', y = 'SepalWidthCm',edgecolor='k', data = df ,hue ='Species')
plt.title('Petal Width vs Sepal Width')
plt.show()<jupyter_output><empty_output><jupyter_text>Finding the optimum numbers of clusters for k-means classification.<jupyter_code>x = df.iloc[:, [1,2,3,4]].values
#using elbow method to find the optimal number of clusters
from sklearn.cluster import KMeans
wcss = []                              # Within cluster sum of squares
for i in range(1, 11):
    kmeans = KMeans(n_clusters = i, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0)
    kmeans.fit(x)
    wcss.append(kmeans.inertia_)<jupyter_output>D:\anaconda\lib\site-packages\sklearn\cluster\_kmeans.py:881: UserWarning: KMeans is known to have a memory leak on Windows with MKL, when there are less chunks than available threads. You can avoid it by setting the environment variable OMP_NUM_THREADS=1.
  warnings.warn(<jupyter_text>**WCSS** is defined as the sum of the squared distance between each member of the cluster and its centroid.<jupyter_code>#Plotting the results onto a line graph
plt.plot(range(1, 11), wcss, "go--", c ='darkmagenta')
plt.title('The Elbow method')
plt.xlabel('Number of clusters')
plt.ylabel('WCSS') 
plt.show()<jupyter_output><empty_output><jupyter_text>**We can clearly state from the above graph that the optimum clusters is where the elbow occurs. This is when the within cluster sum of squares (WCSS) doesn't decrease significantly with every iteration.** The number of clusters  = 3<jupyter_code>#Applying kmeans to the dataset / Creating the kmeans classifier

kmeans = KMeans(n_clusters = 3, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0)
y_kmeans = kmeans.fit_predict(x)
#Visualising the clusters

plt.scatter(x[y_kmeans == 0,0], x[y_kmeans == 0,1], s = 95, edgecolor='k', cmap = 'summer', label = 'Iris-setosa')
plt.scatter(x[y_kmeans == 1,0], x[y_kmeans == 1,1], s = 95, edgecolor='k', cmap = 'summer', label = 'Iris-versicolour')
plt.scatter(x[y_kmeans == 2,0], x[y_kmeans == 2,1], s = 95, edgecolor='k', cmap = 'summer', label = 'Iris-virginica')

centers = kmeans.cluster_centers_
plt.scatter(centers[:,0], centers[:,1], s = 150, edgecolor='k', cmap ='summer', label = 'Centroid')
                                                                
plt.title('Clusters of Iris Species')
plt.legend()
plt.show()<jupyter_output><empty_output>