-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkmeans_mall.py
144 lines (102 loc) · 3.76 KB
/
kmeans_mall.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import plotly.graph_objs as go
from plotly.offline import plot
import seaborn as sns
from time import time
# ============================================================================
df = pd.read_csv('rotated_Mall_Customers.csv', delimiter = ',')
X = df[['Age' , 'Annual Income (k$)' ,'Spending Score (1-100)']].values
# ============================================================================
pd.options.display.max_columns = 10
print(df.describe())
print()
# ----------------------------------------------------------------------------
sns.pairplot(df, vars = df.columns[2:])
plt.tight_layout()
plt.savefig('pairplot_mall_customers_diacak.png', dpi=300)
plt.show()
# ----------------------------------------------------------------------------
plt.title("Heatmap Korelasi Antar Variabel Dataset Diacak")
ax = sns.heatmap(df.corr(), annot = True, cmap = 'RdYlGn')
ax.set_xticklabels(ax.get_xticklabels(), rotation = 40, ha="right")
ax.set_yticklabels(ax.get_yticklabels(), rotation = 68, ha="right")
plt.tight_layout()
plt.savefig('heatmap_mall_customers_diacak.png', dpi=300)
plt.show()
# ============================================================================
kmax = 10
inertia = []
sil = []
for k in range(2, kmax + 1):
kmeans = KMeans(n_clusters = k).fit(X)
labels = kmeans.labels_
inertia.append(kmeans.inertia_)
sil.append(silhouette_score(X, labels, metric = 'euclidean'))
# ----------------------------------------------------------------------------
plt.title("Metode Elbow Dataset Diacak")
plt.plot(range(2, kmax + 1), inertia, marker='o')
plt.xlabel('Jumlah Cluster (k)')
plt.ylabel('Sum of Squared Error')
plt.tight_layout()
plt.savefig('elbow_mall_customers_diacak.png', dpi=300)
plt.show()
# ----------------------------------------------------------------------------
plt.title("Sillhoutte Score Dataset Diacak")
plt.plot(range(2, kmax + 1), sil, marker='o')
plt.xlabel('Jumlah Cluster (k)')
plt.ylabel('Sillhoutte Score')
plt.tight_layout()
plt.savefig('siluet_mall_customers_diacak.png', dpi=300)
plt.show()
# ----------------------------------------------------------------------------
print("Sillhoutte Score setiap K: ")
for i, score in enumerate(sil):
print(str(i + 2) + ": " + str(score))
print()
# ----------------------------------------------------------------------------
highest_sil = max(sil)
k_highest_sil = np.argmax(sil) + 2
print("K terbaik adalah " + str(k_highest_sil) + " dengan Sillhoutte Score sebesar " + str(highest_sil))
print()
# ============================================================================
start_time = time()
kmeans = KMeans(n_clusters = k_highest_sil).fit(X)
print("--- Waktu yang dibutuhkan untuk melatih model adalah %s detik ---" % (time() - start_time))
print()
labels = kmeans.labels_
centroids = kmeans.cluster_centers_
# ----------------------------------------------------------------------------
df['label'] = labels
trace1 = go.Scatter3d(
x = df['Age'],
y = df['Spending Score (1-100)'],
z = df['Annual Income (k$)'],
mode = 'markers',
marker = dict(
color = df['label'],
size = 15,
line = dict(
color = df['label'],
width = 12
),
opacity = 0.8
)
)
data = [trace1]
layout = go.Layout(
title= 'Clusters',
scene = dict(
xaxis = dict(title = 'Age'),
yaxis = dict(title = 'Spending Score'),
zaxis = dict(title = 'Annual Income')
)
)
fig = go.Figure(data=data, layout=layout)
plot(fig)
# ============================================================================