<jupyter_start><jupyter_text>Iris Data-sets step 1 : Importing library<jupyter_code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets<jupyter_output><empty_output><jupyter_text>Step 2 : Loading data of iris<jupyter_code># iris = pd.read_csv("iris.csv")
# iris
iris = datasets.load_iris()
iris
# iris.target
df = pd.DataFrame({
    'x':iris.data[:,0],
    'y':iris.data[:,1],
    'cluster' : iris.target
})
df<jupyter_output><empty_output><jupyter_text>Finding the centroids<jupyter_code>centroids = {}
for i in range(3):
    result = []
    result.append(df.loc[df['cluster'] == i]['x'].mean())
    result.append(df.loc[df['cluster'] == i]['y'].mean())
    centroids[i] = result
centroids<jupyter_output><empty_output><jupyter_text>Plotting The Graph  Step 3 : Draw the scatter graph of cluster<jupyter_code>fig = plt.figure(figsize=(5,5))
plt.scatter(df['x'] ,df['y'], c = iris.target,cmap = 'gist_rainbow')
plt.xlabel('Speal Length ',fontsize=20)
plt.ylabel('Speal Width ',fontsize=20)<jupyter_output><empty_output><jupyter_text>Step 4: Now, Draw the scatter graph of centroids<jupyter_code>cen_map = {0:'y',1:'b',2:'g'}
for i in centroids.keys():
    plt.scatter(centroids[i][0],centroids[i][1],color = cen_map[i])
plt.show()<jupyter_output><empty_output><jupyter_text>Step 5 : Merging the centroids & cluster scatter graphs<jupyter_code>fig = plt.figure(figsize=(5,5))
plt.scatter(df['x'] ,df['y'], c = iris.target,cmap = 'gist_rainbow',alpha = 0.2)

cen_map = {0:'y',1:'b',2:'g'}
for i in centroids.keys():
    plt.scatter(centroids[i][0],centroids[i][1],color = cen_map[i])
plt.show()<jupyter_output><empty_output><jupyter_text>Assignment Stage Step 6 :  Ccalculating  distance and updating dataFrame<jupyter_code>def assignment(df,centroids):
    for i in centroids.keys():
        #sqrt((x1-x2)^2 + (y1-y2))
        df['distance_from_{}'.format(i)] =(
            np.sqrt(
                (df['x']-centroids[i][0]) ** 2 + 
                (df['y']-centroids[i][1]) ** 2
            )
        )
        centroids_dis_cols = ['distance_from_{}'.format(i) for i in centroids.keys()]
    df['closest'] = df.loc[:,centroids_dis_cols].idxmin(axis=1)
    df['closest'] = df['closest'].map(lambda x : int(x.lstrip('distance_from_')))
    df['color'] = df['closest'].map(lambda x : cen_map[x])
    return df
df = assignment(df,centroids)
df
fig = plt.figure(figsize=(5,5))
plt.scatter(df['x'] ,df['y'], c = iris.target,cmap = 'gist_rainbow',alpha = 0.2)

cen_map = {0:'y',1:'b',2:'g'}
for i in centroids.keys():
    plt.scatter(*centroids[i],color = cen_map[i],edgecolor = 'k')
plt.show()<jupyter_output><empty_output><jupyter_text>Updating our new centroids<jupyter_code>def update(k):
    for i in centroids.keys():
        centroids[i][0] = np.mean(df[df['closest']==i]['x'])
        centroids[i][1] = np.mean(df[df['closest']==i]['y'])
        
    return k
centroids = update(centroids )
centroids<jupyter_output><empty_output><jupyter_text>Step 7 : Visualising the graph with updated centroids<jupyter_code>fig = plt.figure(figsize=(5,5))
ax = plt.axes()
plt.scatter(df['x'] ,df['y'], color = df ['color'],alpha = 0.2)
for i in centroids.keys():
    plt.scatter(*centroids[i],color = cen_map[i],edgecolor = 'k')
plt.show()<jupyter_output><empty_output><jupyter_text>Repeat assignment stages to ressign the points with cluster<jupyter_code>df = assignment(df,centroids )<jupyter_output><empty_output><jupyter_text>step 8 : visualising the updated graphs<jupyter_code>fig = plt.figure(figsize=(5,5))
plt.scatter(df['x'] ,df['y'], color = df ['color'],alpha = 0.2)
for i in centroids.keys():
    plt.scatter(centroids[i][0],centroids[i][1],color = cen_map[i],edgecolor = 'k')
plt.show()
while True :
    closest_centroids = df['closest'].copy(deep=True)
    centroids = update(centroids)
    df = assignment(df,centroids)
    if closest_centroids.equals(df['closest']):
        break<jupyter_output><empty_output><jupyter_text>Final Result<jupyter_code>fig = plt.figure(figsize=(5,5))
plt.scatter(df['x'] ,df['y'], color = df ['color'])
for i in centroids.keys():
    plt.scatter(*centroids[i],color = cen_map[i],edgecolor = 'k')
plt.show()<jupyter_output><empty_output><jupyter_text>Previous Cluster<jupyter_code>fig = plt.figure(figsize=(5,5))
plt.scatter(df['x'] ,df['y'], c = iris.target,cmap = 'gist_rainbow')
plt.xlabel('Speal Length ',fontsize=20)
plt.ylabel('Speal Width ',fontsize=20)
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1845742309407044, 'fraction_numerical': 0.015158270173874276, 'mean_word_length': 5.687034277198212, 'pattern_counts': {'":': 0, '<': 53, '<?xml version=': 0, '>': 53, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '13', 'dir': 'jupyter-structured-clean-dedup', 'id': '451155', 'license': 'Apache-2.0', 'n_tokens_mistral': 1810, 'n_tokens_neox': 1791, 'n_words': 286, 'path': 'KMeans_Clustering.ipynb', 'repo_name': 'Shubhanshu-Nishad/Prediction-using-Unsupervised-ML-Iris-datasets', 'size': '4486'}