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

# # Clustering

# +
# %matplotlib inline

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

from sklearn.cluster import KMeans
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

# +
data = load_iris()
df = pd.DataFrame(data.data, columns=data.feature_names)
features = ['petal length (cm)', 'petal width (cm)']

x = df.loc[:, features].values
y = data.target
x = df.loc[:, features].values
x = StandardScaler().fit_transform(x)
# -

pd.DataFrame(x, columns=features).plot.scatter('petal length (cm)', 'petal width (cm)' )
plt.xlabel('petal length (cm)')
plt.ylabel('petal width (cm)')

# <b>Step 1:</b> Make an instance of the Model

kmeans = KMeans(n_clusters=3, random_state=1)
kmeans.fit(x)

# <b>Step 2:</b> Get labels and cluster centroids

labels = kmeans.labels_
centroids = kmeans.cluster_centers_

# <b>Step 3:</b> Visualize the clusters

# +
x = pd.DataFrame(x, columns=features)
colormap = np.array(['r', 'g', 'b'])
plt.figure(figsize=(10,4))

plt.subplot(1, 2, 1)
plt.scatter(x['petal length (cm)'], x['petal width (cm)'], c=colormap[labels])
plt.scatter(centroids[:,0], centroids[:,1], s=100, marker='x', c='k')
plt.xlabel('petal length (cm)')
plt.ylabel('petal width (cm)');
plt.title('K-Means Clustering (k = 3)')
 
plt.subplot(1, 2, 2)
plt.scatter(x['petal length (cm)'], x['petal width (cm)'], c=colormap[y], s=40)
plt.xlabel('petal length (cm)')
plt.ylabel('petal width (cm)');
plt.title('Flower Species')

plt.tight_layout()

StarcoderdataJupyterScriptsDedupFiltered