-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkmean clustering.py
112 lines (84 loc) · 2.39 KB
/
kmean clustering.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# %% [markdown]
# ### Import Python Packages:
# %%
# Import python packages:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import os
print(os.environ['OMP_NUM_THREADS'])
# Import dataset:
df = pd.read_csv('\Clustering\data.csv')
# %%
# Check first 5 rows of data:
df.head()
# %% [markdown]
# Use elbow method to find the optimal number of clusters:
# %%
# Create 2 dimensional array of our independent variables:
X = df[['Annual Income (k$)', 'Spending Score (1-100)']].values
# %%
# create empty list to store wcss values:
wcss = []
# Loop through X array and compute optimal number of clusters using the WCSS algorithm:
for i in range(1, 11):
# Instantiate kmeans:
kmeans = KMeans(
# set number of clusters:
n_clusters = i,
# set init:
init = "k-means++",
# set random state:
random_state = 42,
)
# Train model:
kmeans.fit(X)
# Append the wcss per cluster to wcss list:
wcss.append(kmeans.inertia_)
# Plot the results:
plt.plot(range(1, 11), wcss)
plt.title("Elbow Method")
plt.xlabel('Number of Clusters')
plt.ylabel("WCSS")
plt.tight_layout()
plt.show()
# %% [markdown]
# ### Train Final Model & Visualize Clusters:
# %%
# Instantiate kmeans:
kmeans = KMeans(
# set number of clusters using the optimal number of clusters found above:
n_clusters = 5,
# set init:
init = "k-means++",
# set random state:
random_state = 42,
)
# Fit model:
y_pred = kmeans.fit_predict(X)
# Print the cluster centers
print("Cluster centers:")
print(kmeans.cluster_centers_)
# Print the labels of the clusters
print("Cluster labels for each data point:")
print(kmeans.labels_)
# Plot the clusters
plt.figure(figsize=(10, 6))
# Colors for different clusters
colors = ['red', 'blue', 'green', 'cyan', 'magenta']
for i in range(5):
plt.scatter(X[y_pred == i, 0], X[y_pred == i, 1], s=100, c=colors[i], label=f'Cluster {i}')
# Plot the centroids
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=300, c='yellow', label='Centroids', edgecolor='black')
# Add titles and labels
plt.title('Clusters of customers')
plt.xlabel('Annual Income (k$)')
plt.ylabel('Spending Score (1-100)')
plt.legend()
plt.tight_layout()
plt.show()
# %%
# %%
# %%
# %%