Krepselis commited on
Commit
6d10b44
·
verified ·
1 Parent(s): eb27076

Create clustering.py

Browse files
Files changed (1) hide show
  1. clustering.py +351 -0
clustering.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ from sklearn.preprocessing import StandardScaler
4
+ from sklearn.preprocessing import LabelEncoder
5
+ from sklearn.decomposition import PCA
6
+ from sklearn.cluster import KMeans, AgglomerativeClustering
7
+ import matplotlib.pyplot as plt
8
+ import seaborn as sns
9
+ from scipy.cluster.hierarchy import linkage, dendrogram
10
+ from sklearn.metrics.pairwise import cosine_similarity
11
+ import streamlit as st
12
+
13
+ data_path = '/home/krepselis/Documents/UNI/Applied Data Science & ML/1st Assignment/micro_world_139countries.csv'
14
+ data = pd.read_csv(data_path, encoding='ISO-8859-1', low_memory=False)
15
+ df = pd.read_csv(data_path, encoding='ISO-8859-1')
16
+
17
+ subset_cols = ['economycode', 'age', 'fin7', 'fin8', 'fin8a', 'fin8b', 'fin22a', 'fin24', 'fin34a', 'anydigpayment', 'fin30', 'inc_q', 'educ', 'urbanicity_f2f', 'emp_in']
18
+ subset_df = df[subset_cols].dropna()
19
+
20
+ cc_usage_country = subset_df.groupby('economycode')['fin8'].sum()
21
+ total_usage = cc_usage_country.sum()
22
+ total_usage_prc = (cc_usage_country / total_usage) * 100
23
+
24
+ st.title('Welcome to my humble analysis :sunglasses:')
25
+
26
+ #REFRESH
27
+ if st.button('Refresh Page'):
28
+ st.experimental_rerun()
29
+
30
+
31
+ #===================================================================================================
32
+ #DESCRIPTIVES 1st ASSIGNMENT #there are two csv reading so that it fits the 1st assignment's code...
33
+ #===================================================================================================
34
+ if st.button("CREDIT CARD USAGE DESCRIPTIVES"):
35
+ # Bar chart
36
+ plt.figure(figsize=(12, 6))
37
+ plt.bar(total_usage_prc.index, total_usage_prc.values, color='green')
38
+ plt.xlabel('Country', color='blue')
39
+ plt.ylabel('Credit Card Usage (%)')
40
+ plt.title('Credit Card Usage by Country %', color='blue')
41
+ plt.xticks(rotation=90)
42
+ plt.tight_layout()
43
+
44
+ #dataframe conversion
45
+ df_percentage = total_usage_prc.reset_index()
46
+ df_percentage.columns = ['economycode', 'percentage']
47
+
48
+ #get the economy codes
49
+ min_prc_country = df_percentage.loc[df_percentage['percentage'].idxmin()]
50
+ max_prc_country = df_percentage.loc[df_percentage['percentage'].idxmax()]
51
+
52
+ st.write(f"The minimum CC usage is in: {min_prc_country['economycode']} {min_prc_country['percentage']:.2f}%")
53
+ st.write(f"The maximum CC usage is in: {max_prc_country['economycode']} {max_prc_country['percentage']:.2f}%")
54
+
55
+ # CC per country table
56
+ st.table(df_percentage)
57
+ st.bar_chart(total_usage_prc)
58
+
59
+
60
+ #=========================================================================================================
61
+ #CLUSTERING
62
+ #=========================================================================================================
63
+
64
+ selected_columns = ['age', 'inc_q', 'fin44a', 'fin44b', 'fin44c', 'fin44d',
65
+ 'borrowed', 'saved', 'account_fin', 'anydigpayment',
66
+ 'internetaccess']
67
+
68
+ selected_columns=data[selected_columns] #converting to df, actually not needed :D
69
+
70
+ mean_values=selected_columns['age'].mean()
71
+ selected_columns.fillna(mean_values, inplace=True)
72
+
73
+
74
+ selected_columns.isnull().sum() #filling the 'age' missing vals with the column mean, also not needed HHAHAH
75
+
76
+ features = ['age', 'inc_q', 'fin44a', 'fin44b', 'fin44c', 'fin44d',
77
+ 'borrowed', 'saved', 'account_fin', 'anydigpayment',
78
+ 'internetaccess']
79
+
80
+ X = data[features]
81
+ X.isna().sum()
82
+ X_means=X['age'].mean()
83
+ X.fillna(X_means, inplace=True)
84
+ X.isna().sum() #here is needed :)
85
+
86
+ #X['age'] = pd.to_numeric(X['age'])
87
+ #X['age']
88
+
89
+ scaler = StandardScaler()
90
+ X_scaled = scaler.fit_transform(X)
91
+ #print(X_scaled)
92
+
93
+ pca = PCA()
94
+ X_pca = pca.fit_transform(X_scaled)
95
+ #X_pca
96
+
97
+ explained_variance = pca.explained_variance_ratio_
98
+
99
+ with st.expander("Explained Variance"):
100
+ plt.figure(figsize=(12,7))
101
+ plt.bar(range(len(explained_variance)), explained_variance, alpha=0.7, align='center', color='teal')
102
+ plt.ylabel('Explained Variance Ratio', fontsize=14)
103
+ plt.xlabel('Principal Components', fontsize=14)
104
+ plt.title('PCA: Explained Variance for Each Component', fontsize=16)
105
+ plt.xticks(fontsize=12)
106
+ plt.yticks(fontsize=12)
107
+ plt.tight_layout()
108
+ plt.grid(axis='y')
109
+ plt.show()
110
+
111
+ pca = PCA(n_components=2) #first 2 principal components
112
+ X_pca_2d = pca.fit_transform(X_scaled) #2D Dataframe
113
+
114
+ clusters = []
115
+ for i in range(1, 11):
116
+ kmeans = KMeans(n_clusters=i, random_state=0).fit(X_pca_2d)
117
+ clusters.append(kmeans.inertia_)
118
+
119
+ #plt.figure(figsize=(12,7))
120
+ #plt.plot(range(1, 11), clusters, marker='o', linestyle='--', color='teal')
121
+ #plt.xlabel('Number of Clusters', fontsize=14)
122
+ #plt.ylabel('Inertia', fontsize=14)
123
+ #plt.title('KMeans Elbow Method for Optimal k', fontsize=16)
124
+ #plt.xticks(fontsize=12)
125
+ #plt.yticks(fontsize=12)
126
+ #plt.grid(True)
127
+ #plt.show()
128
+
129
+ kmeans = KMeans(n_clusters=6, random_state=42)
130
+ kmeans.fit(X_pca_2d)
131
+ labels = kmeans.labels_
132
+ #print(labels)
133
+
134
+ #colors = ['red', 'blue', 'green', 'purple', 'black', 'cyan']
135
+ #plt.figure(figsize=(14,8))
136
+ #for i, color, label in zip(range(6), colors, ['Cluster 1', 'Cluster 2', 'Cluster 3', 'Cluster 4', 'cluster 5', 'cluster 6']):
137
+ # plt.scatter(X_pca_2d[labels == i, 0], X_pca_2d[labels == i, 1], s=60, c=color, label=label, alpha=0.6, edgecolors='w', linewidth=0.5)
138
+ #plt.legend(fontsize=12)
139
+ #plt.title('2D PCA with KMeans Clusters', fontsize=16)
140
+ #plt.xlabel('First Principal Component', fontsize=14)
141
+ #plt.ylabel('Second Principal Component', fontsize=14)
142
+ #plt.xticks(fontsize=12)
143
+ #plt.yticks(fontsize=12)
144
+ #plt.grid(True)
145
+ #plt.tight_layout()
146
+ #plt.show()
147
+
148
+ sample_data = X.sample(n=1000, random_state=42)
149
+ #print(sample_data.dtypes)
150
+
151
+ selected_columns = sample_data.columns #selected_columns redefined
152
+ #print(selected_columns)
153
+
154
+ le = LabelEncoder()
155
+ #sample_data['inc_q']=le.fit_transform(sample_data['inc_q'])
156
+ #sample_data['anydigpayment']=le.fit_transform(sample_data['anydigpayment'])
157
+ #sample_data['internetaccess'] = le.fit_transform(sample_data['internetaccess'])
158
+ #sample_data['borrowed'] = le.fit_transform(sample_data['borrowed'])
159
+ #sample_data['saved'] = le.fit_transform(sample_data['saved'])
160
+ #sample_data['account_fin'] = le.fit_transform(sample_data['account_fin'])
161
+ #sample_data['fin44a'] = le.fit_transform(sample_data['fin44a'])
162
+ #sample_data['fin44b'] = le.fit_transform(sample_data['fin44b'])
163
+ #sample_data['fin44c'] = le.fit_transform(sample_data['fin44c'])
164
+ #sample_data['fin44d'] = le.fit_transform(sample_data['fin44d'])
165
+ sample_data['age'] = le.fit_transform(sample_data['age'])
166
+ scaler = StandardScaler()
167
+ X_sample_scaled = scaler.fit_transform(sample_data[selected_columns])
168
+
169
+ #X_sample_scaled
170
+
171
+ pca = PCA(n_components=2)
172
+ X_pca_2d = pca.fit_transform(X_sample_scaled)
173
+ #X_pca_2d #keeping the first 2 clusters which explain the variance
174
+
175
+ linked = linkage(X_pca_2d, method='ward') #method: ward for distance calculation
176
+
177
+ #hierarchical clustering dendrogram
178
+ #plt.figure(figsize=(30, 21))
179
+ #dendrogram(linked)
180
+ #plt.title('Hierarchical Clustering Dendrogram', fontsize=30)
181
+ #plt.xlabel('Samples', fontsize=25)
182
+ #plt.ylabel('Distance', fontsize=25)
183
+ #plt.xticks(fontsize=20, rotation=90)
184
+
185
+ #locs, labels = plt.xticks()
186
+ #plt.xticks(locs[::10], fontsize=20, rotation=90)
187
+ #plt.yticks(fontsize=20)
188
+ #plt.show()
189
+
190
+ hierarchical = AgglomerativeClustering(n_clusters=6, metric='euclidean', linkage='ward')
191
+ hier_clusters = hierarchical.fit_predict(X_pca_2d)
192
+ #hier_clusters
193
+ #automatic data labeling with agglomerative
194
+
195
+ #plt.figure(figsize=(14,8))
196
+ #plt.scatter(X_pca_2d[:, 0], X_pca_2d[:, 1], c=hier_clusters, cmap='plasma')
197
+ #plt.title('Hierarchical Clustering with 2D PCA')
198
+ #plt.xlabel('First Principal Component')
199
+ #plt.ylabel('Second Principal Component')
200
+ #plt.grid(True)
201
+ #plt.tight_layout()
202
+ #plt.show()
203
+
204
+ similarity_matrix = cosine_similarity(X_pca_2d)
205
+ #similarity_matrix
206
+ similarity_df = pd.DataFrame(similarity_matrix, index=range(1000), columns=range(1000)) #creating a similarity matrix dataframe
207
+
208
+ sub_simi_df = similarity_df.iloc[:10, :10]
209
+ #creating a subset of similarity matrix so it can be shown in the heatmap without glitching
210
+ #print(sub_simi_df)
211
+
212
+ #plt.figure(figsize=(10, 8))
213
+ #sns.heatmap(sub_simi_df, cmap='coolwarm')
214
+ #plt.title('Cosine Similarity Matrix Heatmap')
215
+ #plt.xlabel('Sample Index')
216
+ #plt.ylabel('Sample Index')
217
+ #plt.show()
218
+
219
+ def get_recommendations(index, similarity_df, top_n=5):
220
+
221
+ sim_scores = similarity_df[index].sort_values(ascending=False) #most similar points come first
222
+
223
+ sim_scores = sim_scores.iloc[1:top_n+1] #excluding the 1st score which is 0
224
+
225
+
226
+ similar_indices = sim_scores.index.tolist()
227
+
228
+ return similar_indices
229
+
230
+ recommended_indices = get_recommendations(0, similarity_df, top_n=500)
231
+ #print(recommended_indices)
232
+
233
+ #print(f"Recommended records for record 0: {recommended_indices}")
234
+ #print("Details of recommended records:")
235
+ #print(X.iloc[recommended_indices])
236
+
237
+ X['cluster'] = kmeans.labels_
238
+
239
+
240
+ cluster_analysis = X.groupby('cluster').mean().round(3)
241
+
242
+
243
+ #print(cluster_analysis)
244
+
245
+ cluster_analysis['economy'] = data['economy']
246
+
247
+ cols = ['economy'] + [col for col in cluster_analysis.columns if col != 'economy']
248
+ cluster_analysis = cluster_analysis[cols] #reorder the columns so 'economy' is the first one
249
+
250
+ print(cluster_analysis)
251
+
252
+ #print(cols)
253
+
254
+
255
+
256
+ # Set the figure size for the subplots
257
+ plt.figure(figsize=(12, 6))
258
+
259
+ #first plot y=age
260
+ plt.subplot(1, 2, 1) # 1 row, 2 columns, 1st subplot
261
+ sns.barplot(data=X, x='cluster', y='age', palette='dark')
262
+ plt.title('Average Income Quartile by Cluster')
263
+ plt.xlabel('Cluster')
264
+ plt.ylabel('Average Income Quartile')
265
+ plt.xticks(rotation=0)
266
+ plt.grid(axis='y')
267
+
268
+ #second plot y= medical worries
269
+ plt.subplot(1, 2, 2) # 1 row, 2 columns, 2nd subplot
270
+ sns.barplot(data=X, x='cluster', y='fin44b', palette='dark')
271
+ plt.title('Financial Worries about Medical Bills by Cluster')
272
+ plt.xlabel('Cluster')
273
+ plt.ylabel('Financial Worries about Medical Bills')
274
+ plt.xticks(rotation=0)
275
+ plt.grid(axis='y')
276
+
277
+ plt.show()
278
+
279
+
280
+
281
+ with st.expander("Start", expanded=False):
282
+ st.title('PCA: Explained Variance for Each Component')
283
+ st.bar_chart(pca.explained_variance_ratio_)
284
+
285
+ #st.title('2D PCA with KMeans Clusters')
286
+
287
+ #scatter
288
+ #colors = ['red', 'blue', 'green', 'purple', 'black', 'cyan']
289
+ #plt.figure(figsize=(14, 8))
290
+ #for i, color in zip(range(6), colors):
291
+ # plt.scatter(X_pca_2d[labels == i, 0], X_pca_2d[labels == i, 1], s=60, c=color, label=f'Cluster {i + 1}', alpha=0.6, edgecolors='w', linewidth=0.5)
292
+
293
+ #plt.legend(fontsize=17)
294
+ #plt.title('2D PCA with KMeans Clusters', fontsize=16)
295
+ #plt.xlabel('First Principal Component', fontsize=14)
296
+ #plt.ylabel('Second Principal Component', fontsize=14)
297
+ #plt.xticks(fontsize=12)
298
+ #plt.yticks(fontsize=12)
299
+ #plt.grid(True)
300
+ #plt.tight_layout()
301
+ #st.pyplot(plt)
302
+
303
+ st.title("HEATMAP") #Not fitted well to the screen on streamlit :(
304
+
305
+ plt.figure(figsize=(10, 8))
306
+ sns.heatmap(similarity_df, cmap='coolwarm')
307
+ plt.title('Cosine Similarity Matrix Heatmap')
308
+ plt.xlabel('Index')
309
+ plt.ylabel('Index')
310
+ plt.tight_layout()
311
+ st.pyplot(plt)
312
+
313
+
314
+ st.title("Cluster Analysis Table")
315
+ st.table(cluster_analysis)
316
+
317
+ st.title("Explanation of Cluster0 as an example:")
318
+ st.write("""
319
+ - **Age**: ~48
320
+ - **inc_q** (income quartile): 3.7 (~4) belongs to the 20% of the middle class
321
+ - **fin44a** (financially worried about old age): not so worried about financial status about old age (value: 2.8)
322
+ - **fin44b** (financially worried about medical bills): not so worried about medical bills (value: 2.8)
323
+ - **fin44c** (financially worried about bills): not worried at all about bills (value: 2.95)
324
+ - **fin44d** (financially worried about education): not worried at all about educational expenses (value: 3.1)
325
+ - **borrowed** (borrowed money in the past year): A value of 0.53 means that in that cluster there are the 53% of people who have borrowed
326
+ - **saved** (saved money in the past year): A value of 0.8 means that in that cluster there are the 80% of people who have saved
327
+ - **account_fin** (owns an account at a financial institution): A value of 0.99 means that in that cluster there are the 99% of people who own an account at a financial institution
328
+ - **anydigpayment** (if the person made any digital payments): A value of 0.99 means that in that cluster there are the 99% of people who made any digital payments
329
+
330
+ *We can see that the older people between 40 and 50 yrs old are not so worried or worried at all about medical costs than the youth in Afghanistan. In contrast with individuals between 30-40 in cluster4 are very worried about the medical expenses*""")
331
+
332
+ st.title('2 Plots showing Average Income Quartiles and Medical Financial Worries based on the Age:')
333
+
334
+ fig, axes = plt.subplots(1, 2, figsize=(12, 6))
335
+
336
+ #1st plot
337
+ sns.barplot(data=X, x='cluster', y='age', palette='dark', ax=axes[0])
338
+ axes[0].set_title('Average Age by Cluster')
339
+ axes[0].set_xlabel('Cluster')
340
+ axes[0].set_ylabel('Average Age')
341
+ axes[0].grid(axis='y')
342
+
343
+ #2nd plot
344
+ sns.barplot(data=X, x='cluster', y='fin44b', palette='dark', ax=axes[1])
345
+ axes[1].set_title('Financial Worries about Medical Bills by Cluster')
346
+ axes[1].set_xlabel('Cluster')
347
+ axes[1].set_ylabel('Financial Worries about Medical Bills')
348
+ axes[1].grid(axis='y')
349
+
350
+ plt.tight_layout()
351
+ st.pyplot(fig)