# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + [markdown] id="1IYlrzOCgoYR"
# # **K Medoid Algorithm**

# + [markdown] id="j50bcWjtgvU9"
# K Medoid is a Clustering Algorithm in Machine Learning that uses Medoids (i.e. Actual Objects in a Cluster) to represent the Cluster.

# + [markdown] id="vtDPkFeTgxc_"
# For using this library in Python this comes under Scikit Learn Extra Library.

# + [markdown] id="9EAAb8Y1nQTf"
# This function operates on an given set of medoids and updates it inplace.
#
# ## Parameters:	
# **C – The cost matrix**, where the cost in K-Medoids algorithm is given as – The dissimilarity of the medoid(Ci) and object(Pi) is calculated by using E = |Pi - Ci|
# <br>
# **Medoids** – The vector of medoid indexes. <br>The contents of medoids serve as the initial guess and will be overrided by the results.

# + [markdown] id="1XOPH5SJoAeM"
# ## K Medoid Clustering Process
# <ol>
#   <li>Initialize: select k random points out of the n data points as the medoids.</li>
#   <li>Associate each data point to the closest medoid by using any common distance metric methods.</li>
#   <li>While the cost decreases:<br>
#         For each medoid m, for each data o point which is not a medoid:
#     <ol>
#       <li>Swap m and o, associate each data point to the closest medoid, recompute the cost.</li>
#       <li>If the total cost is more than that in the previous step, undo the swap.</li>
#     </ol>
#   </li>
# </ol>  
#

# + [markdown] id="OmGfNSfUgzDE"
# In this file , we will showcase how a basic K Medoid Algorithm works in Python , on a randomly created Dataset.

# + colab={"base_uri": "https://localhost:8080/"} id="h77AWPvfiB76" outputId="47df4fa5-1816-46f6-f623-17608c6674f5"
# !pip install scikit-learn-extra #installing the scikit extra library because it isnt inbuilt

# + [markdown] id="fXnctd_zolGl"
# ## Importing Libraries

# + id="RA1ExtSfgkab"
import matplotlib.pyplot as plt #Used for plotting graphs
from sklearn.datasets import make_blobs #Used for creating random dataset
from sklearn_extra.cluster import KMedoids #KMedoid is provided under Scikit-Learn Extra
from sklearn.metrics import confusion_matrix
from sklearn.metrics import silhouette_score
import numpy as np 
import pandas as pd

# + [markdown] id="-l9UR35Tonr9"
# ## Generating Data

# + id="f4W827BshMjg"
data, clusters = make_blobs(
    n_samples=1000, centers=5, cluster_std=0.4, random_state=0
)

# + colab={"base_uri": "https://localhost:8080/", "height": 265} id="nLj6FN0Mkm9r" outputId="b4571701-37b0-4c26-853d-ab47ccda5392"
# Originally created plot with data
plt.scatter(data[:,0], data[:,1])
plt.show()

# + [markdown] id="FQ4QDcCpot6M"
# ## Model Creation

# + id="Ihyuk4rAiziW"
# Creating KMedoids Model
Km_model = KMedoids(n_clusters=5) # n_clusters means the number of clusters to form as well as the number of medoids to generate.

# + colab={"base_uri": "https://localhost:8080/"} id="_BxT5mork81r" outputId="7ff951df-bbb7-4d37-ba13-c79451767c8e"
Km_model.fit(data) #Fitting the data

# + id="pt2QMyYmlHwU"
pred = Km_model.predict(data) #predicting on our randomly created dataset

# + id="xFqAOVrMlSYG"
labels_KMed = Km_model.labels_ #storing labels to check accuracy of model

# + [markdown] id="acn1qDp-oxH6"
# ## Plotting our observations

# + colab={"base_uri": "https://localhost:8080/", "height": 281} id="OcS8T6lQlb6j" outputId="5f6d6cd8-5859-4eb7-b0b6-4877eeaa568d"
# Viewing our Prediction using Plots
plt.scatter(data[:, 0], data[:, 1], c = pred , cmap='rainbow')
plt.plot(
    Km_model.cluster_centers_[:, 0],
    Km_model.cluster_centers_[:, 1],
    "o",
    markerfacecolor="gold",
    markeredgecolor="k",
    markersize=6,
)

plt.title("KMedoids clustering. Medoids are represented in Golden Colour")
plt.show()

# + colab={"base_uri": "https://localhost:8080/"} id="9XP3p4Rpmewi" outputId="c512661f-d9eb-4499-fb2a-b21584d2444c"
Km_model.cluster_centers_ #points which were selected for Medoids in our clustering data

# + [markdown] id="b8R9V0K-l0a5"
# ## Accuracy of K Medoid Clustering

# + colab={"base_uri": "https://localhost:8080/"} id="yvtPL44vikfa" outputId="46865561-94db-4ecb-da2e-5cf13bb25ea9"
KMed_score = silhouette_score(data, labels_KMed)
KMed_score

# + [markdown] id="swaOXrlKoUjZ"
# On this randomly created dataset we got an accuracy of 81.1 %

# + [markdown] id="IKE4ns8An6GG"
# ## Thanks a lot!

StarcoderdataJupyterScriptsDedupFiltered