Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
debakarr
GitHub Repository: debakarr/machinelearning
Path: blob/master/Part 4 - Clustering/K-Means Clustering/kmeans.py
1009 views
1
# K-Means Clustering
2
3
# Importing the libraries
4
import numpy as np
5
import matplotlib.pyplot as plt
6
import pandas as pd
7
8
# Importing the dataset
9
dataset = pd.read_csv('Mall_Customers.csv')
10
X = dataset.iloc[:, [3, 4]].values
11
# y = dataset.iloc[:, 3].values
12
13
# Splitting the dataset into the Training set and Test set
14
"""from sklearn.cross_validation import train_test_split
15
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)"""
16
17
# Feature Scaling
18
"""from sklearn.preprocessing import StandardScaler
19
sc_X = StandardScaler()
20
X_train = sc_X.fit_transform(X_train)
21
X_test = sc_X.transform(X_test)
22
sc_y = StandardScaler()
23
y_train = sc_y.fit_transform(y_train)"""
24
25
# Using the elbow method to find the optimal number of clusters
26
from sklearn.cluster import KMeans
27
wcss = []
28
for i in range(1, 11):
29
kmeans = KMeans(n_clusters = i, init = 'k-means++', random_state = 42)
30
kmeans.fit(X)
31
wcss.append(kmeans.inertia_)
32
plt.plot(range(1, 11), wcss)
33
plt.title('The Elbow Method')
34
plt.xlabel('Number of clusters')
35
plt.ylabel('WCSS')
36
plt.show()
37
38
# Fitting K-Means to the dataset
39
kmeans = KMeans(n_clusters = 5, init = 'k-means++', random_state = 42)
40
y_kmeans = kmeans.fit_predict(X)
41
42
# Visualising the clusters
43
plt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s = 100, c = 'red', label = 'Cluster 1')
44
plt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s = 100, c = 'blue', label = 'Cluster 2')
45
plt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s = 100, c = 'green', label = 'Cluster 3')
46
plt.scatter(X[y_kmeans == 3, 0], X[y_kmeans == 3, 1], s = 100, c = 'cyan', label = 'Cluster 4')
47
plt.scatter(X[y_kmeans == 4, 0], X[y_kmeans == 4, 1], s = 100, c = 'magenta', label = 'Cluster 5')
48
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s = 300, c = 'yellow', label = 'Centroids')
49
plt.title('Clusters of customers')
50
plt.xlabel('Annual Income (k$)')
51
plt.ylabel('Spending Score (1-100)')
52
plt.legend()
53
plt.show()
54