<jupyter_start><jupyter_text>K-Means Clustering 1. Choose the number of clusters(K) and obtain the data points 2. Place the centroids c_1, c_2, ..... c_k randomly 3. Repeat steps 4 and 5 until convergence or until the end of a fixed number of iterations4. for each data point x_i:       - find the nearest centroid(c_1, c_2 .. c_k)        - assign the point to that cluster 5. for each cluster j = 1..k       - new centroid = mean of all points assigned to that cluster6. End<jupyter_code>dataset = pd.read_csv('Iris.csv')
x = dataset.iloc[:, [1, 2, 3, 4]].values

#Finding the optimum number of clusters for k-means classification
from sklearn.cluster import KMeans
wcss = []

for i in range(1, 11):
    kmeans = KMeans(n_clusters = i, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0)
    kmeans.fit(x)
    wcss.append(kmeans.inertia_)
    
#Plotting the results onto a line graph, allowing us to observe 'The elbow'
plt.plot(range(1, 11), wcss)
plt.title('The elbow method')
plt.xlabel('Number of clusters')
plt.ylabel('WCSS') #within cluster sum of squares
plt.show()
#Applying kmeans to the dataset / Creating the kmeans classifier
kmeans = KMeans(n_clusters = 3, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0)
y_kmeans = kmeans.fit_predict(x)
#Visualising the clusters
plt.scatter(x[y_kmeans == 0, 0], x[y_kmeans == 0, 1], s = 100, c = 'red', label = 'Iris-setosa')
plt.scatter(x[y_kmeans == 1, 0], x[y_kmeans == 1, 1], s = 100, c = 'blue', label = 'Iris-versicolour')
plt.scatter(x[y_kmeans == 2, 0], x[y_kmeans == 2, 1], s = 100, c = 'green', label = 'Iris-virginica')

#Plotting the centroids of the clusters
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:,1], s = 100, c = 'yellow', label = 'Centroids')

plt.legend()
from sklearn.metrics import silhouette_score

silhouette_score(x, y_kmeans)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1337916446324696, 'fraction_numerical': 0.03278688524590164, 'mean_word_length': 4.314606741573034, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, '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': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '214585', 'license': 'MIT', 'n_tokens_mistral': 772, 'n_tokens_neox': 679, 'n_words': 224, 'path': 'Kmeans/Kmeans_using_sklearn.ipynb', 'repo_name': 'anisbhsl/Data-Mining-Assignment', 'size': '1891'}