fit method
Lesson 10 of 19 in Coddy's Introduction to Machine Learning course.
Challenge
HardImplement the fit method and the find_cluster_centroid. The find_cluster_centroid find the centroid of a given list of points (cluster). The instructions on how to find the centroid are in the previous lesson. To implement the fit follow these instructions:
- Initialize Centroids: First, choose
kpoints as the initial centroids from the dataset. To pass the test cases choose the 3th, 5th, 7th, 9th, … points as initial centroids (depending onkpoints) - Assign Clusters: For each point in the dataset, find the nearest centroid (using distance measures such as Euclidean distance) and assign the point to that cluster.
- Update Centroids: Once all points are assigned to clusters, recalculate the centroids by taking the mean of all points in each cluster.
- Repeat Steps 2 and 3: The above steps are repeated until the centroids no longer change significantly. If the distance between the new centroid and the previous centroid is less than
0.01, stop
How to pass the test cases:
- Save the centroids in the
self.centroidsvariable. - Once you find new centroids the total distance between the new centroids and the previous ones is less than
0.01, keep the previous centroids. - The order of the centroids is important. always iterate over the centroids from start to end.
- The test cases will print
self.centroidsand validate if they are correct.
Try it yourself
def euclidian_distance(point_a, point_b):
return (sum([(point_a[i] - point_b[i])**2 for i in range(len(point_a))]))**0.5
class KMeans:
def __init__(self, k):
self.k = k
def find_cluster_centroid(self, cluster_points):
# Write your code here
def fit(self, X_train):
# Write you code here
self.centroids = ...
def predict(self, X_test):
pass