Question: PLEASE TYPE!! AND DO NOT COPY AND PASTE FROM GOOGLE BECAUSE I WILL BE CHECKING IT!! AND NOT COPYING THE SAME ANSWERS FROM DIFFERENT EXPERTS

PLEASE TYPE!! AND DO NOT COPY AND PASTE FROM GOOGLE BECAUSE I WILL BE CHECKING IT!! AND NOT COPYING THE SAME ANSWERS FROM DIFFERENT EXPERTS BECAUSE I WILL REPORT IT!!!

Please fill in the template below, this is a program of K-means from scratch with a test on it in Python. Replace #PLEASE FILL IN THIS PART with the appropriate code to make the program works.

class KMeans: # K: the number of clusters def __init__(self, K): self.K = K

# The features of centroids; set when `fit` is called self.cluster_centers_ = None

# fit: make clusters # X: data points to cluster -- np.ndarray # (shape: [# of data points, # of features]) def fit(self, X): # PLEASE FILL IN THIS PART! # Store the feature ndarray of centroids in `self.cluster_centers_` # The shape of `self.cluster_centers_` has to be # [self.K, # of features] pass

# predict: Predict the cluster indices of input data points # X: data points predicted -- np.ndarray # (shape: [# of data points, # of features]) # Return an ndarray with shape [# of data points] where # each element is an integer from 0 to self.K-1 def predict(self, X): # PLEASE FILL IN THIS PART pass

# check this is a main file if __name__ == '__main__': import numpy as np from sklearn.datasets import load_iris from sklearn.metrics import mean_squared_error

K = 3 iris_dataset = load_iris() kmeans = KMeans(K) kmeans.fit(iris_dataset.data) predict = kmeans.predict(iris_dataset.data) for k in range(K): indices = np.where(predict == k) features = iris_dataset.data[indices] MSE = mean_squared_error( np.tile(kmeans.cluster_centers_[k], (features.shape[0], 1)), features) print('Cluster', k, 'MSE', MSE) assert(MSE < 0.2)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!