-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBig_Data_Analytics.ipynb.orig
1699 lines (1699 loc) · 56.3 KB
/
Big_Data_Analytics.ipynb.orig
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
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "rn-_KJ3eqxVy"
},
"source": [
"# The Woof Factor in Zürich\n",
"---\n",
"\n",
"Through use of data freely available from *Stadt Zürich Open Data*, we analyse dogs registered in Zurich and combine this data with other information available about the districts (kreis) that make up Zurich. A model is developed in which we ...\n",
"\n",
"*Project Group 23:* Corey Bothwell, Nicoletta Farabullini, Jacob Gelling, Andris Prokofjevs, Qasim Warraich"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "HYonn-cUpjzv"
},
"source": [
"# Libraries\n",
"---\n",
"\n",
"The required packages must first be installed. On Linux, this requires the system to have Curl (for communicating with the Yandex Translate API) and GDAL (for generating the map vizualisations) installed."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 625
},
"colab_type": "code",
"id": "8uvzQkZ1pf5R",
"outputId": "0102d1c9-c4a0-4188-cef8-abae10a9b2d0",
"scrolled": false
},
"outputs": [],
"source": [
"install.packages(\"readr\")\n",
"install.packages(\"data.table\")\n",
"install.packages(\"RYandexTranslate\")\n",
"install.packages(\"plyr\")\n",
"install.packages(\"dplyr\")\n",
"install.packages(\"stringr\")\n",
"install.packages(\"class\")\n",
"install.packages(\"e1071\")\n",
"install.packages(\"ggplot2\")\n",
"install.packages(\"reshape2\")\n",
"install.packages(\"leaflet\")\n",
"install.packages(\"rgdal\")\n",
"install.packages(\"stringi\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Libraries used throughout the analysis are imported here."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"library(readr)\n",
"library(data.table)\n",
"library(RYandexTranslate)\n",
"library(plyr)\n",
"library(dplyr)\n",
"library(stringr)\n",
"library(class)\n",
"library(e1071)\n",
"library(ggplot2)\n",
"library(reshape2)\n",
"library(leaflet)\n",
"library(rgdal)\n",
"library(stringi)"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "fxWlXtTDj5EE"
},
"source": [
"# Data Cleaning\n",
"---\n",
"\n",
"This section is used for importing the raw data from CSV files into R data tables. Appropriate data merging and cleaning is performed.\n",
"\n",
"Also performed is automatic translations from German to English for some of the column content that would otherwise be too laborious to do by hand."
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "NDSSGT4R4aca"
},
"source": [
"Rather than running data cleaning each time we run the notebook during development, which can be slow due to the Yandex Translate API, an R data image of the alreadly cleaned data provided with the Notebook file can be loaded instead by running the following block."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {},
"colab_type": "code",
"id": "DYmD8dDM4QoG"
},
"outputs": [],
"source": [
"load(\"dogs.Rdata\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "5BqJj3pYm1jr"
},
"source": [
"## Import Dog Data\n",
"\n",
"The dog registration data for 2020, for which the source is available at [Stadt Zürich Open Data](https://data.stadt-zuerich.ch/dataset/sid_stapo_hundebestand/resource/a05e2101-7997-4bb5-bed8-c5a61cfffdcf), is imported and converted to a R data table."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 510
},
"colab_type": "code",
"id": "ynxU6g3GnNLJ",
"outputId": "85b79030-11ba-41ef-83f2-2b51ad2d62db"
},
"outputs": [],
"source": [
"dogs2020 <- data.table(read_csv(\"data_sources/20200306_hundehalter.csv\"))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Data cleaning is now performed. Due to what is likely a typographical error, a dog with a district value of 8 is removed (non-existant stadtquartier).\n",
"\n",
"Data we are uninterested in and rows that are incomplete are also removed, however for the 2020 dog dataset we find that 0 rows are ommited."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Dog w. district \"8\", typographical error? We remove it.\n",
"dogs2020 <- dogs2020[(dogs2020$STADTQUARTIER!=8), ]\n",
"\n",
"# Removing unnececesary columns\n",
"dogs2020[, c(\"RASSE1_MISCHLING\", \"RASSE2\", \"RASSE2_MISCHLING\"):=NULL]\n",
"\n",
"# If a row has a NA entry in one of the cells, remove the entire row\n",
"dogs2020 <- na.omit(dogs2020)\n",
"# 0 rows ommited, still leave the code in place in case we change data basis."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Due to the international makeup of our team members, we translate the column names from German to English."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Rename columns\n",
"setnames(dogs2020,\n",
" old = c(\"HALTER_ID\", \"ALTER\", \"GESCHLECHT\", \"STADTQUARTIER\", \"STADTKREIS\", \"RASSE1\", \"RASSENTYP\", \"GEBURTSJAHR_HUND\", \"GESCHLECHT_HUND\", \"HUNDEFARBE\"),\n",
" new = c(\"OWNER_ID\", \"AGE\", \"SEX\", \"DISTRICT\", \"DISTRICT_BIG\", \"BREED\", \"BREED_TYPE\", \"YOB_DOG\", \"SEX_DOG\", \"COLOR_DOG\")\n",
" )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Because stadtquartier is a more granular district segmentation than stadtkreis, and not all datasets can be merged by stadtkreis, we used it instead. We found that it is hard to view on a map when the dataset does not contain normal district names, so we extract the district names from the wealth dataset."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Import district names\n",
"district_names <- data.table(read_csv(\"data_sources/wir100od1004.csv\"))\n",
"district_names <- unique(district_names[, QuarSort, QuarLang])\n",
"\n",
"# Rename columns\n",
"setnames(district_names,\n",
" old = c(\"QuarSort\", \"QuarLang\"),\n",
" new = c(\"DISTRICT\", \"DISTRICT_NAME\")\n",
" )\n",
"\n",
"dogs2020 <- merge(dogs2020, district_names , by = \"DISTRICT\", all.x = T)\n",
"\n",
"# Remove unused variable\n",
"rm(district_names)"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "qMHV7jrUm-E9"
},
"source": [
"## Import Wealth Data\n",
"\n",
"Next the wealth data, for which the source is available at [Stadt Zürich Open Data](https://data.stadt-zuerich.ch/dataset/fd_median_einkommen_quartier_od1003), is imported and converted to a R data table."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 221
},
"colab_type": "code",
"id": "mx1asHDGnDuh",
"outputId": "ba02bb01-58c5-4962-fa24-240d9a2304f1"
},
"outputs": [],
"source": [
"wealth <- data.table(read_csv(\"data_sources/wir100od1004.csv\"))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The latest data from this source is for 2017, so we select only this wealth data, store the average and aggregate the data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# We don't have data for 2020, the freshest data is for 2017\n",
"wealth <- wealth[SteuerJahr == 2017,]\n",
"\n",
"# Create a new column to store the average\n",
"wealth[, wealth50 := SteuerVermoegen_p50]\n",
"\n",
"# Replace the family values in this column with same divided by 2 for normalization\n",
"wealth$wealth50[wealth$SteuerTarifSort == 1] <- wealth$wealth50[wealth$SteuerTarifSort == 1]/2\n",
"\n",
"# Aggregate data for family status\n",
"# new table = old table, select mean of wealth50 (ignore NA), aggregate it by quartal\n",
"wealth_merge <- wealth[,mean(wealth50, na.rm = T), by=QuarSort]\n",
"\n",
"# Leaving only quartals that have dogs in them\n",
"wealth_merge <- wealth_merge[wealth_merge$QuarSort %in% dogs2020$DISTRICT]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We again translate the column names from German to English and then merge the data with the dogs data table."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Rename columns\n",
"setnames(wealth_merge,\n",
" old = c(\"V1\", \"QuarSort\"),\n",
" new = c(\"WEALTH_T_CHF\", \"DISTRICT\")\n",
" )\n",
"\n",
"# Merge wealth into dogs dataset\n",
"dogs2020 <- merge(dogs2020, wealth_merge, by = \"DISTRICT\", all.x = T)\n",
"# ATTENTION! FYI: not all districts have wealth values! \n",
"\n",
"# Remove unused variables\n",
"rm(wealth, wealth_merge)"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "e9zuqYq6nW-J"
},
"source": [
"## Import Income Data\n",
"\n",
"Next the income data, for which the source is available at [Stadt Zürich Open Data](https://data.stadt-zuerich.ch/dataset/fd_median_vermoegen_quartier_od1004), is imported and converted to a R data table."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 221
},
"colab_type": "code",
"id": "KGQ9qrWsnZoK",
"outputId": "d36d841c-4300-4d53-b62c-d56ffa5acd7a"
},
"outputs": [],
"source": [
"income <- data.table(read_csv(\"data_sources/wir100od1003.csv\"))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Again, the latest data from this source is for 2017, so we select only this income data, store the average and aggregate the data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# We don't have data for 2020, the freshest data is for 2017\n",
"income <- income[SteuerJahr == 2017,]\n",
"\n",
"# Create a new column to store the average\n",
"income[, incomep50 := SteuerEInkommen_p50]\n",
"\n",
"# Replace the family values in this column with same divided by 2 for normalization\n",
"income$incomep50[income$SteuerTarifSort == 1] <- income$incomep50[income$SteuerTarifSort == 1]/2\n",
"\n",
"# Aggregate data for family status\n",
"# new table = old table, select mean of incomep50 (ignore NA), aggregate it by quartal\n",
"income_merge <- income[,mean(incomep50, na.rm = T), by=QuarSort]\n",
"\n",
"# Leaving only quartals that have dogs in them\n",
"income_merge <- income_merge[income_merge$QuarSort %in% dogs2020$DISTRICT]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We again translate the column names from German to English and then merge the data with the dogs data table."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Rename columns\n",
"setnames(income_merge,\n",
" old = c(\"V1\", \"QuarSort\"),\n",
" new = c(\"INCOME_T_CHF\", \"DISTRICT\")\n",
" )\n",
"\n",
"# Merge income into dogs dataset\n",
"dogs2020 <- merge(dogs2020, income_merge, by = \"DISTRICT\", all.x = T)\n",
"# ATTENTION! FYI: not all districts have income values! \n",
"\n",
"# Remove unused variables\n",
"rm(income, income_merge)"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "I24YVJ_VncAY"
},
"source": [
"## Import Education Data\n",
"\n",
"The import of education data is straightforward, requiring only a long to wide reshape of the data. The data source is available at [Stadt Zürich Open Data](https://data.stadt-zuerich.ch/dataset/bfs_bev_bildungsstand_statquartier_seit1970_od1012)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 187
},
"colab_type": "code",
"id": "4NssSsYpneo0",
"outputId": "105009b9-96f9-4f5a-b71c-18c1cd01ad35"
},
"outputs": [],
"source": [
"education <- data.table(read_csv(\"data_sources/bil101od1012 (2).csv\"))\n",
"\n",
"# Long to wide education reshape\n",
"education <- dcast(education, RaumSort ~ Bildungsstand, value.var = \"AntBev\")\n",
"\n",
"# Rename columns\n",
"setnames(education,\n",
" old = c(\"RaumSort\", \"Obligatorische Schule\", \"Sekundarstufe II\", \"Tertiärstufe\"),\n",
" new = c(\"DISTRICT\", \"BASIC_SCHOOL_PERCENTAGE\", \"GYMNASIUM_PERCENTAGE\", \"UNIVERSITY_PERCENTAGE\")\n",
" )\n",
"\n",
"# Merge income into dogs dataset\n",
"dogs2020 <- merge(dogs2020, education, by = \"DISTRICT\", all.x = T)\n",
"\n",
"# Remove unused variable\n",
"rm(education)"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "aHUmAB4pnjK5"
},
"source": [
"## Import Home Type Data\n",
"\n",
"Home type data, such as number of resident buildings in a district, is now imported. The data source is available at [Stadt Zürich Open Data](https://data.stadt-zuerich.ch/dataset/bau_best_geb_whg_bev_gebaeudeart_quartier_seit2008/resource/3850add1-264c-4993-98cd-d8a9ba87ee25). 2019 is the latest data available. Each building type is summed and a long to wide reshape of the data is performed."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 374
},
"colab_type": "code",
"id": "C80_N4ZgnmDm",
"outputId": "45d43f21-1696-4bca-f310-6e27c77ed11b"
},
"outputs": [],
"source": [
"home_type <- data.table(read_csv(\"data_sources/bau_best_geb_whg_bev_gebaeudeart_quartier_seit2008.csv\")) \n",
"\n",
"# We don't have data for 2020, the freshest data is for 2019\n",
"home_type <- home_type[Jahr == 2019,]\n",
"\n",
"# Count the sum of every type of building\n",
"home_type <- home_type[, sum(AnzGeb), by = list(QuarSort,GbdArtPubName)]\n",
"\n",
"# Rename columns\n",
"setnames(home_type,\n",
" old = c(\"QuarSort\", \"GbdArtPubName\", \"V1\"), \n",
" new = c(\"DISTRICT\", \"Hometype\", \"Number_homes\")\n",
" )\n",
"\n",
"# Long to wide hometype reshape\n",
"home_type <- data.table::dcast(home_type, DISTRICT ~ Hometype, value.var = \"Number_homes\")\n",
"\n",
"# Translate hometype columns\n",
"setnames(home_type,\n",
" old = c(\"Produktions- und Lagergebäude\", \"Mehrfamilienhäuser\", \"Einfamilienhäuser\", \"Infrastrukturgebäude\", \"Kleingebäude\", \"Kommerzielle Gebäude\", \"Spezielle Wohngebäude\"), \n",
" new = c(\"FACTORIES_AND_WAREHOUSES\", \"APARTMENTS\", \"SINGLE_FAMILY_HOMES\", \"INFRASTRUCTURE_BUILDINGS\", \"SMALL_BUILDINGS\", \"COMMERCIAL_BUILDINGS\", \"SPECIAL_ACCOMODATION\")\n",
" )\n",
"\n",
"# Remove unnececesary column\n",
"home_type[, Unbekannt:=NULL]\n",
"\n",
"# Merge home types into dogs dataset\n",
"dogs2020 <- merge(dogs2020, home_type, by = \"DISTRICT\", all.x = T)\n",
"\n",
"# Remove unused variable\n",
"rm(home_type)"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "55CKOQRFnrCr"
},
"source": [
"## Import Population Data\n",
"\n",
"Next population data is imported. The data source is available at [Stadt Zürich Open Data](https://www.stadt-zuerich.ch/prd/de/index/statistik/themen/bevoelkerung/bevoelkerungsentwicklung/kreise-und-quartiere.html#daten). The source CSV file is a little messy, so some additional data cleaning is required. When importing, the first 8 lines are skipped for the parser to reach the CSV header. As one of the columns are unlabelled, a warning is produced."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 204
},
"colab_type": "code",
"id": "RLQ9mG4vntd5",
"outputId": "30696c37-6fa7-47ea-d850-ef27c42ab3b4"
},
"outputs": [],
"source": [
"# Warning shown due to formatting of souce CSV header, can be ignored\n",
"pop_per_district <- data.table(read_csv(\"data_sources/2019-Table_1.csv\", col_names = TRUE, skip = 8))\n",
"\n",
"# Set column names\n",
"setnames(pop_per_district, old = \"X1\", new = \"DISTRICT_NAME\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The data also contains hidden characters acting as whitespace which the standard regex matching pattern ```\\\\s``` does not always catch. For this reason we remove all non-numeric characters with a regex function."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# This Reg-Ex Matching Function Removes all Whitespaces and not only conventional ones (bad data design)\n",
"pop_per_district[,2:5] <- data.table(apply(pop_per_district[,2:5], 2, function(x) gsub('[^0-9.]', '', x)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As normal, we continue by merging the population data into the dogs data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Join by district name (perfect match with no NAs)\n",
"dogs2020 <- merge(dogs2020, pop_per_district, by = \"DISTRICT_NAME\", all.x = T)\n",
"\n",
"# Remove unused variable\n",
"rm(pop_per_district)\n",
"\n",
"# Rename columns\n",
"setnames(dogs2020,\n",
" old = c(\"Total\", \"Schweizer/-innen\", \"Ausländer/-innen\", \"Anteil ausländische\\nBevölkerung (%)\"),\n",
" new = c(\"TOTAL_POPULATION\", \"SWISS_POPULATION\", \"FOREIGN_POPULATION\", \"FOREIGN_POPULATION_PERCENTAGE\")\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The columns are then cast as numeric data types for use in mathematical operations later in the analysis."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Cast columns as numeric\n",
"dogs2020$TOTAL_POPULATION <- as.numeric(dogs2020$TOTAL_POPULATION)\n",
"dogs2020$SWISS_POPULATION <- as.numeric(dogs2020$SWISS_POPULATION)\n",
"dogs2020$FOREIGN_POPULATION <- as.numeric(dogs2020$FOREIGN_POPULATION )\n",
"dogs2020$FOREIGN_POPULATION_PERCENTAGE <- as.numeric(dogs2020$FOREIGN_POPULATION_PERCENTAGE)"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "nvMuam6BnzHX"
},
"source": [
"## Translate Dataframes\n",
"Using the Yandex Translate API, values in columns are automatically translated from German to English."
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "3UqXvple8DvM"
},
"source": [
"Firstly the Yandex translate package is fixed, as per the [solution found on GitHub](https://github.com/mukul13/RYandexTranslate/issues/2)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {},
"colab_type": "code",
"id": "7Wt8fMK68L8c"
},
"outputs": [],
"source": [
"translate = function (api_key, text = \"\", lang = \"\") \n",
"{\n",
" url = \"https://translate.yandex.net/api/v1.5/tr.json/translate?\"\n",
" url = paste(url, \"key=\", api_key, sep = \"\")\n",
" if (text != \"\") {\n",
" url = paste(url, \"&text=\", text, sep = \"\")\n",
" }\n",
" if (lang != \"\") {\n",
" url = paste(url, \"&lang=\", lang, sep = \"\")\n",
" }\n",
" url = gsub(pattern = \" \", replacement = \"%20\", x = url)\n",
" d = RCurl::getURL(url, ssl.verifyhost = 0L, ssl.verifypeer = 0L, .encoding = \"UTF-8\")\n",
" d = jsonlite::fromJSON(d)\n",
" d$code = NULL # Remove unused variables\n",
" d\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "rsjgeXUK8Yhq"
},
"source": [
"As the Yandex Translate API requires an API key, we define this here. It is connected to Andris' personal account, so please do not disclose it elsewhere."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Andris' personal Yandex Translate API key\n",
"# PLEASE DO NOT DISCLOSE ELSEWHERE\n",
"api_key <- \"trnsl.1.1.20200515T134653Z.f9fb709ac3e94036.783aefa609692b463a79b5827d5c0e7f2d037a8c\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next we define the list of columns for which we want to translate their contents."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"column_list <- c(\"BREED\", \"COLOR_DOG\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We then loop through columns that we wish to translate and pass these to the Yandex Translate API. As translation can be slow, we pass only unique values from the columns, preventing a translation call for every row, even if the value was translated before. The output is saved to the dogs data table."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 1000
},
"colab_type": "code",
"id": "NQfpAlpIn1xI",
"outputId": "1eff4904-573a-4253-ce95-6ed13b2af689"
},
"outputs": [],
"source": [
"# Loop through columns in column_list\n",
"for (column_names in column_list) {\n",
" # Get all unique values in the coresponding column\n",
" unique_values <- unique(dogs2020[, get(column_names)])\n",
" \n",
" # Loop through unique values to be translated\n",
" for (unique_num in 1:length(unique_values)) {\n",
" \n",
" # Print progress for debugging\n",
" print(column_names)\n",
" print(paste(unique_num, \" out of \", length(unique_values)))\n",
" \n",
" # data.table synthaxis code\n",
" dogs2020[\n",
" # Select all rows where value is equal to current unique value\n",
" # left part \"get\" is needed in order to use dynamic column_names.\n",
" dogs2020[,get(column_names)] == unique_values[unique_num],\n",
" # Replace old value with translated one.\n",
" # Left part is \"eval\" is needed in order to use dynamic column_names.\n",
" # Right part is a Yandex Translate function, providing api_key and text to be translated.\n",
" eval(column_names) := translate(api_key, text=stringi::stri_unescape_unicode(unique_values[unique_num]),\n",
" # Specify language pair and translation direction.\n",
" lang=\"de-en\"\n",
" # Extract only output text from the return given by Yandex.\n",
" )$text]\n",
" \n",
" }\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We manually replace sex and sex_dog variable to match the English language conventions for sex abbreviations."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"dogs2020[SEX == \"w\", SEX := \"f\"]\n",
"dogs2020[SEX_DOG == \"w\", SEX_DOG := \"f\"]"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "HfomTPUf4s2X"
},
"source": [
"## Save RData Image\n",
"An R data image is saved here so that instead of running the entire data cleaning code block again in future runs, the image can be loaded."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {},
"colab_type": "code",
"id": "l0-a80wa43XP"
},
"outputs": [],
"source": [
"save.image(\"dogs.Rdata\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "XlVYqq67tNF1"
},
"source": [
"## Backup Output\n",
"Save a backup of the dogs data set in another variable."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {},
"colab_type": "code",
"id": "KdoFnYpZtVpH"
},
"outputs": [],
"source": [
"dogs2020_backup = copy(dogs2020)"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "d1-vswSaoGvZ"
},
"source": [
"# Investigation\n",
"---\n",
"This section of code explores predicting dog breed type."
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "5qnDRGFdpwjR"
},
"source": [
"## Model Preparation"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 51
},
"colab_type": "code",
"id": "VET_xDP0p0JH",
"outputId": "10dce23d-7930-47b9-afe8-6677b2181bcc"
},
"outputs": [],
"source": [
"# color recode to make bigger chunks\n",
"# doublecolored dogs will be recoded as singlecolored with first color taken as main.\n",
"a <- str_split(dogs2020$COLOR_DOG, \"/\")\n",
"new_colors <- a[[1]][1]\n",
"# clear variable i from the enviroment\n",
"rm(i)\n",
"for (i in 2:length(a)) {\n",
" new_colors <- append(new_colors, a[[i]][1])\n",
"}\n",
"dogs2020$COLOR_DOG <- new_colors\n",
"\n",
"# refactoring text attributes to numeric, so that knn can work with it.\n",
"dogs2020$DISTRICT_NAME <- as.numeric(as.factor(dogs2020$DISTRICT_NAME))\n",
"dogs2020$AGE <- as.numeric(as.factor(dogs2020$AGE))\n",
"dogs2020$SEX <- as.numeric(as.factor(dogs2020$SEX))\n",
"dogs2020$SEX_DOG <- as.numeric(as.factor(dogs2020$SEX_DOG))\n",
"dogs2020$COLOR_DOG <- as.numeric(as.factor(dogs2020$COLOR_DOG))\n",
"dogs2020$YOB_DOG <- as.numeric(as.factor(dogs2020$YOB_DOG))\n",
"\n",
"#saving labels in order to see later what numbers represent what breedtypes\n",
"breedtype_labels <- as.factor(dogs2020$BREED_TYPE)\n",
"dogs2020$BREED_TYPE <- as.numeric(as.factor(dogs2020$BREED_TYPE))\n",
"\n",
"#saving labels in order to see later what numbers represent what breeds\n",
"breed_labels <- as.factor(dogs2020$BREED)\n",
"dogs2020$BREED <- as.numeric(as.factor(dogs2020$BREED))"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "JlCqPfaRp_Xa"
},
"source": [
"## Naive Approach"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 1000
},
"colab_type": "code",
"id": "ZQqHvoD5qCKc",
"outputId": "0c234121-6626-4423-af11-999789995ed8"
},
"outputs": [],
"source": [
"# data separation, so that we have test and training group\n",
"dat.d <- sample(1:nrow(dogs2020),size=nrow(dogs2020)*0.7,replace = FALSE) #random selection of 70% data.\n",
"\n",
"# now we tried differrent input settings in an attempt to find optimal one\n",
"\n",
"# train.dogs <- dogs2020[dat.d, c(\"DISTRICT_NAME\", \"YOB_DOG\", \"AGE\", \"SEX\", \"SEX_DOG\", \"COLOR_DOG\")] # 70% training data\n",
"# test.dogs <- dogs2020[-dat.d,c(\"DISTRICT_NAME\", \"YOB_DOG\", \"AGE\", \"SEX\", \"SEX_DOG\", \"COLOR_DOG\")] # remaining 30% test data\n",
"\n",
"# train.dogs <- dogs2020[dat.d, c(\"DISTRICT_NAME\", \"YOB_DOG\", \"AGE\", \"SEX\", \"SEX_DOG\")] # 70% training data\n",
"# test.dogs <- dogs2020[-dat.d,c(\"DISTRICT_NAME\", \"YOB_DOG\", \"AGE\", \"SEX\", \"SEX_DOG\")] # remaining 30% test data\n",
"\n",
"# train.dogs <- dogs2020[dat.d, c(\"COLOR_DOG\")] # 70% training data\n",
"# test.dogs <- dogs2020[-dat.d,c(\"COLOR_DOG\")] # remaining 30% test data\n",
"\n",
"# this is the only setting where we are not \"cheating\" by using dog associated attributes\n",
"train.dogs <- dogs2020[dat.d, c(\"DISTRICT_NAME\", \"AGE\", \"SEX\")] # 70% training data\n",
"test.dogs <- dogs2020[-dat.d,c(\"DISTRICT_NAME\", \"AGE\", \"SEX\")] # remaining 30% test data\n",
"\n",
"train.dogs_labels <- dogs2020[dat.d,BREED]\n",
"test.dogs_labels <-dogs2020[-dat.d,BREED]\n",
"\n",
"# train.dogs_labels <- dogs2020[dat.d,group]\n",
"# test.dogs_labels <-dogs2020[-dat.d,group]\n",
"\n",
"\n",
"#aprox k value\n",
"k_value <- sqrt(nrow(dogs2020))\n",
"\n",
"knn.test <- knn(train=train.dogs, test=test.dogs, cl=train.dogs_labels, k=k_value)\n",
"\n",
"ACC.test <- 100 * sum(test.dogs_labels == knn.test)/NROW(test.dogs_labels)\n",
"\n",
"table(knn.test ,test.dogs_labels)\n",
"\n",
"ACC.test\n",
"\n",
"# accuracy of direct prediction is 9,22%"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "ZPZgLDmuqL94"
},
"source": [
"## Lets try separating dataset and predict breed type at first, smaller chunks may lead to more accuracy"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# and try knn on breed directly now\n",
"rm(i)\n",
"results <- 0\n",
"for (i in 1:length(unique(test.dogs_labels)))\n",
"{\n",
" if (any(train.dogs$PREDICTED_BREED_TYPE == i) == F) {\n",
" next()\n",
" }\n",
" \n",
" train.dogs_labels <- dogs2020[dat.d,BREED]\n",
" test.dogs_labels <- dogs2020[-dat.d,BREED]\n",
" \n",
" knn.test <- knn(train=train.dogs[train.dogs$PREDICTED_BREED_TYPE == i], \n",
" test=test.dogs[test.dogs$PREDICTED_BREED_TYPE == i], \n",
" cl=train.dogs_labels[train.dogs$PREDICTED_BREED_TYPE == i], k=k_value)\n",
" \n",
" ACC.test <- 100 *\n",
" sum(test.dogs_labels[test.dogs$PREDICTED_BREED_TYPE == i] == knn.test)/\n",
" NROW(test.dogs_labels[test.dogs$PREDICTED_BREED_TYPE == i])\n",
" \n",
" table(knn.test ,test.dogs_labels[test.dogs$PREDICTED_BREED_TYPE == i])\n",
" \n",
" results[i] <- ACC.test\n",
" \n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# doesnt really help.\n",
"# weighted accuracy is (2305 * 9.32754880694143/100 + 6.38297872340426/100 * 47) / 2352\n",
"(length(test.dogs_labels[test.dogs$PREDICTED_BREED_TYPE == 1]) * results[1]/100 \n",
" + length(test.dogs_labels[test.dogs$PREDICTED_BREED_TYPE == 3]) * results[3]/100 ) / \n",
" (length(test.dogs_labels[test.dogs$PREDICTED_BREED_TYPE == 1]) + length(test.dogs_labels[test.dogs$PREDICTED_BREED_TYPE == 3]))\n",
"# = 0.09268707, which is not substantially better than approach without breed type grouping.\n",
"\n",
"\n",
"# reasonable would be to throw away every breed that comes less than 100 times.\n",
"# cause we clearly see that because we dont have more attributes on dog owner levels \n",
"# and more gradual data, we are becomming here just inference of distribution of dogs among the\n",
"# attributes we use.\n",
"# so to improve accuracy it makes sense to reduce the number of possible \"answers\"\n",
"\n",
"\n",
"# in order to test it, we have to calculate how many people own which breeds\n",
"# count how many people own every breed.\n",
"breed_filter <- data.table(aggregate(OWNER_ID ~ BREED, data = dogs2020, FUN = function(x){NROW(x)}))\n",
"\n",
"#renaming\n",
"setnames(breed_filter, old = c(\"OWNER_ID\")\n",