<s> from . base import _BaseCluster <EOL> import numpy as np <EOL> from time import time <EOL> class Kmeans ( _BaseCluster ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , k , max_iter = <NUM_LIT:10> , random_seed = None , print_progress = <NUM_LIT:0> ) : <EOL> super ( Kmeans , self ) . __init__ ( print_progress = print_progress , <EOL> random_seed = random_seed ) <EOL> self . k = k <EOL> self . max_iter = max_iter <EOL> def _fit ( self , X ) : <EOL> """<STR_LIT>""" <EOL> self . iterations_ = <NUM_LIT:0> <EOL> n_samples = X . shape [ <NUM_LIT:0> ] <EOL> idx = np . random . choice ( n_samples , self . k , replace = False ) <EOL> self . centroids_ = X [ idx ] <EOL> for _ in range ( self . max_iter ) : <EOL> self . clusters_ = { i : [ ] for i in range ( self . k ) } <EOL> for sample_idx , cluster_idx in enumerate ( <EOL> self . _get_cluster_idx ( X = X , centroids = self . centroids_ ) ) : <EOL> self . clusters_ [ cluster_idx ] . append ( sample_idx ) <EOL> new_centroids = np . array ( [ np . mean ( X [ self . clusters_ [ k ] ] , axis = <NUM_LIT:0> ) <EOL> for k in sorted ( self . clusters_ . keys ( ) ) ] ) <EOL> if ( self . centroids_ == new_centroids ) . all ( ) : <EOL> break <EOL> else : <EOL> self . centroids_ = new_centroids <EOL> self . iterations_ += <NUM_LIT:1> <EOL> if self . print_progress : <EOL> self . _print_progress ( iteration = self . iterations_ , <EOL> n_iter = self . max_iter ) <EOL> return self <EOL> def _get_cluster_idx ( self , X , centroids ) : <EOL> for sample_idx , sample in enumerate ( X ) : <EOL> dist = np . sqrt ( np . sum ( np . square ( sample - self . centroids_ ) , axis = <NUM_LIT:1> ) ) <EOL> yield np . argmin ( dist ) <EOL> def _predict ( self , X ) : <EOL> """<STR_LIT>""" <EOL> pred = np . array ( [ idx for idx in self . _get_cluster_idx ( X = X , <EOL> centroids = self . centroids_ ) ] ) <EOL> return pred </s>
