Task 3: Implement WCSS (Within-Cluster Sum of Squares)
â—†Instructions:
Complete the function get_wcss(df, centroids) from scratch. This function calculates the Within-Cluster Sum of Squares (WCSS), which measures the
compactness of clusters in K-Means clustering. You must calculate the WCSS score based on euclidean distance and manhattan distance.
â—† Note:
X Do NOT use external libraries ( numpy, scipy, sklearn).
✔ Inputs:
df→ The dataset (use the generated one from generate_student_dataset function).
centroids → The cluster centroids as obtained from mykmeans (...)
Implement both Euclidean and Manhattan distance calculations.
✔ Outputs:
wcss_euclidean → The WCSS metric calculated based on euclidean distance function
wcss_manhattan → The WCSS metric calculated based on manhattan distance function
â—† How to find WCSS?
Within-Cluster-Sum of Squared Errors can be computed using the following steps:
The Squared Error for each point is the square of the distance of the point from its closest cluster centroid.
The WCSS score is the sum of these Squared Errors for all the points
The distance metric could be any distance function such as Euclidean Distance and/or the Manhattan Distance
A generic formula for WCSS = ∑(d(point, centroid))², where d(...) will be replaced by the euclidean or manhattan distance function specified below:
Euclidean Distance:
$d(A,B) = \sqrt{\sum_{i}(A_{i} – B_{i})^2}$, (where A_i is the i-th element (or item) in vector A)
Manhattan Distance:
$d(A,B) = \sum_{i}|A_{i} - B_{i}|$, (where A_i is the i-th element (or item) in vector A)
In [ ]: import numpy as np
def get_wcss(df, centroids): # X DO NOT MODIFY the function arguments
"""
Compute the Within-Cluster Sum of Squares (WCSS) using both Euclidean and Manhattan distances.
:param df: Dataset (numpy array), where each row represents a data point.
:param centroids: Cluster centroids (numpy array).
:return: A tuple (WCSS_Euclidean, WCSS_Manhattan).
"""
# --- Your Code Here --- #
wcss_euclidean = # Complete YOUR code
wcss_manhattan = # Complete YOUR code
# --- #
return wcss_euclidean, wcss_manhattan # X DO NOT MODIFY this return statement