-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclimateready_heatwave_survey.py
1531 lines (1093 loc) · 57 KB
/
climateready_heatwave_survey.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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""climateready-heatwave-survey.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/16f6Kk54hmL4Gk0FAKd3knuRWVjw5ELjp
# **CLIMATEREADY Thermal Comfort Survey Amid Heatwaves Dataset**
This CLIMATEREADY survey dataset contains thermal comfort votes during the 2021 and 2022 heatwave periods in Pamplona, Spain, as well as other relevant parameters self-reported by surveyees (e.g. occupant characteristics and behaviour, key building/dwelling characteristics), used as case study for the research paper **Exploring indoor thermal comfort and its causes and consequences amid heatwaves in a Southern European city— An unsupervised learning approach**.
This dataset is part of the [CLIMATEREADY research project](https://experience.arcgis.com/experience/a85fb262378b49dc87381261a2e53c91). Its goal is to assess the adaptability of Spanish homes to global warming, promote passive measures in the design and use of buildings to achieve adequate indoor environmental conditions in summer conditions and in heat wave events, minimise and quantify the risks of overheating with the minimum energy demand for cooling when conditions make it necessary.
"""
import sklearn
print(sklearn.__version__)
"""## **Load libraries**"""
#Cargar librerías
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
"""## **Connection to Google Drive**"""
# Conexión con Google Drive
from google.colab import drive
drive.mount('/content/drive')
"""## **Loading and inspecting data**"""
dataset = "/content/drive/My Drive/Post-Doc DATAI/Colaboraciones de investigacion/CLIMATEREADY/encuestas/paper/final draft/climateready-heatwave-survey.csv"
# Read Excel file
merge = pd.read_csv(dataset, sep=";",
encoding='latin-1') # UnicodeDecodeError: 'utf-8' codec can't decode byte 0xed in position 1: invalid continuation byte. SOLVED: encoding='latin-1'
merge
merge.columns
"""## **Research sub-question 1**
### **Normalized rank**
"""
from scipy.stats import rankdata
merge['TSen_day_NR'] = (rankdata(merge['TSen_day']) - 1) / (len(merge['TSen_day']) - 1)
merge['TSen_night_NR'] = (rankdata(merge['TSen_night']) - 1) / (len(merge['TSen_night']) - 1)
merge['TSatisf_day_NR'] = (rankdata(merge['TSatisf_day']) - 1) / (len(merge['TSatisf_day']) - 1)
merge['TSatisf_night_NR'] = (rankdata(merge['TSatisf_night']) - 1) / (len(merge['TSatisf_night']) - 1)
merge['TPref_day_NR'] = (rankdata(merge['TPref_day']) - 1) / (len(merge['TPref_day']) - 1)
merge['TPref_night_NR'] = (rankdata(merge['TPref_night']) - 1) / (len(merge['TPref_night']) - 1)
"""### **KMeans**
"""
kmeans_df = merge[['TSen_day_NR', "TSatisf_day_NR","TPref_day_NR",'TSen_night_NR',"TSatisf_night_NR","TPref_night_NR"]]
kmeans_df.reset_index(drop=True)
kmeans_df = kmeans_df.astype(float)
kmeans_df.info()
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
# Silhouette method for K-means
silhouette_scores_kmeans = []
K = range(2, 11)
for k in K:
kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
labels = kmeans.fit_predict(kmeans_df)
score = silhouette_score(kmeans_df, labels)
silhouette_scores_kmeans.append(score)
print(f"Silhouette score for K-means with {k} clusters: {score}")
# Plot the silhouette scores for K-means
plt.figure(figsize=(5, 5))
plt.plot(K, silhouette_scores_kmeans, 'bx-')
plt.xlabel('Number of clusters')
plt.ylabel('Silhouette Score')
plt.title('Silhouette Method For Optimal k (K-means)')
plt.show()
kmeans = KMeans(n_clusters=2, random_state=42, n_init=10)
merge['cluster_kmeans'] = kmeans.fit_predict(kmeans_df)
merge.groupby("cluster_kmeans").agg("count")["ID"]
# merge['cluster_kmeans'] = merge['cluster_kmeans'].replace({1: 0, 0: 1})
merge.groupby("cluster_kmeans").agg("count")["ID"]
# Select only numeric columns
numeric_columns = merge.select_dtypes(include=[np.number])
numeric_columns.groupby("cluster_kmeans").agg("median")["TPref_night"]
merge[["ID","cluster_kmeans"]].to_csv('cluster_kmeans_enpunto.csv', sep=';', index=False)
"""#### **Summary: Sensation**
"""
TSen_day_cluster0 = merge[merge["cluster_kmeans"] == 0].groupby("TSen_day").agg("count")[["ID"]]
TSen_day_cluster1 = merge[merge["cluster_kmeans"] == 1].groupby("TSen_day").agg("count")[["ID"]]
TSen_day_cluster0 = TSen_day_cluster0.transpose()
TSen_day_cluster1 = TSen_day_cluster1.transpose()
TSen_day_cluster0.index = pd.MultiIndex.from_product([['Comfortable'], TSen_day_cluster0.index])
TSen_day_cluster1.index = pd.MultiIndex.from_product([['Uncomfortable'], TSen_day_cluster1.index])
TSen_day_summary = pd.concat([TSen_day_cluster0, TSen_day_cluster1], axis=0)
TSen_day_summary = TSen_day_summary.droplevel(1)
TSen_day_summary = TSen_day_summary.reset_index()
TSen_day_summary["time_of_the_day"] = "Day"
TSen_day_summary
TSen_night_cluster0 = merge[merge["cluster_kmeans"] == 0].groupby("TSen_night").agg("count")[["ID"]]
TSen_night_cluster1 = merge[merge["cluster_kmeans"] == 1].groupby("TSen_night").agg("count")[["ID"]]
TSen_night_cluster0 = TSen_night_cluster0.transpose()
TSen_night_cluster1 = TSen_night_cluster1.transpose()
TSen_night_cluster0.index = pd.MultiIndex.from_product([['Comfortable'], TSen_night_cluster0.index])
TSen_night_cluster1.index = pd.MultiIndex.from_product([['Uncomfortable'], TSen_night_cluster1.index])
TSen_night_summary = pd.concat([TSen_night_cluster0, TSen_night_cluster1], axis=0)
TSen_night_summary = TSen_night_summary.droplevel(1)
TSen_night_summary = TSen_night_summary.reset_index()
TSen_night_summary["time_of_the_day"] = "Night"
TSen_night_summary
TSen_summary = pd.concat([TSen_day_summary, TSen_night_summary], axis=0)
TSen_summary.to_csv('TSen_summary_kmeans.csv', sep=';', index=False)
TSen_summary
"""#### **Summary: Satisfaction**
"""
TSatis_day_cluster0 = merge[merge["cluster_kmeans"] == 0].groupby("TSatisf_day").agg("count")[["ID"]]
TSatis_day_cluster1 = merge[merge["cluster_kmeans"] == 1].groupby("TSatisf_day").agg("count")[["ID"]]
TSatis_day_cluster0 = TSatis_day_cluster0.transpose()
TSatis_day_cluster1 = TSatis_day_cluster1.transpose()
TSatis_day_cluster0.index = pd.MultiIndex.from_product([['Comfortable'], TSatis_day_cluster0.index])
TSatis_day_cluster1.index = pd.MultiIndex.from_product([['Uncomfortable'], TSatis_day_cluster1.index])
TSatis_day_summary = pd.concat([TSatis_day_cluster0, TSatis_day_cluster1], axis=0)
TSatis_day_summary = TSatis_day_summary.droplevel(1)
TSatis_day_summary = TSatis_day_summary.reset_index()
TSatis_day_summary["time_of_the_day"] = "Day"
TSatis_day_summary
TSatis_night_cluster0 = merge[merge["cluster_kmeans"] == 0].groupby("TSatisf_night").agg("count")[["ID"]]
TSatis_night_cluster1 = merge[merge["cluster_kmeans"] == 1].groupby("TSatisf_night").agg("count")[["ID"]]
TSatis_night_cluster0 = TSatis_night_cluster0.transpose()
TSatis_night_cluster1 = TSatis_night_cluster1.transpose()
TSatis_night_cluster0.index = pd.MultiIndex.from_product([['Comfortable'], TSatis_night_cluster0.index])
TSatis_night_cluster1.index = pd.MultiIndex.from_product([['Uncomfortable'], TSatis_night_cluster1.index])
TSatis_night_summary = pd.concat([TSatis_night_cluster0, TSatis_night_cluster1], axis=0)
TSatis_night_summary = TSatis_night_summary.droplevel(1)
TSatis_night_summary = TSatis_night_summary.reset_index()
TSatis_night_summary["time_of_the_day"] = "Night"
TSatis_night_summary
TSatis_summary = pd.concat([TSatis_day_summary, TSatis_night_summary], axis=0)
TSatis_summary.to_csv('TSatis_summary_kmeans.csv', sep=';', index=False)
TSatis_summary
"""#### **Summary: Preference**
"""
TPref_day_cluster0 = merge[merge["cluster_kmeans"] == 0].groupby("TPref_day").agg("count")[["ID"]]
TPref_day_cluster1 = merge[merge["cluster_kmeans"] == 1].groupby("TPref_day").agg("count")[["ID"]]
TPref_day_cluster0 = TPref_day_cluster0.transpose()
TPref_day_cluster1 = TPref_day_cluster1.transpose()
TPref_day_cluster0.index = pd.MultiIndex.from_product([['Comfortable'], TPref_day_cluster0.index])
TPref_day_cluster1.index = pd.MultiIndex.from_product([['Uncomfortable'], TPref_day_cluster1.index])
TPref_day_summary = pd.concat([TPref_day_cluster0, TPref_day_cluster1], axis=0)
TPref_day_summary = TPref_day_summary.droplevel(1)
TPref_day_summary = TPref_day_summary.reset_index()
TPref_day_summary["time_of_the_day"] = "Day"
TPref_day_summary
TPref_night_cluster0 = merge[merge["cluster_kmeans"] == 0].groupby("TPref_night").agg("count")[["ID"]]
TPref_night_cluster1 = merge[merge["cluster_kmeans"] == 1].groupby("TPref_night").agg("count")[["ID"]]
TPref_night_cluster0 = TPref_night_cluster0.transpose()
TPref_night_cluster1 = TPref_night_cluster1.transpose()
TPref_night_cluster0.index = pd.MultiIndex.from_product([['Comfortable'], TPref_night_cluster0.index])
TPref_night_cluster1.index = pd.MultiIndex.from_product([['Uncomfortable'], TPref_night_cluster1.index])
TPref_night_summary = pd.concat([TPref_night_cluster0, TPref_night_cluster1], axis=0)
TPref_night_summary = TPref_night_summary.droplevel(1)
TPref_night_summary = TPref_night_summary.reset_index()
TPref_night_summary["time_of_the_day"] = "Night"
TPref_night_summary
TPref_summary = pd.concat([TPref_day_summary, TPref_night_summary], axis=0)
TPref_summary.to_csv('TPref_summary_kmeans.csv', sep=';', index=False)
TPref_summary
"""### **Hierarchical clustering**
"""
import pandas as pd
from sklearn.cluster import AgglomerativeClustering
from scipy.cluster.hierarchy import dendrogram, linkage
# Your data
hclust_df = merge[['TSen_day_NR', 'TSatisf_day_NR', 'TPref_day_NR', 'TSen_night_NR', 'TSatisf_night_NR', 'TPref_night_NR']]
hclust_df.reset_index(drop=True, inplace=True) # Make sure to use drop=True to avoid creating a new index
hclust_df = hclust_df.astype(float)
# Silhouette method for Hierarchical Clustering
silhouette_scores_hierarchical = []
for k in K:
hierarchical_clustering = AgglomerativeClustering(n_clusters=k, metric='euclidean', linkage='complete')
labels = hierarchical_clustering.fit_predict(hclust_df)
score = silhouette_score(hclust_df, labels)
silhouette_scores_hierarchical.append(score)
print(f"Silhouette score for Hierarchical Clustering with {k} clusters: {score}")
# Plot the silhouette scores for hierarchical clustering
plt.figure(figsize=(5, 5))
plt.plot(K, silhouette_scores_hierarchical, 'bx-')
plt.xlabel('Number of clusters')
plt.ylabel('Silhouette Score')
plt.title('Silhouette Method For Optimal k (Hierarchical Clustering)')
plt.show()
# Apply hierarchical clustering
n_clusters = 2 # Set the number of clusters
hierarchical_clustering = AgglomerativeClustering(n_clusters=n_clusters, metric='euclidean', linkage='complete') # average or complete
merge['cluster_hierarchical'] = hierarchical_clustering.fit_predict(hclust_df)
# Group by cluster and count
cluster_counts = merge.groupby('cluster_hierarchical').agg(count=('ID', 'count'))
print(cluster_counts)
merge['cluster_hierarchical'] = merge['cluster_hierarchical'].replace({1: 0, 0: 1})
merge.groupby("cluster_hierarchical").agg("count")["ID"]
# Select only numeric columns
numeric_columns = merge.select_dtypes(include=[np.number])
numeric_columns.groupby("cluster_hierarchical").agg("median")["TPref_night"]
merge[["ID","cluster_hierarchical"]].to_csv('cluster_hierarchical_enpunto.csv', sep=';', index=False)
"""##### **Summary: Sensation**
"""
TSen_day_cluster0 = merge[merge["cluster_hierarchical"] == 0].groupby("TSen_day").agg("count")[["ID"]]
TSen_day_cluster1 = merge[merge["cluster_hierarchical"] == 1].groupby("TSen_day").agg("count")[["ID"]]
TSen_day_cluster0 = TSen_day_cluster0.transpose()
TSen_day_cluster1 = TSen_day_cluster1.transpose()
TSen_day_cluster0.index = pd.MultiIndex.from_product([['Comfortable'], TSen_day_cluster0.index])
TSen_day_cluster1.index = pd.MultiIndex.from_product([['Uncomfortable'], TSen_day_cluster1.index])
TSen_day_summary = pd.concat([TSen_day_cluster0, TSen_day_cluster1], axis=0)
TSen_day_summary = TSen_day_summary.droplevel(1)
TSen_day_summary = TSen_day_summary.reset_index()
TSen_day_summary["time_of_the_day"] = "Day"
TSen_day_summary
TSen_night_cluster0 = merge[merge["cluster_hierarchical"] == 0].groupby("TSen_night").agg("count")[["ID"]]
TSen_night_cluster1 = merge[merge["cluster_hierarchical"] == 1].groupby("TSen_night").agg("count")[["ID"]]
TSen_night_cluster0 = TSen_night_cluster0.transpose()
TSen_night_cluster1 = TSen_night_cluster1.transpose()
TSen_night_cluster0.index = pd.MultiIndex.from_product([['Comfortable'], TSen_night_cluster0.index])
TSen_night_cluster1.index = pd.MultiIndex.from_product([['Uncomfortable'], TSen_night_cluster1.index])
TSen_night_summary = pd.concat([TSen_night_cluster0, TSen_night_cluster1], axis=0)
TSen_night_summary = TSen_night_summary.droplevel(1)
TSen_night_summary = TSen_night_summary.reset_index()
TSen_night_summary["time_of_the_day"] = "Night"
TSen_night_summary
TSen_summary = pd.concat([TSen_day_summary, TSen_night_summary], axis=0)
TSen_summary.to_csv('TSen_summary_hclust.csv', sep=';', index=False)
TSen_summary
"""##### **Summary: Satisfaction**
"""
TSatis_day_cluster0 = merge[merge["cluster_hierarchical"] == 0].groupby("TSatisf_day").agg("count")[["ID"]]
TSatis_day_cluster1 = merge[merge["cluster_hierarchical"] == 1].groupby("TSatisf_day").agg("count")[["ID"]]
TSatis_day_cluster0 = TSatis_day_cluster0.transpose()
TSatis_day_cluster1 = TSatis_day_cluster1.transpose()
TSatis_day_cluster0.index = pd.MultiIndex.from_product([['Comfortable'], TSatis_day_cluster0.index])
TSatis_day_cluster1.index = pd.MultiIndex.from_product([['Uncomfortable'], TSatis_day_cluster1.index])
TSatis_day_summary = pd.concat([TSatis_day_cluster0, TSatis_day_cluster1], axis=0)
TSatis_day_summary = TSatis_day_summary.droplevel(1)
TSatis_day_summary = TSatis_day_summary.reset_index()
TSatis_day_summary["time_of_the_day"] = "Day"
TSatis_day_summary
TSatis_night_cluster0 = merge[merge["cluster_hierarchical"] == 0].groupby("TSatisf_night").agg("count")[["ID"]]
TSatis_night_cluster1 = merge[merge["cluster_hierarchical"] == 1].groupby("TSatisf_night").agg("count")[["ID"]]
TSatis_night_cluster0 = TSatis_night_cluster0.transpose()
TSatis_night_cluster1 = TSatis_night_cluster1.transpose()
TSatis_night_cluster0.index = pd.MultiIndex.from_product([['Comfortable'], TSatis_night_cluster0.index])
TSatis_night_cluster1.index = pd.MultiIndex.from_product([['Uncomfortable'], TSatis_night_cluster1.index])
TSatis_night_summary = pd.concat([TSatis_night_cluster0, TSatis_night_cluster1], axis=0)
TSatis_night_summary = TSatis_night_summary.droplevel(1)
TSatis_night_summary = TSatis_night_summary.reset_index()
TSatis_night_summary["time_of_the_day"] = "Night"
TSatis_night_summary
TSatis_summary = pd.concat([TSatis_day_summary, TSatis_night_summary], axis=0)
TSatis_summary.to_csv('TSatis_summary_hclust.csv', sep=';', index=False)
TSatis_summary
"""##### **Summary: Preference**
"""
TPref_day_cluster0 = merge[merge["cluster_hierarchical"] == 0].groupby("TPref_day").agg("count")[["ID"]]
TPref_day_cluster1 = merge[merge["cluster_hierarchical"] == 1].groupby("TPref_day").agg("count")[["ID"]]
TPref_day_cluster0 = TPref_day_cluster0.transpose()
TPref_day_cluster1 = TPref_day_cluster1.transpose()
TPref_day_cluster0.index = pd.MultiIndex.from_product([['Comfortable'], TPref_day_cluster0.index])
TPref_day_cluster1.index = pd.MultiIndex.from_product([['Uncomfortable'], TPref_day_cluster1.index])
TPref_day_summary = pd.concat([TPref_day_cluster0, TPref_day_cluster1], axis=0)
TPref_day_summary = TPref_day_summary.droplevel(1)
TPref_day_summary = TPref_day_summary.reset_index()
TPref_day_summary["time_of_the_day"] = "Day"
TPref_day_summary
TPref_night_cluster0 = merge[merge["cluster_hierarchical"] == 0].groupby("TPref_night").agg("count")[["ID"]]
TPref_night_cluster1 = merge[merge["cluster_hierarchical"] == 1].groupby("TPref_night").agg("count")[["ID"]]
TPref_night_cluster0 = TPref_night_cluster0.transpose()
TPref_night_cluster1 = TPref_night_cluster1.transpose()
TPref_night_cluster0.index = pd.MultiIndex.from_product([['Comfortable'], TPref_night_cluster0.index])
TPref_night_cluster1.index = pd.MultiIndex.from_product([['Uncomfortable'], TPref_night_cluster1.index])
TPref_night_summary = pd.concat([TPref_night_cluster0, TPref_night_cluster1], axis=0)
TPref_night_summary = TPref_night_summary.droplevel(1)
TPref_night_summary = TPref_night_summary.reset_index()
TPref_night_summary["time_of_the_day"] = "Night"
TPref_night_summary
TPref_summary = pd.concat([TPref_day_summary, TPref_night_summary], axis=0)
TPref_summary.to_csv('TPref_summary_hclust.csv', sep=';', index=False)
TPref_summary
"""### **Venn Diagram**
"""
# Create a DataFrame containing the relevant columns
df_subset = merge[['cluster_kmeans', 'cluster_hierarchical']]
# Create a cross-tabulation (confusion matrix-like table)
confusion_matrix = pd.crosstab(index=df_subset['cluster_kmeans'],
columns=df_subset['cluster_hierarchical'],
rownames=['K-Means'], colnames=['Hierarchical Clustering'])
# Print the confusion matrix-like table
print(confusion_matrix)
pip install matplotlib_venn
import matplotlib.pyplot as plt
from matplotlib_venn import venn3, venn2
kmeans_values = set(merge.loc[merge['cluster_kmeans'] == 1].index)
hierarchical_values = set(merge.loc[merge['cluster_hierarchical'] == 1].index)
# Calculate the intersection and set sizes
venn_labels = {'10': kmeans_values - hierarchical_values,
'01': hierarchical_values - kmeans_values,
'11': kmeans_values.intersection(hierarchical_values)}
# Create Venn diagram
venn_labels = venn2(subsets=(len(venn_labels['10']), len(venn_labels['01']), len(venn_labels['11'])),
set_labels=('KMeans', 'HierarchicalClustering'))
plt.savefig("venn_htd.png", dpi=300) # Save the plot as PNG with 300dpi
plt.show()
kmeans_values = set(merge.loc[merge['cluster_kmeans'] == 0].index)
hierarchical_values = set(merge.loc[merge['cluster_hierarchical'] == 0].index)
# Calculate the intersection and set sizes
venn_labels = {'10': kmeans_values - hierarchical_values,
'01': hierarchical_values - kmeans_values,
'11': kmeans_values.intersection(hierarchical_values)}
# Create Venn diagram
venn_labels = venn2(subsets=(len(venn_labels['10']), len(venn_labels['01']), len(venn_labels['11'])),
set_labels=('KMeans', 'HierarchicalClustering'))
plt.savefig("venn_ltd.png", dpi=300) # Save the plot as PNG with 300dpi
plt.show()
from sklearn.metrics import adjusted_rand_score
# Create your clustering results as 1D arrays
kmeans_array = merge["cluster_kmeans"].values
hierarchical_array = merge["cluster_hierarchical"].values
# Calculate ARI
ari = adjusted_rand_score(kmeans_array, hierarchical_array)
# Print the results
print(f'ARI for LTD: {ari}')
"""##### **Crosstab Sensation**
"""
import seaborn as sns
"""**K-Means**"""
# Create a DataFrame containing the relevant columns
df_subset = merge[['TSen_day', 'TSen_night', 'cluster_kmeans']]
# Filter by the desired cluster_kmeans value (replace 'desired_cluster_value' with the actual value you want to filter)
filtered_df = df_subset[df_subset['cluster_kmeans'] == 1]
# Create a cross-tabulation (confusion matrix-like table)
confusion_matrix = pd.crosstab(index=filtered_df['TSen_night'],
columns=filtered_df['TSen_day'],
rownames=['TSen_night'], colnames=['TSen_day'])
# Print the confusion matrix-like table
print(confusion_matrix)
# Create a DataFrame containing the relevant columns
df_subset = merge[['TSen_day', 'TSen_night', 'cluster_kmeans']]
# Filter by the desired cluster_kmeans value (replace 'desired_cluster_value' with the actual value you want to filter)
filtered_df = df_subset[df_subset['cluster_kmeans'] == 0]
# Create a cross-tabulation (confusion matrix-like table)
confusion_matrix = pd.crosstab(index=filtered_df['TSen_night'],
columns=filtered_df['TSen_day'],
rownames=['TSen_night'], colnames=['TSen_day'])
# Print the confusion matrix-like table
print(confusion_matrix)
"""**Hierarchical Clustering**"""
# Create a DataFrame containing the relevant columns
df_subset = merge[['TSen_day', 'TSen_night', 'cluster_hierarchical']]
# Filter by the desired cluster_cluster_hierarchical value (replace 'desired_cluster_value' with the actual value you want to filter)
filtered_df = df_subset[df_subset['cluster_hierarchical'] == 1]
# Create a cross-tabulation (confusion matrix-like table)
confusion_matrix = pd.crosstab(index=filtered_df['TSen_night'],
columns=filtered_df['TSen_day'],
rownames=['TSen_night'], colnames=['TSen_day'])
# Print the confusion matrix-like table
print(confusion_matrix)
# Create a DataFrame containing the relevant columns
df_subset = merge[['TSen_day', 'TSen_night', 'cluster_hierarchical']]
# Filter by the desired cluster_cluster_hierarchical value (replace 'desired_cluster_value' with the actual value you want to filter)
filtered_df = df_subset[df_subset['cluster_hierarchical'] == 0]
# Create a cross-tabulation (confusion matrix-like table)
confusion_matrix = pd.crosstab(index=filtered_df['TSen_night'],
columns=filtered_df['TSen_day'],
rownames=['TSen_night'], colnames=['TSen_day'])
# Print the confusion matrix-like table
print(confusion_matrix)
"""**Hstograms**"""
# List of filter conditions
filters = ["cluster_kmeans", "cluster_hierarchical"]
# Create subplots
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
# Loop through filters and create subplots
for i, filter_col in enumerate(filters):
ax = axes[i]
# Apply filter condition and plot
data_subset = merge[merge[filter_col] == 1]
sns.histplot(merge[merge[filter_col] == 1], x="TSen_day", y="TSen_night", legend=False, discrete=(True, True), ax=ax)
ticks = range(-3, 4)
ax.set_xticks(ticks)
ax.set_yticks(ticks)
ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)
# Set subplot title
if filter_col == "cluster_kmeans":
ax.set_title("K-Means")
# Add text in the top left corner
ax.text(-3.8, 3.8, "'Uncomfortable' cluster (n=97)", fontsize=10, ha='left', va='top', color='black')
elif filter_col == "cluster_hierarchical":
ax.set_title("Hierarchical Clustering")
# Add text in the top left corner
ax.text(-3.8, 3.8, "'Uncomfortable' cluster (n=113)", fontsize=10, ha='left', va='top', color='black')
# Set x and y axis titles
ax.set_xlabel("TSEN_day")
ax.set_ylabel("TSEN_night")
# Add frequency labels using annotate
for (x, y), count in data_subset.groupby(["TSen_day", "TSen_night"]).size().items():
ax.annotate(count, (x, y), textcoords="offset points", xytext=(0, 3), ha='center', fontsize=10, color='white')
# Adjust layout and show the plot
plt.tight_layout()
plt.savefig("TSen_HTD.png", dpi=300) # Save the plot as PNG with 300dpi
plt.show()
# List of filter conditions
filters = ["cluster_kmeans", "cluster_hierarchical"]
# Create subplots
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
# Loop through filters and create subplots
for i, filter_col in enumerate(filters):
ax = axes[i]
# Apply filter condition and plot
data_subset = merge[merge[filter_col] == 0]
sns.histplot(merge[merge[filter_col] == 0], x="TSen_day", y="TSen_night", legend=False, discrete=(True, True), ax=ax)
ticks = range(-3, 4)
ax.set_xticks(ticks)
ax.set_yticks(ticks)
ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)
# Set subplot title
if filter_col == "cluster_kmeans":
ax.set_title("K-Means")
# Add text in the top left corner
ax.text(-3.8, 3.8, "'Comfortable' cluster (n=92)", fontsize=10, ha='left', va='top', color='black')
elif filter_col == "cluster_hierarchical":
ax.set_title("Hierarchical Clustering")
# Add text in the top left corner
ax.text(-3.8, 3.8, "'Comfortable' cluster (n=76)", fontsize=10, ha='left', va='top', color='black')
# Set x and y axis titles
ax.set_xlabel("TSEN_day")
ax.set_ylabel("TSEN_night")
# Add frequency labels using annotate
for (x, y), count in data_subset.groupby(["TSen_day", "TSen_night"]).size().items():
ax.annotate(count, (x, y), textcoords="offset points", xytext=(0, 3), ha='center', fontsize=10, color='white')
# Adjust layout and show the plot
plt.tight_layout()
plt.savefig("TSen_LTD.png", dpi=300) # Save the plot as PNG with 300dpi
plt.show()
"""##### **Crosstab Satisfaction**
**K-Means**
"""
# Create a DataFrame containing the relevant columns
df_subset = merge[['TSatisf_day', 'TSatisf_night', 'cluster_kmeans']]
# Filter by the desired cluster_kmeans value (replace 'desired_cluster_value' with the actual value you want to filter)
filtered_df = df_subset[df_subset['cluster_kmeans'] == 1]
# Create a cross-tabulation (confusion matrix-like table)
confusion_matrix = pd.crosstab(index=filtered_df['TSatisf_night'],
columns=filtered_df['TSatisf_day'],
rownames=['TSatisf_night'], colnames=['TSatisf_day'])
# Print the confusion matrix-like table
print(confusion_matrix)
# Create a DataFrame containing the relevant columns
df_subset = merge[['TSatisf_day', 'TSatisf_night', 'cluster_kmeans']]
# Filter by the desired cluster_kmeans value (replace 'desired_cluster_value' with the actual value you want to filter)
filtered_df = df_subset[df_subset['cluster_kmeans'] == 0]
# Create a cross-tabulation (confusion matrix-like table)
confusion_matrix = pd.crosstab(index=filtered_df['TSatisf_night'],
columns=filtered_df['TSatisf_day'],
rownames=['TSatisf_night'], colnames=['TSatisf_day'])
# Print the confusion matrix-like table
print(confusion_matrix)
"""**Hierarchical Clustering**"""
# Create a DataFrame containing the relevant columns
df_subset = merge[['TSatisf_day', 'TSatisf_night', 'cluster_hierarchical']]
# Filter by the desired cluster_hierarchical value (replace 'desired_cluster_value' with the actual value you want to filter)
filtered_df = df_subset[df_subset['cluster_hierarchical'] == 1]
# Create a cross-tabulation (confusion matrix-like table)
confusion_matrix = pd.crosstab(index=filtered_df['TSatisf_night'],
columns=filtered_df['TSatisf_day'],
rownames=['TSatisf_night'], colnames=['TSatisf_day'])
# Print the confusion matrix-like table
print(confusion_matrix)
# Create a DataFrame containing the relevant columns
df_subset = merge[['TSatisf_day', 'TSatisf_night', 'cluster_hierarchical']]
# Filter by the desired cluster_hierarchical value (replace 'desired_cluster_value' with the actual value you want to filter)
filtered_df = df_subset[df_subset['cluster_hierarchical'] == 0]
# Create a cross-tabulation (confusion matrix-like table)
confusion_matrix = pd.crosstab(index=filtered_df['TSatisf_night'],
columns=filtered_df['TSatisf_day'],
rownames=['TSatisf_night'], colnames=['TSatisf_day'])
# Print the confusion matrix-like table
print(confusion_matrix)
# List of filter conditions
filters = ["cluster_kmeans", "cluster_hierarchical"]
# Create subplots
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
# Loop through filters and create subplots
for i, filter_col in enumerate(filters):
ax = axes[i]
# Apply filter condition and plot
data_subset = merge[merge[filter_col] == 1]
sns.histplot(merge[merge[filter_col] == 1], x="TSatisf_day", y="TSatisf_night", legend=False, discrete=(True, True), ax=ax)
ticks = range(-3, 4)
ax.set_xticks(ticks)
ax.set_yticks(ticks)
ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)
# Set subplot title
if filter_col == "cluster_kmeans":
ax.set_title("K-Means")
# Add text in the top left corner
ax.text(-3.8, 3.8, "'Uncomfortable' cluster (n=97)", fontsize=10, ha='left', va='top', color='black')
elif filter_col == "cluster_hierarchical":
ax.set_title("Hierarchical Clustering")
# Add text in the top left corner
ax.text(-3.8, 3.8, "'Uncomfortable' cluster (n=113)", fontsize=10, ha='left', va='top', color='black')
# Set x and y axis titles
ax.set_xlabel("TSATIS_day")
ax.set_ylabel("TSATIS_night")
# Add frequency labels using annotate
for (x, y), count in data_subset.groupby(["TSatisf_day", "TSatisf_night"]).size().items():
ax.annotate(count, (x, y), textcoords="offset points", xytext=(0, 3), ha='center', fontsize=10, color='white')
# Adjust layout and show the plot
plt.tight_layout()
plt.savefig("TSatisf_HTD.png", dpi=300) # Save the plot as PNG with 300dpi
plt.show()
# List of filter conditions
filters = [ "cluster_kmeans", "cluster_hierarchical"]
# Create subplots
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
# Loop through filters and create subplots
for i, filter_col in enumerate(filters):
ax = axes[i]
# Apply filter condition and plot
data_subset = merge[merge[filter_col] == 0]
sns.histplot(merge[merge[filter_col] == 0], x="TSatisf_day", y="TSatisf_night", legend=False, discrete=(True, True), ax=ax)
ticks = range(-3, 4)
ax.set_xticks(ticks)
ax.set_yticks(ticks)
ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)
# Set subplot title
if filter_col == "cluster_kmeans":
ax.set_title("K-Means")
# Add text in the top left corner
ax.text(-3.8, 3.8, "'Comfortable' cluster (n=92)", fontsize=10, ha='left', va='top', color='black')
elif filter_col == "cluster_hierarchical":
ax.set_title("Hierarchical Clustering")
# Add text in the top left corner
ax.text(-3.8, 3.8, "'Comfortable' cluster (n=76)", fontsize=10, ha='left', va='top', color='black')
# Set x and y axis titles
ax.set_xlabel("TSATIS_day")
ax.set_ylabel("TSATIS_night")
# Add frequency labels using annotate
for (x, y), count in data_subset.groupby(["TSatisf_day", "TSatisf_night"]).size().items():
ax.annotate(count, (x, y), textcoords="offset points", xytext=(0, 3), ha='center', fontsize=10, color='white')
# Adjust layout and show the plot
plt.tight_layout()
plt.savefig("TSatisf_LTD.png", dpi=300) # Save the plot as PNG with 300dpi
plt.show()
"""##### **Crosstab Preference**
**K-Means**
"""
# Create a DataFrame containing the relevant columns
df_subset = merge[['TPref_day', 'TPref_night', 'cluster_kmeans']]
# Filter by the desired cluster_kmeans value (replace 'desired_cluster_value' with the actual value you want to filter)
filtered_df = df_subset[df_subset['cluster_kmeans'] == 1]
# Create a cross-tabulation (confusion matrix-like table)
confusion_matrix = pd.crosstab(index=filtered_df['TPref_night'],
columns=filtered_df['TPref_day'],
rownames=['TPref_night'], colnames=['TPref_day'])
# Print the confusion matrix-like table
print(confusion_matrix)
# Create a DataFrame containing the relevant columns
df_subset = merge[['TPref_day', 'TPref_night', 'cluster_kmeans']]
# Filter by the desired cluster_kmeans value (replace 'desired_cluster_value' with the actual value you want to filter)
filtered_df = df_subset[df_subset['cluster_kmeans'] == 0]
# Create a cross-tabulation (confusion matrix-like table)
confusion_matrix = pd.crosstab(index=filtered_df['TPref_night'],
columns=filtered_df['TPref_day'],
rownames=['TPref_night'], colnames=['TPref_day'])
# Print the confusion matrix-like table
print(confusion_matrix)
"""**Hierarchical**"""
# Create a DataFrame containing the relevant columns
df_subset = merge[['TPref_day', 'TPref_night', 'cluster_hierarchical']]
# Filter by the desired cluster_hierarchical value (replace 'desired_cluster_value' with the actual value you want to filter)
filtered_df = df_subset[df_subset['cluster_hierarchical'] == 1]
# Create a cross-tabulation (confusion matrix-like table)
confusion_matrix = pd.crosstab(index=filtered_df['TPref_night'],
columns=filtered_df['TPref_day'],
rownames=['TPref_night'], colnames=['TPref_day'])
# Print the confusion matrix-like table
print(confusion_matrix)
# Create a DataFrame containing the relevant columns
df_subset = merge[['TPref_day', 'TPref_night', 'cluster_hierarchical']]
# Filter by the desired cluster_hierarchical value (replace 'desired_cluster_value' with the actual value you want to filter)
filtered_df = df_subset[df_subset['cluster_hierarchical'] == 0]
# Create a cross-tabulation (confusion matrix-like table)
confusion_matrix = pd.crosstab(index=filtered_df['TPref_night'],
columns=filtered_df['TPref_day'],
rownames=['TPref_night'], colnames=['TPref_day'])
# Print the confusion matrix-like table
print(confusion_matrix)
# List of filter conditions
filters = ["cluster_kmeans", "cluster_hierarchical"]
# Create subplots
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
# Loop through filters and create subplots
for i, filter_col in enumerate(filters):
ax = axes[i]
# Apply filter condition and plot
data_subset = merge[merge[filter_col] == 1]
sns.histplot(merge[merge[filter_col] == 1], x="TPref_day", y="TPref_night", legend=False, discrete=(True, True), ax=ax)
ticks = range(-1, 2)
ax.set_xticks(ticks)
ax.set_yticks(ticks)
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
# Set subplot title
if filter_col == "cluster_kmeans":
ax.set_title("K-Means")
# Add text in the top left corner
ax.text(-1.8, 1.8, "'Uncomfortable' cluster (n=97)", fontsize=10, ha='left', va='top', color='black')
elif filter_col == "cluster_hierarchical":
ax.set_title("Hierarchical Clustering")
# Add text in the top left corner
ax.text(-1.8, 1.8, "'Uncomfortable' cluster (n=113)", fontsize=10, ha='left', va='top', color='black')
# Set x and y axis titles
ax.set_xlabel("TPREF_day")
ax.set_ylabel("TPREF_night")
# Add frequency labels using annotate
for (x, y), count in data_subset.groupby(["TPref_day", "TPref_night"]).size().items():
ax.annotate(count, (x, y), textcoords="offset points", xytext=(0, 3), ha='center', fontsize=10, color='white')
# Adjust layout and show the plot
plt.tight_layout()
plt.savefig("TPref_HTD.png", dpi=300) # Save the plot as PNG with 300dpi
plt.show()
# List of filter conditions
filters = ["cluster_kmeans", "cluster_hierarchical"]
# Create subplots
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
# Loop through filters and create subplots
for i, filter_col in enumerate(filters):
ax = axes[i]
# Apply filter condition and plot
data_subset = merge[merge[filter_col] == 0]
sns.histplot(merge[merge[filter_col] == 0], x="TPref_day", y="TPref_night", legend=False, discrete=(True, True), ax=ax)
ticks = range(-1, 2)
ax.set_xticks(ticks)
ax.set_yticks(ticks)
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
# Set subplot title
if filter_col == "cluster_kmeans":
ax.set_title("K-Means")
# Add text in the top left corner
ax.text(-1.8, 1.8, "'Comfortable' cluster (n=92)", fontsize=10, ha='left', va='top', color='black')
elif filter_col == "cluster_hierarchical":
ax.set_title("Hierarchical Clustering")
# Add text in the top left corner
ax.text(-1.8, 1.8, "'Comfortable' cluster (n=76)", fontsize=10, ha='left', va='top', color='black')
# Set x and y axis titles
ax.set_xlabel("TPREF_day")
ax.set_ylabel("TPREF_night")
# Add frequency labels using annotate
for (x, y), count in data_subset.groupby(["TPref_day", "TPref_night"]).size().items():
ax.annotate(count, (x, y), textcoords="offset points", xytext=(0, 3), ha='center', fontsize=10, color='white')
# Adjust layout and show the plot
plt.tight_layout()
plt.savefig("TPref_LTD.png", dpi=300) # Save the plot as PNG with 300dpi
plt.show()
"""## **Research sub-question 2**
"""
import statsmodels.api as sm
import statsmodels.formula.api as smf
"""### **Replace extreme values with mean values**
"""
sns.boxplot(data=merge,y="ThermostatTemp", fill=False, gap= 0.1, fliersize = 3)
plt.show()
temp_hw_true = merge[merge["hw_True"] == True]["ThermostatTemp"].mean()
temp_hw_true
temp_hw_false = merge[merge["hw_True"] == False]["ThermostatTemp"].mean()
temp_hw_false
merge.loc[merge['ThermostatTemp'] == 36.0, 'ThermostatTemp'] = temp_hw_true
merge.loc[merge['ThermostatTemp'] == 35.0, 'ThermostatTemp'] = temp_hw_false
merge[merge["ThermostatTemp"] >= 35][["hw_True","ID","cluster_kmeans","ThermostatTemp","meanTout","TSen_day"]]
"""### **Discomfort - KMeans**
"""
f, ax = plt.subplots(figsize=(5, 5))
# Set the order for legend labels
hue_order = ['Comfortable', 'Uncomfortable']
sns.boxplot(data=merge, x="hw_True", y="ThermostatTemp", hue="cluster_kmeans", fill=False, gap= 0.1, fliersize = 3)
# Add labels to the axis and plot
ax.set(xlabel="Period", ylabel="Indoor temperature (ºC, thermostat)")
plt.xticks([0, 1], ['Non-HW', 'HW'])
# Get the legend object
legend = ax.legend()
# Set legend title
legend.set_title("Cluster")
# Set legend labels
for i, label in enumerate(hue_order):
legend.get_texts()[i].set_text(label)
# Add "K-means" annotation outside the plot
plt.text(1, 1.05, "K-means", fontsize=12, ha='right', va='top', transform=ax.transAxes)
plt.savefig("temp_kmeans.png", dpi=300) # Save the plot as PNG with 300dpi
plt.show()
night = (merge["Hour"] >= 23) | (merge["Hour"] < 7)
night.sum()
morning = (merge["Hour"] >= 7) & (merge["Hour"] < 15)
morning.sum()
afternoon = (merge["Hour"] >= 15) & (merge["Hour"] < 23)
afternoon.sum()
merge["cte_23_7h_True"] = night
merge["cte_7_15h_True"] = morning
merge["cte_15_23h_True"] = afternoon
# Define a function to determine the time of the day
def get_time_of_day(row):
if row['cte_23_7h_True']:
return '23:00 - 7:00 h'
elif row['cte_7_15h_True']:
return '7:00 - 15:00 h'
elif row['cte_15_23h_True']:
return '15:00 - 23:00 h'
else:
return 'unknown' # Handle any case where none of the conditions are True
# Apply the function to each row of the DataFrame
merge['time_of_the_day'] = merge.apply(get_time_of_day, axis=1)
# Calculate the overall average temperature for each cluster_kmeans category