-
Notifications
You must be signed in to change notification settings - Fork 0
/
Machine Learning - Naive Bayes, Multiple Regression, Logistic Regression
1632 lines (1161 loc) · 64.7 KB
/
Machine Learning - Naive Bayes, Multiple Regression, Logistic Regression
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
---
title: "DA5030 - Practicum 2"
author: "Brian Gridley"
date: "November 2, 2018"
output: pdf_document
---
PROBLEM 1:
1) Download the data set Census Income Data for Adults along with its explanation. Note that the data file does not contain header names; you may wish to add those. The description of each column can be found in the data set explanation.
```{r}
# the data is located online, so I will download from the url
# and create a dataframe with the data ("census_income")
dataurl <- "http://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data"
download.file(url = dataurl, destfile = "adult.data")
census_income <- read.csv("adult.data", header = FALSE, sep = ",", strip.white = TRUE)
# the dataset is a csv but there is a space after each comma,
# so I removed the leading spaces with "strip.white = TRUE"
head(census_income)
# looks good
# now download the explanation
data_desc_url <- "http://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.names"
download.file(url = data_desc_url, destfile = "adult.names")
census_income_desc <- read.delim("adult.names", header = FALSE)
# Add column headers to the data, using the variable names in
# the "census_income_desc" file
names(census_income) <- c("age","workclass","fnlwgt","education",
"education-num","marital-status","occupation",
"relationship","race","sex","capital-gain",
"capital-loss","hours-per-week",
"native-country","income")
head(census_income)
# looks good!
```
2) Explore the data set as you see fit and that allows you to get a sense of the data and get comfortable with it. Is there distributional skew in any of the features? Is there a need to apply a transform?
```{r}
# look at the structure
str(census_income)
summary(census_income)
```
There are 32,561 records and 15 variables. There are a combination of numeric and factor variables. All of the categorical variables are already factors, so we won't need to convert any of them. I noticed in the structure that there are unknown values in three of the variables... "workclass", "occupation", and "native-country". They are marked with a "?". I'll want to remove these. I can also tell that the "capital-gain" and "capital-loss" variables are right-skewed because the 1st quartile, median, and 3rd quartile values are all 0 but there are a few larger values to the right because the mean and max are high.
However, since I will be applying the Naive Bayes algorithm using just the categorical variables here, I won't need to bother transforming any numeric variables. I will remove the unkown values from the data though, to have a cleaner liklihood table.
```{r}
# take care of the unknown values in the data. There are three
# variables that have unknowns present...
# workclass, occupation, and native-country
table(census_income$workclass)
# 1836 records
table(census_income$occupation)
# 1843 records
table(census_income$`native-country`)
# 583
# remove "?" data
library(tidyverse)
count(filter(census_income, workclass == "?" | occupation == "?" |
`native-country` == "?"))
# 2399 total records need to be removed
census_income_clean <- census_income %>%
filter(workclass != "?" & occupation != "?" & `native-country` != "?")
# check to make sure the correct amount was removed
count(census_income)
# 32561
count(census_income_clean)
# 30162
32561-30162
# 2399... thats correct
```
3) Create a frequency and then a likelihood table for the categorical features in the data set. Build your own Naive Bayes classifier for those features.
```{r}
str(census_income_clean)
```
Income is the binomial classification variable. Each of the predictor categorical variables are workclass (9 levels), education (16 levels), marital-status (7), occupation (15), relationship (6), race (5), sex (2), and native-country (42). This would be quite difficult to manage and make sure there are no mistakes if I created a frequency table all at once, so I will create a separate frequency table for each categorical variable to make things easier to comprehend. I will then combine them all into one total table and create a total liklihood table to use for the algorithm. I will do this manually rather than automate the process with a loop or function, so I can make sure all levels of each variable are examined carefully.
```{r}
# workclass
# frequency table
table(census_income_clean$workclass)
# first create a table with the counts of each class level, by income type
workclass_frequency_yes <- census_income_clean %>%
group_by(workclass, income) %>%
summarise(count = n())
workclass_frequency_yes
# noticed that there is no "Without-pay" for ">50K"
# so I will add this to the table with a count of 0
workclass_frequency_yes[nrow(workclass_frequency_yes) + 1,] =
list("Without-pay",">50K",0)
# create an object with the total counts for each income level
# which will be used to calculate the "no" counts for each level
total_counts <- workclass_frequency_yes %>%
group_by(income) %>%
summarise(count_total = sum(count))
# create another table with the same classes, to be filled in
# for the "No" columns in the table
workclass_frequency_No <- workclass_frequency_yes
# bring in the total counts to calculate the no's
workclass_frequency_No <- left_join(workclass_frequency_No,
total_counts, by = "income")
# calculate the "no" counts
workclass_frequency_No <- workclass_frequency_No %>%
mutate(count_no = count_total - count)
# now delete the "yes" and "total" count columns
workclass_frequency_No <- workclass_frequency_No %>%
select(1,2,5)
# rename the "count_no" column to just "count" for when we append to the "yes" table
colnames(workclass_frequency_No)[3] <- "count"
# add "_no" to the class type name
workclass_frequency_No$workclass <- paste(workclass_frequency_No$workclass,
"No", sep = "_")
# now add "_yes" to the yes table
workclass_frequency_yes$workclass <- paste(workclass_frequency_yes$workclass,
"Yes", sep = "_")
# append the "no" table to the "yes" table
workclass_frequency <- rbind(workclass_frequency_yes, workclass_frequency_No)
# need to adjust for instances where there is no occurrence
# will use laplace estimator of 1... add 1 to every count value in the
# table so a 0 doesn't occur and ruin our Naive Bayes calculations
workclass_frequency$count <- workclass_frequency$count + 1
# order the class name column alphabetically so when we spread it, the "yes"
# column is next to the "no" column for each class type
workclass_frequency <- arrange(workclass_frequency, workclass)
# now reorganize the table to be in proper format
workclass_frequency <- spread(workclass_frequency, key = "workclass", value = "count")
workclass_frequency
# great, the frequency table is all set now
```
That's the frequency table for the first categorical variable... now do the same for next one
```{r}
# education
# frequency table
table(census_income_clean$education)
# first create a table with the counts of each class level, by income type
education_frequency_yes <- census_income_clean %>%
group_by(education, income) %>%
summarise(count = n())
education_frequency_yes
# noticed that there is no "Preschool" for ">50K"
# so I will add this to the table with a count of 0
education_frequency_yes[nrow(education_frequency_yes) + 1,] =
list("Preschool",">50K",0)
# create another table with the same classes, to be filled in
# for the "No" columns in the table
education_frequency_No <- education_frequency_yes
# bring in the total counts to calculate the no's
education_frequency_No <- left_join(education_frequency_No,
total_counts, by = "income")
# calculate the "no" counts
education_frequency_No <- education_frequency_No %>%
mutate(count_no = count_total - count)
# now delete the "yes" and "total" count columns
education_frequency_No <- education_frequency_No %>%
select(1,2,5)
# rename the "count_no" column to just "count" for when we append to the "yes" table
colnames(education_frequency_No)[3] <- "count"
# add "_no" to the class type name
education_frequency_No$education <- paste(education_frequency_No$education,
"No", sep = "_")
# now add "_yes" to the yes table
education_frequency_yes$education <- paste(education_frequency_yes$education,
"Yes", sep = "_")
# append the "no" table to the "yes" table
education_frequency <- rbind(education_frequency_yes, education_frequency_No)
# use laplace estimator of 1... add 1 to every count value
education_frequency$count <- education_frequency$count + 1
# order the class name column alphabetically so when we spread it, the "yes"
# column is next to the "no" column for each class type
education_frequency <- arrange(education_frequency, education)
# now reorganize the table to be in proper format
education_frequency <- spread(education_frequency, key = "education", value = "count")
education_frequency
# great, the frequency table is all set now
```
Now, do the same for the next variable
```{r}
# marital-status
# frequency table
table(census_income_clean$`marital-status`)
# first create a table with the counts of each class level, by income type
marital_frequency_yes <- census_income_clean %>%
group_by(`marital-status`, income) %>%
summarise(count = n())
marital_frequency_yes
# There are no missing instances that need to be correctd for
# create another table with the same classes, to be filled in
# for the "No" columns in the table
marital_frequency_No <- marital_frequency_yes
# bring in the total counts to calculate the no's
marital_frequency_No <- left_join(marital_frequency_No,
total_counts, by = "income")
# calculate the "no" counts
marital_frequency_No <- marital_frequency_No %>%
mutate(count_no = count_total - count)
# now delete the "yes" and "total" count columns
marital_frequency_No <- marital_frequency_No %>%
select(1,2,5)
# rename the "count_no" column to just "count" for when we append to the "yes" table
colnames(marital_frequency_No)[3] <- "count"
# add "_no" to the class type name
marital_frequency_No$`marital-status` <- paste(marital_frequency_No$`marital-status`,
"No", sep = "_")
# now add "_yes" to the yes table
marital_frequency_yes$`marital-status` <- paste(marital_frequency_yes$`marital-status`,
"Yes", sep = "_")
# append the "no" table to the "yes" table
marital_frequency <- rbind(marital_frequency_yes, marital_frequency_No)
# although there are no instances with no occurrences
# I will still use laplace estimator of 1 to keep things consistent
marital_frequency$count <- marital_frequency$count + 1
# order the class name column alphabetically so when we spread it, the "yes"
# column is next to the "no" column for each class type
marital_frequency <- arrange(marital_frequency, `marital-status`)
# now reorganize the table to be in proper format
marital_frequency <- spread(marital_frequency, key = "marital-status", value = "count")
marital_frequency
# great, the frequency table is all set now
```
Next variable...
```{r}
# occupation
# frequency table
table(census_income_clean$occupation)
# first create a table with the counts of each class level, by income type
occupation_frequency_yes <- census_income_clean %>%
group_by(occupation, income) %>%
summarise(count = n())
occupation_frequency_yes
# There are no missing instances that need to be corrected for
# create another table with the same classes, to be filled in
# for the "No" columns in the table
occupation_frequency_No <- occupation_frequency_yes
# bring in the total counts to calculate the no's
occupation_frequency_No <- left_join(occupation_frequency_No,
total_counts, by = "income")
# calculate the "no" counts
occupation_frequency_No <- occupation_frequency_No %>%
mutate(count_no = count_total - count)
# now delete the "yes" and "total" count columns
occupation_frequency_No <- occupation_frequency_No %>%
select(1,2,5)
# rename the "count_no" column to just "count" for when we append to the "yes" table
colnames(occupation_frequency_No)[3] <- "count"
# add "_no" to the class type name
occupation_frequency_No$occupation <- paste(occupation_frequency_No$occupation,
"No", sep = "_")
# now add "_yes" to the yes table
occupation_frequency_yes$occupation <- paste(occupation_frequency_yes$occupation,
"Yes", sep = "_")
# append the "no" table to the "yes" table
occupation_frequency <- rbind(occupation_frequency_yes, occupation_frequency_No)
# although there are no instances with no occurrences
# I will still use laplace estimator of 1 to keep things consistent
occupation_frequency$count <- occupation_frequency$count + 1
# order the class name column alphabetically so when we spread it, the "yes"
# column is next to the "no" column for each class type
occupation_frequency <- arrange(occupation_frequency, occupation)
# now reorganize the table to be in proper format
occupation_frequency <- spread(occupation_frequency, key = "occupation", value = "count")
occupation_frequency
# great, the frequency table is all set now
```
Next variable...
```{r}
# relationship
# frequency table
table(census_income_clean$relationship)
# first create a table with the counts of each class level, by income type
relationship_frequency_yes <- census_income_clean %>%
group_by(relationship, income) %>%
summarise(count = n())
relationship_frequency_yes
# There are no missing instances that need to be corrected for
# create another table with the same classes, to be filled in
# for the "No" columns in the table
relationship_frequency_No <- relationship_frequency_yes
# bring in the total counts to calculate the no's
relationship_frequency_No <- left_join(relationship_frequency_No,
total_counts, by = "income")
# calculate the "no" counts
relationship_frequency_No <- relationship_frequency_No %>%
mutate(count_no = count_total - count)
# now delete the "yes" and "total" count columns
relationship_frequency_No <- relationship_frequency_No %>%
select(1,2,5)
# rename the "count_no" column to just "count" for when we append to the "yes" table
colnames(relationship_frequency_No)[3] <- "count"
# add "_no" to the class type name
relationship_frequency_No$relationship <- paste(relationship_frequency_No$relationship,
"No", sep = "_")
# now add "_yes" to the yes table
relationship_frequency_yes$relationship <- paste(relationship_frequency_yes$relationship,
"Yes", sep = "_")
# append the "no" table to the "yes" table
relationship_frequency <- rbind(relationship_frequency_yes, relationship_frequency_No)
# although there are no instances with no occurrences
# I will still use laplace estimator of 1 to keep things consistent
relationship_frequency$count <- relationship_frequency$count + 1
# order the class name column alphabetically so when we spread it, the "yes"
# column is next to the "no" column for each class type
relationship_frequency <- arrange(relationship_frequency, relationship)
# now reorganize the table to be in proper format
relationship_frequency <- spread(relationship_frequency, key = "relationship", value = "count")
relationship_frequency
# great, the frequency table is all set now
```
Next variable...
```{r}
# race
# frequency table
table(census_income_clean$race)
# first create a table with the counts of each class level, by income type
race_frequency_yes <- census_income_clean %>%
group_by(race, income) %>%
summarise(count = n())
race_frequency_yes
# There are no missing instances that need to be corrected for
# create another table with the same classes, to be filled in
# for the "No" columns in the table
race_frequency_No <- race_frequency_yes
# bring in the total counts to calculate the no's
race_frequency_No <- left_join(race_frequency_No,
total_counts, by = "income")
# calculate the "no" counts
race_frequency_No <- race_frequency_No %>%
mutate(count_no = count_total - count)
# now delete the "yes" and "total" count columns
race_frequency_No <- race_frequency_No %>%
select(1,2,5)
# rename the "count_no" column to just "count" for when we append to the "yes" table
colnames(race_frequency_No)[3] <- "count"
# add "_no" to the class type name
race_frequency_No$race <- paste(race_frequency_No$race,
"No", sep = "_")
# now add "_yes" to the yes table
race_frequency_yes$race <- paste(race_frequency_yes$race,
"Yes", sep = "_")
# append the "no" table to the "yes" table
race_frequency <- rbind(race_frequency_yes, race_frequency_No)
# although there are no instances with no occurrences
# I will still use laplace estimator of 1 to keep things consistent
race_frequency$count <- race_frequency$count + 1
# order the class name column alphabetically so when we spread it, the "yes"
# column is next to the "no" column for each class type
race_frequency <- arrange(race_frequency, race)
# now reorganize the table to be in proper format
race_frequency <- spread(race_frequency, key = "race", value = "count")
race_frequency
# great, the frequency table is all set now
```
Next variable...
```{r}
# sex
# frequency table
table(census_income_clean$sex)
# first create a table with the counts of each class level, by income type
sex_frequency_yes <- census_income_clean %>%
group_by(sex, income) %>%
summarise(count = n())
sex_frequency_yes
# There are no missing instances that need to be corrected for
# create another table with the same classes, to be filled in
# for the "No" columns in the table
sex_frequency_No <- sex_frequency_yes
# bring in the total counts to calculate the no's
sex_frequency_No <- left_join(sex_frequency_No,
total_counts, by = "income")
# calculate the "no" counts
sex_frequency_No <- sex_frequency_No %>%
mutate(count_no = count_total - count)
# now delete the "yes" and "total" count columns
sex_frequency_No <- sex_frequency_No %>%
select(1,2,5)
# rename the "count_no" column to just "count" for when we append to the "yes" table
colnames(sex_frequency_No)[3] <- "count"
# add "_no" to the class type name
sex_frequency_No$sex <- paste(sex_frequency_No$sex,
"No", sep = "_")
# now add "_yes" to the yes table
sex_frequency_yes$sex <- paste(sex_frequency_yes$sex,
"Yes", sep = "_")
# append the "no" table to the "yes" table
sex_frequency <- rbind(sex_frequency_yes, sex_frequency_No)
# although there are no instances with no occurrences
# I will still use laplace estimator of 1 to keep things consistent
sex_frequency$count <- sex_frequency$count + 1
# order the class name column alphabetically so when we spread it, the "yes"
# column is next to the "no" column for each class type
sex_frequency <- arrange(sex_frequency, sex)
# now reorganize the table to be in proper format
sex_frequency <- spread(sex_frequency, key = "sex", value = "count")
sex_frequency
# great, the frequency table is all set now
```
Now the last variable...
```{r}
# native-country
# frequency table
table(census_income_clean$`native-country`)
# first create a table with the counts of each class level, by income type
country_frequency_yes <- census_income_clean %>%
group_by(`native-country`, income) %>%
summarise(count = n())
country_frequency_yes
# There are missing instances for "Outlying-US(Guam-USVI-etc)" / ">50K"
# and "Holand-Netherlands" / ">50K"... add 2 rows
country_frequency_yes[nrow(country_frequency_yes) + 1,] =
list("Outlying-US(Guam-USVI-etc)",">50K",0)
country_frequency_yes[nrow(country_frequency_yes) + 1,] =
list("Holand-Netherlands",">50K",0)
# create another table with the same classes, to be filled in
# for the "No" columns in the table
country_frequency_No <- country_frequency_yes
# bring in the total counts to calculate the no's
country_frequency_No <- left_join(country_frequency_No,
total_counts, by = "income")
# calculate the "no" counts
country_frequency_No <- country_frequency_No %>%
mutate(count_no = count_total - count)
# now delete the "yes" and "total" count columns
country_frequency_No <- country_frequency_No %>%
select(1,2,5)
# rename the "count_no" column to just "count" for when we append to the "yes" table
colnames(country_frequency_No)[3] <- "count"
# add "_no" to the class type name
country_frequency_No$`native-country` <- paste(country_frequency_No$`native-country`,
"No", sep = "_")
# now add "_yes" to the yes table
country_frequency_yes$`native-country` <- paste(country_frequency_yes$`native-country`,
"Yes", sep = "_")
# append the "no" table to the "yes" table
country_frequency <- rbind(country_frequency_yes, country_frequency_No)
# apply the laplace estimator of 1
country_frequency$count <- country_frequency$count + 1
# order the class name column alphabetically so when we spread it, the "yes"
# column is next to the "no" column for each class type
country_frequency <- arrange(country_frequency, `native-country`)
# now reorganize the table to be in proper format
country_frequency <- spread(country_frequency, key = "native-country", value = "count")
country_frequency
# great, the frequency table is all set now
```
All of the separate categorical predictor variable frequency tables are created. I will combine them all into one total frequency table and create a combined liklihood table to be used for the Naive Bayes algorithm.
```{r}
# total frequency table... combining them and removing the first column
# from all but the first table, so it is not repeated
frequency_total <- cbind(workclass_frequency,
education_frequency[2:ncol(education_frequency)],
marital_frequency[2:ncol(marital_frequency)],
occupation_frequency[2:ncol(occupation_frequency)],
relationship_frequency[2:ncol(relationship_frequency)],
race_frequency[2:ncol(race_frequency)],
sex_frequency[2:ncol(sex_frequency)],
country_frequency[2:ncol(country_frequency)])
frequency_total
# checking the total columns... subtract 7 at the end
# because the first column was removed from the final 7 tables
sum(ncol(workclass_frequency),ncol(education_frequency),
ncol(marital_frequency), ncol(occupation_frequency),
ncol(relationship_frequency), ncol(race_frequency),
ncol(sex_frequency), ncol(country_frequency), -7)
# they match... so the table is complete
# Create the total liklihood table
# create a liklihood table to populate... same dimensions
liklihood_total <- frequency_total
# calculate the liklihoods
liklihood_total1 <-
data.frame(less = apply(liklihood_total[1,c(2:197)], 1,
function (x) x/sum(frequency_total[1,2:3])))
liklihood_total2 <-
data.frame(greater = apply(liklihood_total[2,c(2:197)], 1,
function (x) x/sum(frequency_total[2,2:3])))
# populate the liklihoods into the proper table format
liklihood_total[1,2:197] <- liklihood_total1[,1]
liklihood_total[2,2:197] <- liklihood_total2[,1]
liklihood_total
# looks good
# do a few checks in the table
# check a percentage in the "<=50K" row from the individual
# frequency table counts
education_frequency$`Some-college_No`[1]/sum(education_frequency[1,2:3])
# 0.7641684
# check the final liklihood value
liklihood_total$`Some-college_No`[1]
# 0.7641684... it matches
# check one from the ">50K" row
sex_frequency$Female_Yes[2]/sum(education_frequency[2,2:3])
# 0.1482024
liklihood_total$Female_Yes[2]
# 0.1482024... matches
# everything looks correct
```
Now, building a Naive Bayes classifier... To summarize the Naive Bayes, you multiply the conditional probabilities according to the Naive Bayes' rule to come up with the liklihood of the class you are interested in, then divide by the total likelihood to transform it into a probability. For this data, you multiply each individual conditional probability of the feature given that income is ">50K" times the overall probability of it being ">50K", then you divide by the total likelihood across all possible outcomes to get the probability of it being classified as ">50K.
```{r}
# I am creating a Naive Bayes classifier that takes the
# frequency data as an input (to calculate the prior probabilities),
# as well as the liklihood data (to identify the conditional probabilities
# to include in the calculation), and a feature column number vector,
# which identifies which columns in the liklihood table we should look
# at based on the classifying problem
bayes_income_data <- function(frequency_data, liklihood_data, feature_colnum_vector)
{
greater_prior_prob <- sum(frequency_data[2,2:3])/(sum(frequency_data[1:2,2:3]))
less_prior_prob <- sum(frequency_data[1,2:3])/(sum(frequency_data[1:2,2:3]))
liklihood_greater <- prod(liklihood_data[2,feature_colnum_vector]) * greater_prior_prob
liklihood_less <- prod(liklihood_data[1,feature_colnum_vector]) * less_prior_prob
prob <- (liklihood_greater/(liklihood_greater+liklihood_less))
bayes_income_data <- prob
}
```
4) Predict the binomial class membership for a white female adult who is a federal government worker with a bachelors degree who immigrated from India. Ignore any other features in your model. You must build your own Naive Bayes Classifier -- you may not use a package.
```{r}
# the problem calls for:
# race = white
# sex = female
# workclass = federal government
# education = bachelors degree
# native-country = India
# looking at the liklihood_total table to get the appropriate column numbers
# for the function I created
# race = white = 111
# sex = female = 113
# workclass = federal government = 3
# education = bachelors degree = 35
# native-country = India = 153
# checking the columns for feature_colnum_vector for the function
liklihood_total[,c(111,113,3,35,153)]
# great, now can insert into the function
case1 <- bayes_income_data(frequency_total,liklihood_total,c(111,113,3,35,153))
case1
# 0.5410806... 54% chance of greater than 50K
```
According to the function I created, this person has a 54% chance of making an income >50K
```{r}
# checking the result manually
greater_prior_prob <- sum(frequency_total[2,2:3])/(sum(frequency_total[1:2,2:3]))
less_prior_prob <- sum(frequency_total[1,2:3])/(sum(frequency_total[1:2,2:3]))
liklihood_greater <- liklihood_total$White_Yes[2] * liklihood_total$Female_Yes[2] *
liklihood_total$`Federal-gov_Yes`[2] * liklihood_total$Bachelors_Yes[2] *
liklihood_total$India_Yes[2] * greater_prior_prob
liklihood_less <- liklihood_total$White_Yes[1] * liklihood_total$Female_Yes[1] *
liklihood_total$`Federal-gov_Yes`[1] * liklihood_total$Bachelors_Yes[1] *
liklihood_total$India_Yes[1] * less_prior_prob
# probability of making >50K
liklihood_greater/(liklihood_greater+liklihood_less)
# 0.5410806
# this matches the output from the function
```
5) Perform 10-fold cross validation on your algorithm to tune it and report the final accuracy results.
For this question, I am using the liklihood table that I already created from the full dataset as the trained model for each of the 10 tests in the cross validation rather than create a new liklihood table 10 separate times for each test, since that would be very time consuming. So, I'm using the liklihood table I created (liklihood_total) and testing a different 1/10th of the data as the test data in each classification test (and calculating the average accuracy).
```{r}
# first I will adjust the liklihood table a bit and my Naive Bayes
# classification algorithm for this large amount of data to run
# through it more smoothly, for a more automated method
# since the classification is only looking at cases where a categorical
# variable is "yes", I can delete the "no" columns in my liklihood table to
# be able to automate the classification process for such a large amount of data
liklihood_total_short <- liklihood_total
# all yes columns are the odd numbered from 2-197
# also want to include row 1...
# create a vector of these columns
columns <- seq(from = 1, by = 2, to = 197)
# now take just those columns
liklihood_total_short <- liklihood_total_short[columns]
# now remove "_Yes" from the column names so that I can
# match each class level on the column names rather than
# have to use column numbers
colnames(liklihood_total_short)[2:99] <-
c(substr(colnames(liklihood_total_short[2:99]),1,
nchar(colnames(liklihood_total_short[2:99]))-4))
liklihood_total_short
# looks good
# the columns can now be referenced by the variable values in the data set
# create an adjusted version of my naive bayes algorithm to match
# values in the validation cells to column names in the liklihood table
# and to calculate overall accuracy by running the validation data through
# the algorithm; classifying each record in the data; comparing it to
# the actual classification; and calculating the percentage of correct
# classifications
bayes_income_accuracy <- function(liklihood_data, validation_data)
{
greater_prior_prob <- 0.2489558
less_prior_prob <- 0.7510442
m <- nrow(validation_data)
greater <- numeric(m)
less <- numeric(m)
total_prob <- numeric(m)
prediction <- numeric(m)
actual <- numeric(m)
for (i in 1:3016) {
greater[i] <- liklihood_data[2,as.character(validation_data[i,1])] *
liklihood_data[2,as.character(validation_data[i,2])] *
liklihood_data[2,as.character(validation_data[i,3])] *
liklihood_data[2,as.character(validation_data[i,4])] *
liklihood_data[2,as.character(validation_data[i,5])] *
liklihood_data[2,as.character(validation_data[i,6])] *
liklihood_data[2,as.character(validation_data[i,7])] *
liklihood_data[2,as.character(validation_data[i,8])] *
greater_prior_prob
less[i] <- liklihood_data[1,as.character(validation_data[i,1])] *
liklihood_data[1,as.character(validation_data[i,2])] *
liklihood_data[1,as.character(validation_data[i,3])] *
liklihood_data[1,as.character(validation_data[i,4])] *
liklihood_data[1,as.character(validation_data[i,5])] *
liklihood_data[1,as.character(validation_data[i,6])] *
liklihood_data[1,as.character(validation_data[i,7])] *
liklihood_data[1,as.character(validation_data[i,8])] *
less_prior_prob
total_prob[i] <- (greater[i]/(greater[i]+less[i]))
prediction[i] <- ifelse(total_prob[i] < 0.5, "<=50K", ">50K")
actual[i] <- as.character(validation_data[i,9])
}
bayes_income_accuracy <- sum(prediction == actual)/m
}
# Next I will split the original data set into 10 equal parts,
# taking just the categorical variables, which is what is in
# the liklihood table
validate <- census_income_clean[,c(2,4,6:10,14:15)]
head(validate)
# looks good
nrow(validate)
# 30162
# split it into 10 separate groups
validate1 <- validate[1:3016,]
validate2 <- validate[3017:6032,]
validate3 <- validate[6033:9048,]
validate4 <- validate[9049:12064,]
validate5 <- validate[12065:15080,]
validate6 <- validate[15081:18096,]
validate7 <- validate[18097:21112,]
validate8 <- validate[21113:24128,]
validate9 <- validate[24129:27144,]
validate10 <- validate[27145:30162,]
# use the updated Naive Bayes accuracy function to
# calculate the accuracy for each of the 10 validation
# data sets using the liklihood table that we already
# created
accuracy1 <- bayes_income_accuracy(liklihood_total_short, validate1)
# 0.7970822
accuracy2 <- bayes_income_accuracy(liklihood_total_short, validate2)
#0.7871353
accuracy3 <- bayes_income_accuracy(liklihood_total_short, validate3)
#0.7937666
accuracy4 <- bayes_income_accuracy(liklihood_total_short, validate4)
#0.7864721
accuracy5 <- bayes_income_accuracy(liklihood_total_short, validate5)
#0.7897878
accuracy6 <- bayes_income_accuracy(liklihood_total_short, validate6)
#0.7887931
accuracy7 <- bayes_income_accuracy(liklihood_total_short, validate7)
#0.7884615
accuracy8 <- bayes_income_accuracy(liklihood_total_short, validate8)
#0.8007294
accuracy9 <- bayes_income_accuracy(liklihood_total_short, validate9)
#0.7974138
accuracy10 <- bayes_income_accuracy(liklihood_total_short, validate10)
#0.7819748
# calculate the average of the 10 tests
mean(accuracy1,accuracy2,accuracy3,accuracy4,accuracy5,accuracy6,
accuracy7,accuracy8,accuracy9,accuracy10)
# 0.7970822
```
After splitting the data into 10 equal subsets, I classified each record in each of the subsets. I then calculated the accuracy of the classifications from each of the 10 tests in the cross validations using my bayes_income_accuracy function. I averaged each of the 10 tests to find that the algorithm I created accurately predicted 79.7% of the data on average. This is not a true 10-fold cross validation because the training data didn't change each time. You should use the remaining data from the full data set that's not included in each of the 10 subsets for each run, meaning the likihood table should be updated and changed for each of the runs based on what data is included in the training set. But I assumed for this problem that we should use our own algorithm rather than a built in package, so I used the liklihood table that was created earlier in the problem in my algorithm.
PROBLEM 2: After reading the case study background information, using the UFFI data set, answer these questions:
1) Are there outliers in the data set? How do you identify outliers and how do you deal with them? Remove them but create a second data set with outliers removed. Keep the original data set.
```{r}
# import the data
uffi <- read_csv("C:/Users/gridl/Documents/NEU/Classes/machine_learning/week_9/uffidata.csv")
# looking into the data
head(uffi)
str(uffi)
# 99 records, 12 variables... 1 of which is just an observation ID
# all are numeric, with some binary
summary(uffi)
# based on the summary statistics, the sale price, lot area, and
# living area SF look like they are right-skewed and might have outliers
# because the mean is significantly higher than the median
# looking into the distributions more to confirm
# looking at all continuous variables
hist(uffi$`Year Sold`)
# looks okay
hist(uffi$`Sale Price`)
# as suspected, it is right-skewed with some outliers on the high end
hist(uffi$`Bsmnt Fin_SF`)
# looks like it may be okay, but will examine further
hist(uffi$`Lot Area`)
# looks okay, maybe a few outliers to right, but will examine further
hist(uffi$`Enc Pk Spaces`)
# should be okay
hist(uffi$`Living Area_SF`)
# definitely appears to be outliers on the high end
# further examining outliers, I will look at the zscores for those variables
# using a zscore of 3 as the outlier threshold
# copy data into new data frame for this
uffi_no_outliers <- uffi
uffi_no_outliers %>%
mutate(zscore_SalePrice = (`Sale Price`-mean(`Sale Price`))/sd(`Sale Price`)) %>%
filter(abs(zscore_SalePrice) >= 3)
# 3 outliers on the higher end
# remove them...
uffi_no_outliers <- uffi_no_outliers %>%
filter(Observation != 94 & Observation != 40 & Observation != 60)
# look at zscores of `Bsmnt Fin_SF`
uffi_no_outliers %>%
mutate(zscore_bsmnt = (`Bsmnt Fin_SF`-mean(`Bsmnt Fin_SF`))/sd(`Bsmnt Fin_SF`)) %>%
filter(abs(zscore_bsmnt) >= 3)
# no outliers
# look at zscores of `Lot Area`
uffi_no_outliers %>%
mutate(zscore_lot = (`Lot Area`-mean(`Lot Area`))/sd(`Lot Area`)) %>%
filter(abs(zscore_lot) >= 3)
# two outliers on higher end
# remove them...
uffi_no_outliers <- uffi_no_outliers %>%
filter(Observation != 12 & Observation != 48)
# look at zscores of `Living Area_SF`
uffi_no_outliers %>%
mutate(zscore_SF = (`Living Area_SF`-mean(`Living Area_SF`))/sd(`Living Area_SF`)) %>%
filter(abs(zscore_SF) >= 3)
# one outlier on higher end