<jupyter_start><jupyter_text>K-Means- Common clustering technique, helps to solve many problems efficiently.- K-Means is an example of Hard Clustering, where every point belongs only to one cluster. Motivation Problem - *Pizza Parlour Study***Problem Statement** Given the list of locations of customers who frequently order Pizza we want to find out optimal locations of Pizza Parlours where they should be opened.**Step-1** : Initialise Pizza Parlour Centers randomly.**Step-2** : Assign each customer to its nearest Pizza Center.**Step-3** : Update the Center Location by taking mean of customers assigned to it.**Step-4** : Repeat Steps 2 and 3 Until Convergence.  K-Means Algorithm**Input Data** : X = {x1,...,xN}**Goal** : Partition the data among some K number of clusters. Let us assume K is known to us.Let µk denote the center of Kth Cluster (uk will be vector)So we need to ﬁnd an assignment of data points to clusters,as well as a set of cluster centers{µk}, such that the sum of the squares of the distances of each data point to its closest cluster center µk, is a minimum.    Implementation<jupyter_code>import numpy as np
from matplotlib import pyplot as plt
from sklearn.datasets import make_blobs<jupyter_output><empty_output><jupyter_text>Dataset Preparation<jupyter_code>X,y  = make_blobs?
X,y  = make_blobs(n_samples=500,n_features=2,centers=5,random_state=3)
plt.figure(0)
plt.grid(True)
plt.scatter(X[:,0],X[:,1])
plt.show()
k = 5

color  = ["green","red","blue","yellow","orange"]

clusters = {}

for i in range(k):
    center = 10*(2*np.random.random((X.shape[1],))-1)
    points = []
    
    cluster = {
        'center':center,
        'points':points,
        'color': color[i]
        }
    
    clusters[i] = cluster



#center = 10*(2*np.random.random((X.shape[1],))-1)
#print(center)
#clusters
def distance(v1,v2):
    return np.sqrt(np.sum((v1-v2)**2))


#v1 = np.array([1,2])
#v2 = np.array([3,5])
#distance(v1,v2)

# Assign every data point to one of the clusters
for ix in range(X.shape[0]):
    dist = []
    curr_x = X[ix]
    
    for kx in range(k):
        d = distance(curr_x,clusters[kx]['center'])
        dist.append(d)
        
    current_cluster = np.argmin(dist)    
    clusters[current_cluster]['points'].append(curr_x)
   
    
def plotClusters(clusters):
    for kx in range(k):
        pts = clusters[kx]['points']
        print(len(pts))
        
        pts = np.array(pts)
        print(pts.shape)
        
        try:
            plt.scatter(pts[:,0],pts[:,1],color=clusters[kx]['color'])
        except:
            pass

        center = clusters[kx]['center']
        plt.scatter(center[0],center[1],color='black',s=100,marker='*')
plotClusters(clusters)<jupyter_output>84
(84, 2)
5
(5, 2)
26
(26, 2)
284
(284, 2)
101
(101, 2)
{'fraction_non_alphanumeric': 0.13409824309788454, 'fraction_numerical': 0.026891358910003587, 'mean_word_length': 3.5662847790507364, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 8, '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': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '336544', 'license': 'MIT', 'n_tokens_mistral': 986, 'n_tokens_neox': 930, 'n_words': 277, 'path': 'ml_repo/10. K-Means and Color Extraction/.ipynb_checkpoints/K-Means Clustering-Copy1-checkpoint.ipynb', 'repo_name': 'sachinpr0001/data_science', 'size': '2789'}