<jupyter_start><jupyter_text>K - Means Clustering  Contextk-means is an unsupervised machine learning algorithm used to find groups of observations (clusters) that share similar characteristics. What is the meaning of unsupervised learning? It means that the observations given in the data set are unlabeled, there is no outcome to be predicted. We are going to use a Wine data set to cluster different types of wines. This data set contains the results of a chemical analysis of wines grown in a specific area of Italy.<jupyter_code>import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.read_csv('wine.csv')
df.columns=['Class', 'Alcohol','Malic acid','Ash','Alcalinity of ash','Magnesium','Total phenols','Flavanoids','Nonflavanoid phenols','Proanthocyanins',
            'Color intensity','Hue','OD280/OD315 of diluted wines','Proline' ]
df.head()<jupyter_output><empty_output><jupyter_text>Clustering the Data  Standardizing the data<jupyter_code>from sklearn.cluster import KMeans<jupyter_output><empty_output><jupyter_text>Optimization of the n cluster: Inertia / Silhouette  Optimization of the n cluster: Elbow method<jupyter_code>kmeans = KMeans(n_clusters=3, init = 'k-means++', random_state = 15)
kmeans = kmeans.fit(df.iloc[:,[12,1]])

centroids_df = pd.DataFrame(kmeans.cluster_centers_, columns = list(df.iloc[:,[12,1]].columns.values))

fig, ax = plt.subplots(1, 1)

df.plot.scatter(x = 'Alcohol', y = 'OD280/OD315 of diluted wines', c= kmeans.labels_, figsize=(12,8), colormap='jet', ax=ax, mark_right=False)

centroids_df.plot.scatter(x = 'Alcohol', y = 'OD280/OD315 of diluted wines', ax = ax,  s = 100, mark_right=False, c='r')
# def find_cluster(value):
#     centers = kmeans.cluster_centers_
    
#     distances = []
    
#     dist0 = np.linalg.norm(centers[0]-(value))
#     distances.append(dist0)
#     dist1 = np.linalg.norm(centers[1]-(value))
#     distances.append(dist1)
#     dist2 = np.linalg.norm(centers[2]-(value)) 
#     distances.append(dist2)
       
#     return distances.index(min(distances))

# df['clusters'] = df[['OD280/OD315 of diluted wines','Alcohol']].apply(lambda value: find_cluster(value), axis=1)
def find_cluster(value):
    centers = kmeans.cluster_centers_
    
    distances = []
    
    for i in range(0, kmeans.n_clusters):
        dist = np.linalg.norm(centers[i]-(value))
        distances.append(dist)
    
       
    return distances.index(min(distances))

df['clusters'] = df[['OD280/OD315 of diluted wines','Alcohol']].apply(lambda value: find_cluster(value), axis=1)
df['clusters'].values<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12974203338391502, 'fraction_numerical': 0.022382397572078907, 'mean_word_length': 4.86, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, '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': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '453740', 'license': 'BSD-2-Clause', 'n_tokens_mistral': 946, 'n_tokens_neox': 886, 'n_words': 221, 'path': 'Machine Learning/K means clustering/K means clustering - K2.ipynb', 'repo_name': 'k21k/Python-Notes', 'size': '2636'}