# ---
# 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

# ## Task2 - Prediction using Unsupervised ML 
# - From the given ‘Iris’ dataset, predict the optimum number of  clusters and represent it visually. 
# - Use R or Python or perform this task
# - Data can be found at https://bit.ly/3kXTdox -> save as **Iris.csv**

# ### Importing the libraries

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#import sklearn
from sklearn.cluster import KMeans
#from sklearn.metrics import silhouette_score
from sklearn.model_selection import train_test_split


# ### Loading the dataset

# Loading the dataset
df = pd.read_csv("Iris.csv")
df

# Let's check the relationship between the columns
sns.set_style("whitegrid")
sns.pairplot(df,hue="Species",height=3)
plt.show()

# Clustering is an unsupervised learning method that allows us to group set of objects based on similar characteristics. In general, it can help you find meaningful structure among your data, group similar data together and discover underlying patterns.
#
# One of the most common clustering methods is **K-means algorithm**. The goal of this algorithm is to partition the data into set such that the total sum of squared distances from each point to the mean point of the cluster is minimized.

# +
# last column values excluded
x = df.iloc[:, :-1].values 
# last column value
y = df.iloc[:,   -1].values 

# Splitting the dataset into the Training set and Test set
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=0)  
# -

# Let's check the optimal k
Sum_of_squared_distances = []
K = range(1,10)
for num_clusters in K :
    kmeans = KMeans(n_clusters=num_clusters)
    kmeans.fit(df[["SepalLengthCm","SepalWidthCm","PetalLengthCm","PetalWidthCm"]])
    Sum_of_squared_distances.append(kmeans.inertia_)
plt.plot(K,Sum_of_squared_distances,"bx-")
plt.xlabel("Values of K") 
plt.ylabel("Sum of squared distances/Inertia") 
plt.title("Elbow Method For Optimal k")
plt.show()

# ### Observing the elbow method for optimal k we can check above that 3 is the number of cluster that we can use

# +
# Applying Kmeans classifier
kmeans = KMeans(n_clusters=3,init = 'k-means++',   max_iter = 100, n_init = 10, random_state = 0) 
y_kmeans = kmeans.fit_predict(x)

# Display cluster centers
print(f"Cluster centers \n {kmeans.cluster_centers_}")

plt.scatter(x[y_kmeans   == 0, 0], x[y_kmeans == 0, 1],s = 100, c = 'red', label = 'Iris-setosa')

plt.scatter(x[y_kmeans   == 1, 0], x[y_kmeans == 1, 1],s = 100, c = 'blue', label = 'Iris-versicolour')

plt.scatter(x[y_kmeans   == 2, 0], x[y_kmeans == 2, 1],s = 100, c = 'green', label = 'Iris-virginica')   

# Visualising the clusters - On the first two columns
# Plotting the centroids of the clusters

plt.scatter(kmeans.cluster_centers_[:,   0], kmeans.cluster_centers_[:,1],s = 100, c = 'black', label = 'Centroids')   
plt.legend()
plt.show()
# -

# ### In the plot above we can observe the centroids of the 3 groups

StarcoderdataJupyterScriptsDedupFiltered