<jupyter_start><jupyter_text>![title](Header__0004_6.png "Header")___ Chapter 6 - Cluster Analysis Segment 1 - K-means method Setting up for clustering analysis<jupyter_code>import numpy as np
import pandas as pd

import matplotlib.pyplot as plt

import sklearn
from sklearn.cluster import KMeans
from mpl_toolkits.mplot3d import Axes3D
from sklearn.preprocessing import scale
import sklearn.metrics as sm
from sklearn import datasets
from sklearn.metrics import confusion_matrix, classification_report
%matplotlib inline
plt.figure(figsize=(7,4))
iris = datasets.load_iris()

X = scale(iris.data)
y = pd.DataFrame(iris.target)
variable_names = iris.feature_names
X[0:10,]<jupyter_output><empty_output><jupyter_text>Building and running your model<jupyter_code>clustering = KMeans(n_clusters=3, random_state=5)

clustering.fit(X)<jupyter_output><empty_output><jupyter_text>Plotting your model outputs<jupyter_code>iris_df = pd.DataFrame(iris.data)
iris_df.columns = ['Sepal_Length', 'Sepal_Width', 'Petal_Length', 'Petal_Width']
y.columns = ['Targets']
color_theme = np.array(['darkgray', 'lightsalmon', 'powderblue'])

plt.subplot(1,2,1)
plt.scatter(x=iris_df.Petal_Length,y=iris_df.Petal_Width, c=color_theme[iris.target], s=50)
plt.title('Ground Truth Classification')

plt.subplot(1,2,2)
plt.scatter(x=iris_df.Petal_Length,y=iris_df.Petal_Width, c=color_theme[clustering.labels_], s=50)
plt.title('K-Means Classification')
relabel = np.choose(clustering.labels_, [2, 0, 1]).astype(np.int64)
plt.subplot(1,2,1)
plt.scatter(x=iris_df.Petal_Length,y=iris_df.Petal_Width, c=color_theme[iris.target], s=50)
plt.title('Ground Truth Classification')

plt.subplot(1,2,2)
plt.scatter(x=iris_df.Petal_Length,y=iris_df.Petal_Width, c=color_theme[relabel], s=50)
plt.title('K-Means Classification')<jupyter_output><empty_output><jupyter_text>Evaluate your clustering results<jupyter_code>print(classification_report(y, relabel))<jupyter_output>precision    recall  f1-score   support

          0       1.00      1.00      1.00        50
          1       0.74      0.78      0.76        50
          2       0.77      0.72      0.74        50

avg / total       0.83      0.83      0.83       150
{'fraction_non_alphanumeric': 0.1187756966651439, 'fraction_numerical': 0.04111466423024212, 'mean_word_length': 5.083333333333333, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '89513', 'license': 'MIT', 'n_tokens_mistral': 883, 'n_tokens_neox': 818, 'n_words': 146, 'path': 'Ch06/06_01/06_01.ipynb', 'repo_name': 'desaiankitb/Python-for-Data-Science-Essential', 'size': '2189'}