human
2. K-means
2.1 Algoritmo completo
Utilizando as funções codificadas anteriormente, complete a classe do algoritmo K-means!
 ... Write me a the Python program you requested?
assistant
#Here is the Python program you requested.
class KMeans():
    
    def __init__(self, n_clusters=8, max_iter=300):
        self.n_clusters = n_clusters
        self.max_iter = max_iter
    
    def fit(self,X):
        
        # Inicializa os centróides
        self.cluster_centers_ = calculate_initial_centers(X, self.n_clusters)
        
        # Computa o cluster de cada amostra
        self.labels_ = all_nearest_centroids(X, self.cluster_centers_)
        
        # Calcula a inércia inicial
        old_inertia   = inertia(X, self.cluster_centers_, self.labels_)
        self.inertia_ = old_inertia
        
        for index in range(self.max_iter):
            
            #### CODE HERE ####
            self.cluster_centers_ = update_centroids(X, self.cluster_centers_, self.labels_)
            self.labels_          = all_nearest_centroids(X, self.cluster_centers_)
            self.inertia_         = inertia(X, self.cluster_centers_, self.labels_)
            
            if (self.inertia_ == old_inertia):
                break
            else:
                old_inertia = self.inertia_
            ### END OF CODE ###
                    
        return self
    
    def predict(self, X):
        
        return all_nearest_centroids(X, self.cluster_centers_)