<jupyter_start><jupyter_text>K-Means<jupyter_code>class KMeans:
    
    def __init__(self, k, scaling=False, random_state=-1):
        
        # scalar : #centroids
        self.k = k
        self.random_state = random_state
        self.scaling = scaling
        
    def standardScaler(self, data):
        
        # shape(#features, )
        data_mean = data.mean(axis=0)
        data_std = data.std(axis=0)

        # shape(#samples, #features)
        scaled_data = (data - data_mean) / data_std

        return scaled_data
        
    def centroidInit(self, data):
        
        if self.random_state != -1:
            np.random.seed(self.random_state)
            
        # shape(#samples, #features)
        centroids = data.copy()
        np.random.shuffle(centroids)
        
        # shape(#centroids, #features)
        return centroids[:self.k]
        
            
    def clusterAssignment(self, data):
        
        # shape(#samples, )
        self.clusters = np.argmin(np.sqrt(((data - self.centroids[:, np.newaxis])**2).sum(axis=2)), axis=0)
        
    def centroidUpdate(self, data):
        
        # shape(#centroids, #features)
        self.old_centroids = self.centroids.copy()
        self.centroids = np.array([data[self.clusters==i].mean(axis=0) for i in range(self.k)])
        
    def fitTransform(self, data):
        
        if self.scaling:
            # shape(#samples, #features)
            data = self.standardScaler(data)
        
        # shape(#centroids, #features)
        self.centroids = self.centroidInit(data)
        
        while True:
            
            self.clusterAssignment(data)
            self.centroidUpdate(data)
            if np.array_equal(self.old_centroids, self.centroids):
                break<jupyter_output><empty_output><jupyter_text>Data Preparation<jupyter_code>df = pd.read_csv('data/Iris.csv')
data = df.drop(['Species'], axis=1).values
data.shape<jupyter_output><empty_output><jupyter_text>Train  Without Scaling<jupyter_code>km = KMeans(3, random_state=0)
km.fitTransform(data)
km.clusters<jupyter_output><empty_output><jupyter_text>With Scaling<jupyter_code>km = KMeans(3, scaling=True, random_state=0)
km.fitTransform(data)
km.clusters<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1209179170344219, 'fraction_numerical': 0.005736981465136805, 'mean_word_length': 2.348596750369276, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '400449', 'license': 'MIT', 'n_tokens_mistral': 762, 'n_tokens_neox': 749, 'n_words': 108, 'path': 'K-means.ipynb', 'repo_name': 'mohdsaqibhbi/ScratchML', 'size': '2266'}