-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathAbalone.Rmd
1653 lines (1189 loc) · 82.4 KB
/
Abalone.Rmd
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
---
output:
html_document: default
pdf_document: default
---
---
title: "Predicting the age of abalone using regression"
date: "July 24, 2017"
output: html_document
toc: yes
--
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Methods
```{r, eval=FALSE, message=FALSE, warning=FALSE}
#Run these commands to intall all the required packages for this reportt
install.packages("readr")
install.packages("dplyr")
install.packages("car")
install.packages("lmtest")
install.packages("ggplot2")
install.packages("GGally")
install.packages("gridExtra")
install.packages("MASS")
install.packages("leaps")
install.packages("glmnet")
install.packages("caret")
install.packages("gbm")
```
```{r Installing/Loading Packages, message=FALSE, warning=FALSE}
#loading all necessary packages
library(readr)
library(dplyr)
library(car)
library(lmtest)
library(ggplot2)
library(GGally)
library(gridExtra)
library(MASS)
library(leaps)
library(glmnet)
library(caret)
library(gbm)
```
### Data summary and statistics
```{r, message=FALSE, warning=FALSE}
abalone <- read_csv("Abalone_data.csv")
is.factor(abalone$Sex)
abalone$Sex <- as.factor(abalone$Sex)
str(abalone, give.attr = FALSE)
library(knitr)
kable(abalone[1:10,], digits = 4,format = 'markdown')
```
##### Categorial Variables
| Sex | Number of observations |
| --- | ---------------------- |
| M | 1527 |
| F | 1307 |
| I | 1342 |
##### Numeric Variables
| | Length | Diameter | Height | Whole Weight | Shucked Weight | Viscera Weight | Shell Weight | Rings |
| ---- | ------ | -------- | ------ | ----- | ------- | ------- | ----- | ----- |
| Min | 15.0 | 11.00 | 0.0000 | 0.4 | 0.20 | 0.10 | 0.30 | 1 |
|Median| 109.0 | 85.00 | 28.00 | 159.9 | 67.20 | 34.20 | 46.80 | 9 |
| Mean | 104.8 | 81.58 | 27.91 | 165.8 | 71.88 | 36.12 | 47.77 | 9.932 |
| Max | 163.0 | 130.00 | 226.00 | 565.1 | 297.60 | 152.00 | 201.00| 29 |
| Cor | 0.557 | 0.5750 | 0.5581 | 0.5408| 0.4212 | 0.5043 | 0.6280| 1.000 |
- Looking at the dataset summary, we can see that data is quite evenly distributed between the three factor levels of `male`, `female` and `infant`.
- Also from we see that there are four different measure of weight i.e. `Whole_weight`, `Shucked_weight`, `Viscera_weight` and `Shell.weight`. `Whole_weight` is linear function of other weight predictors with Unknown mass of water/blood lost from shucking process. Also we observed that min value of predictor `Height` is 0. Practically this is not possible, we will investigate these observations to look closely.
##### Response variable
- The dependent variable Rings is included in the dataset. It was measured as the number of rings observed after cutting and examining an abalone. Although it does not denote the age of a given abalone directly, it determines it more-or-less perfectly. The age of an abalone equals Rings + 1.5 . Since this relationship holds reliably, Rings will be considered as the dependent variable. The number of rings measured in the data ranges from 1 to 29 and most of the abalone have between 5 and 15 rings. The distribution is slightly positively skewed as well but this does not pose any specific problems for the further analysis. (see plot below)
####Pair Plot
```{r, fig.height=10, fig.width=12, message=FALSE, warning=FALSE}
ggpairs(abalone, aes(colour = Sex, alpha = 0.8), title="Pairs plot for abalone dataset") +
theme_grey(base_size = 8)
```
####Observations from Pair Plot :
- First thing to note here is high correlation in data. There seems to be high multicollinearity between the predictors. for example correlation between `Diameter` and `Length` is extremely high (about 98.7).
- Similarly `Whole_weight` seems to be highly correlated with other weight predictors and is the sum of `Shucked_weight`, `Viscera_weight` and `Shell_weight`.
- Secondly, the distributions of predictor `Sex` with factor level value of `female` and `male` are very similar with respect to all other predictors.
- The shape of distribution is also significantly similar for factor levels of `female` and `male`.
- We could think about redefining this feature to define gender as infant vs non-infant (where non-infant = female and male both).
- Most of the abalones rings are between 5 and 15.
```{r, echo=FALSE}
#Function to calculate RMSE
rmse <- function(actual, predicted) {
sqrt(mean((actual - predicted) ^ 2))
}
#high leverage points
calculate_leverage <- function(model){
(hatvalues(model) > 2 * mean(hatvalues(model)))
}
#large residuals
calculated_residuales <- function(model){
(abs(rstandard(model)) > 2)
}
#influential points
calculate_influence <- function(model){
sum(cooks.distance(model) > 4 / length(cooks.distance(model)))
}
#Function for boxplot
create_boxplot <- function(xvar,yvar,xtitle,ytitle){
ggplot(abalone, aes(x=xvar,y=yvar, fill=Sex))+
geom_boxplot() +
xlab(paste(xtitle)) +
ylab(paste(ytitle))
}
#function for density plots
create_den_plots <- function(xvar, title){
ggplot(abalone, aes(x = xvar, fill = Sex)) +
geom_density(alpha = 0.8) +
ylab("Number of abalone") +
ggtitle(paste(title)) +
xlab("Sex")
#facet_wrap(~Sex, ncol = 3)
}
#variable added plot
create_varplot <- function(big_model, small_model){
plot(resid(big_model) ~ resid(small_model),
col = "dodgerblue", pch = 20,
xlab = "Residuals, Added Predictor",
ylab = "Residuals, Original Model")
abline(h = 0, lty = 2)
abline(v = 0, lty = 2)
abline(lm(resid(big_model) ~ resid(small_model)),
col = "darkorange", lwd = 2)
}
#Scatter plots
create_scatter_plot <- function(xvar,yvar,xtitle,ytitle) {
ggplot(abalone_train,aes(x=xvar,y=yvar, col=Sex)) +
geom_point() +
geom_jitter() +
xlab(paste(xtitle)) +
ylab(paste(ytitle))
}
#fitted vs residuals plots
create_fitted_residuals <- function(model,name){
plot(fitted(model), resid(model), col = "grey", pch = 20,
xlab = "Fitted", ylab = "Residuals", main = paste("Fitted vs Residuals (",name,")"))
abline(h = 0, col = "darkorange", lwd = 2)
}
#normal q-q plot
create_qq_normal <- function(model,name){
qqnorm(resid(model), main = paste("Normal Q-Q Plot (",name,")"), col = "darkgrey")
qqline(resid(model), col = "dodgerblue", lwd = 2)
}
compare_rmse <- function(model,name){
abalone_add_train_rmse <- rmse(abalone_train$Rings, predict(model,abalone_train))
abalone_add_test_rmse <- rmse(abalone_test$Rings, predict(model,abalone_test))
result <- data.frame('Model'=c(name),"RMSE Train"=c(abalone_add_train_rmse),"RMSE Test"=c(abalone_add_test_rmse))
}
log_rmse <- function(model,name){
abalone_add_train_rmse <- sqrt(mean((abalone_train$Rings - exp(fitted(model))) ^2))
abalone_add_test_rmse <- sqrt(mean((abalone_test$Rings - exp(predict(model, newdata=abalone_test))) ^ 2))
result <- data.frame('Model'=c(name),"RMSE Train"=c(abalone_add_train_rmse),"RMSE Test"=c(abalone_add_test_rmse))
}
get_log_rmse <- function(model){
abalone_add_train_rmse <- sqrt(mean((abalone_train$Rings - exp(fitted(model))) ^2))
abalone_add_test_rmse <- sqrt(mean((abalone_test$Rings - exp(predict(model, newdata=abalone_test))) ^ 2))
data.frame(train=abalone_add_train_rmse,test=abalone_add_test_rmse)
}
get_log_rmse_obs <- function(model,train_data){
abalone_add_train_rmse <- sqrt(mean((train_data$Rings - exp(fitted(model))) ^2))
abalone_add_test_rmse <- sqrt(mean((abalone_test$Rings - exp(predict(model, newdata=abalone_test))) ^ 2))
data.frame(train=abalone_add_train_rmse,test=abalone_add_test_rmse)
}
model_assumptions <- function(model,name){
par(mfrow = c(1, 2),oma=c(0,0,0,0))
create_fitted_residuals(model,name)
create_qq_normal(model,name)
}
test_model <- function(degree){
model <- lm(log(Rings) ~ Diameter+ Length + Height + poly(Whole_weight,degree) + poly(Viscera_weight,degree) + poly(Shucked_weight,degree) + poly(Shell_weight,degree) + Sex, data=abalone_train)
model
}
test_int_model <- function(d){
model <- lm(log(Rings) ~ Length + Height + Diameter + poly(Whole_weight, d) +
poly(Viscera_weight, d) + poly(Shucked_weight,d) + poly(Shell_weight, d) + Sex + Diameter:poly(Shucked_weight, d) + poly(Shucked_weight, d):Sex, data=abalone_train)
model
}
find_leverage <- function(model){
return (which(hatvalues(model) > 2 * mean(hatvalues(model))))
}
find_outliers <- function(model){
which(abs(rstandard(model)) > 2)
}
find_influence <- function(model){
which(cooks.distance(model)> 4 / length(cooks.distance(model)))
}
get_best_result <- function(caret_fit) {
best_result <- caret_fit$results[as.numeric(rownames(caret_fit$bestTune)), ]
rownames(best_result) <- NULL
best_result
}
get_rmse <- function(model){
abalone_add_train_rmse <- sqrt(mean((abalone_train$Rings - (fitted(model))) ^2))
abalone_add_test_rmse <- sqrt(mean((abalone_test$Rings - (predict(model, newdata=abalone_test))) ^ 2))
data.frame(train=abalone_add_train_rmse,test=abalone_add_test_rmse)
}
```
#### Data quality
- **Addition of variables**: We will update the abalone dataset to create new variable named `Infant` which will have values based on original value from `Sex` variable. It will have value of `I`, when `Sex` variable is `I` and `NI` otherwise.
```{r, message=FALSE, warning=FALSE}
abalone['Infant'] <- ifelse(abalone$Sex == 'I','I','NI')
abalone$Infant <- as.factor(abalone$Infant)
abalone$Sex <- as.factor(abalone$Sex)
```
- Also we observed that min value of predictor `Height` is 0. Practically this is not possible, we will investigate these observations to look closely.
```{r}
#Data quality check for height being 0
kable(abalone[abalone$Height == 0,], digits = 4,format = 'markdown')
```
- We see that there are two observations for which `Height` might not be recorded properly as other predictors seems to have valid values. Also if we look at the predictor `Whole_weight`, we see that these values are really small compare to rest of the observation and below first quantile. This tells us that this might not be a data error therefore we can not exclude these from our dataset.
- We will also add a new variable named `weight.diff`.We can see in the summary that there are four different measure of weight i.e. `Whole_weight`, `Shucked_weight`, `Viscera_weight` and `Shell.weight`. `Whole_weight` is linear function of other weight predictors with unknown mass of water/blood lost from shucking process.
```{r}
abalone$weight.diff <- abalone$Whole_weight - (abalone$Viscera_weight + abalone$Shucked_weight + abalone$Shell_weight)
str(abalone, give.attr = FALSE)
```
- We see that variable `Whole_weight` should be the linear function of variables `Shucked_weight`, `Viscersa_weight` and `Shell_weight`, and we could write it as `Whole_weight` = `Shucked_weight` + `Viscera_weight`+ `Shell_weight` + unknown mass of water/blood lost from shucking process.
- However when we calculated difference between `Whole_weight` and other weight variables we see that there are `r nrow(abalone[abalone$weight.diff < 0,])` observations that are violating this. i.e. this seems to be a illogical and could be an error while recording data.
- If we plot the histogram of the newly added `weight.diff` variable, we can see that there are observations when `weight.diff` is negative.
```{r, fig.width=12, message=FALSE, warning=FALSE}
#Identify observations that are not recorded properly
#Histogram of illogical observations
ggplot(abalone, aes(x=weight.diff)) +
geom_histogram(colour="dodgerblue",fill=rgb(1,.54,0,.7), bins = 30) +
scale_y_continuous(name="count") +
labs(title="Histogram of abalone with weight difference less than zero")
```
- To make sure, lets take a look at few of these records.
```{r}
nrow(abalone[abalone$weight.diff < 0,])
kable(head(abalone[abalone$weight.diff < 0,], n=10), digits = 4,format = 'markdown')
```
- Note that there are total 153 observations that has combined weight of more than `Whole_weight`. When we looked at 10 such observations, it seems that other values are correct and there is no similarity so we are sure that this might be an data entry error. Therefore we will keep these observations for further analysis.
- We will start with diving our dataset in train and test. The dataset will be splitted between train and test with the ratio of 70/30 with random selected observations.
####Train & Test Split
```{r, message=FALSE, warning=FALSE}
set.seed(42)
#Splitting dataset in train and test using 70/30 method
indexes <- sample(1:nrow(abalone), size = 0.3 * nrow(abalone))
abalone_train <- abalone[-indexes,]
abalone_test <- abalone[indexes,]
```
###Additive Multiple Linear Regression Model
- We have started with fitting an additive model with all variables and will look at the significance of the parameters. Based on that we will modify our model. For now we will work with original value for variable `Sex` which have factor levels of `F`, `I` and `M`.
```{r}
abalone_add <- lm(Rings ~ Sex+Length+Diameter+Height+ Whole_weight
+Shucked_weight+Viscera_weight
+Shell_weight,data = abalone_train)
summary(abalone_add)
```
- In first additive model, note that factor level **female** is reference level for `Sex` variable.
- After fitting the additive model with all predictors we can see that test statistics showing all variables as significant except `Length`. As we saw previously from pairs plot that `Length` and `Diameter` predictors are highly correlated. We also see that different weights predictors are also significant even though they should be linear function of each other.
####RMSE Score:
```{r}
kable(compare_rmse(abalone_add,"Additive Model"), digits = 4,format = 'markdown')
```
####Multicollinearity:
- We will calculate **variance inflation factor** in order to find presence of Multicollinearity issue with the dataset.
```{r}
faraway::vif(abalone_add)
```
- We looked that variable inflation factor for all variable and it appears that all predictors have multicollinearity issue except `Sex` and `Height` as we saw previously in pairs plot. Predictor `Whole_weight` has highest VIF value as it is a linear function of other weight.
####Partial correlation coefficient between Whole_weight & Rings :
We will first calculate the partial correlation coefficient of the `Whole_weight` variable & the response variable (Rings).
```{r}
#check variabolity in high collinearity variables
whole_weight_fit <- lm(Whole_weight ~ Sex + Length + Diameter + Height + Shucked_weight + Viscera_weight + Shell_weight, data=abalone_train)
abalone_add_without_whole_weight <- lm(Rings ~ Sex + Length + Diameter + Height
+ Shucked_weight + Viscera_weight + Shell_weight,data = abalone_train)
```
- The correlation of these two residuals are close to zero, it means that the variation of Rings that is unexplained by predictors `Sex`,`Length`,`Diameter`,`Height`,`Shucked_weight`,`Viscera_weight` and `Shell_weight` shows very little correlation with the variation of `Whole_weight` that is not explained by `Sex`,`Length`,`Diameter`,`Height`,`Shucked_weight`,`Viscera_weight` and `Shell_weight`. Thus adding `Whole_weight` to the model would likely be of little benefit.
####Variable added plot
- Similarly a variable added plot visualizes these residuals against each other. It is also helpful to regress the residuals of the response against the residuals of the predictor and add the regression line to the plot.
```{r}
cor(resid(whole_weight_fit),resid(abalone_add_without_whole_weight))
create_varplot(abalone_add_without_whole_weight,whole_weight_fit)
```
####Variance inflation factor of the additive model without the Whole_weight
- Still the VIF of the `Diameter` and `Length` is high.
```{r}
faraway::vif(abalone_add_without_whole_weight)
```
####Partial correlation coefficient between Diameter & Rings
We will now calculate the partial correlation coefficient of the `Diameter` variable & the response variable (Rings) without having the `Whole_weight` variable in the model.
```{r, message=FALSE, warning=FALSE}
diameter_fit <- lm(Diameter ~ Sex + Length + Height + Shucked_weight + Viscera_weight + Shell_weight, data=abalone_train)
abalone_add_small <- lm(Rings ~ Sex + Length + Height + Shucked_weight + Viscera_weight + Shell_weight,data = abalone_train)
```
- The correlation of these two residuals are close to zero, it means that the variation of Rings that is unexplained by `Sex`,`Length`,`Height`,`Shucked_weight`,`Viscera_weight` and `Shell_weight` shows very little correlation with the variation of `Diameter` that is not explained by `Sex`,`Length`,`Height`,`Shucked_weight`,`Viscera_weight` and `Shell_weight`. Thus adding `Diameter` to the model would likely be of little benefit.
```{r, message=FALSE, warning=FALSE}
cor(resid(diameter_fit),resid(abalone_add_small))
create_varplot(abalone_add_small,diameter_fit)
```
#### Variance inflation factor of the additive model without the Whole_weight & Diameter
```{r, message=FALSE, warning=FALSE}
faraway::vif(abalone_add_small)
```
- Now the VIF is much lower. We will use the both the abalone_add & abalone_add_small for our analysis.
#### RMSE Score of abalone_add_small
```{r, message=FALSE, warning=FALSE}
kable(compare_rmse(abalone_add_small,"Additive Small Model"), digits = 4,format = 'markdown')
```
#### Anova *F* Test
```{r}
anova(abalone_add_small,abalone_add)
```
- As per the Anova Test, we can reject the null hypothesis.
- Now lets try to run `AIC` and `BIC` on the additive model for parameter selection.
```{r}
#Running AIC and BIC on additive model
abalone_model_add_aic <- step(abalone_add, direction="backward", trace=0)
summary(abalone_model_add_aic)
n <- length(resid(abalone_add))
abalone_model_add_bic <- step(abalone_add, direction="backward", k=log(n), trace=0)
summary(abalone_model_add_bic)
```
- We ran `AIC` AND `BIC` method using best model (`abalone_add`) from the previous Anova F Test. both `AIC` and `BIC` selected the same model without the `Length` predictor.
- We selected the model from `BIC` (Since both models are same) and will plot fitted vs residuals and qq normal plots.
#### Additive Model Assumptions
```{r, fig.height=4, fig.width=10, message=FALSE, warning=FALSE}
model_assumptions(abalone_model_add_bic,"abalone_model_add_bic")
```
- Here we see that fitted vs residuals plots suggests that model is violating the constant variation and appears to have a pattern where residuals are increasing as fitted values are increasing.
- Normal QQ plot also has fat tail which are indication that errors are may not be normally distributed.
- This is an indication that we might need to need to look to improve this model. Even though multicollinearity does not have effect on prediction, this looks like an extreme case where there is a clear pattern that violates model assumptions. This could be achieved by several techniques for example variable selection and transformation. Lets take a look at the variable selection method to see which variables could be used to create another model that does not violate constant variation and normality assumptions.
### Exhaustive search
```{r, fig.height=5, fig.width=10, message=FALSE, warning=FALSE}
#exhaustive search
all_abalone_add <- summary(regsubsets(Rings ~ Sex + Length + Diameter + Height + Whole_weight + Shell_weight + Shucked_weight + Viscera_weight , data=abalone_train))
kable(all_abalone_add$which, digits = 4,format = 'markdown')
var_num=rep(0,8)
for(i in c(1:8)){
var_num[i]=sum(all_abalone_add$which[i,])-1
}
par(mfrow = c(1, 2),oma=c(0,0,0,0))
plot(var_num,all_abalone_add$rss,pch = 20,
col = "dodgerblue", type = "b", cex = 2,
xlab = '# of Predictors (Including Dummy Variable)')
plot(var_num,all_abalone_add$adjr2,pch = 20, col = "dodgerblue",
xlab = '# of Predictors (Including Dummy Variable)',type = "b", cex = 2)
(bestrj2 <- which.max(all_abalone_add$adjr2))
all_abalone_add$which[bestrj2,]
#Plotting model parameter vs AIC plot
p <- length(coef(abalone_add))
n <- length(resid(abalone_add))
abalone_mod_aic <- n * log(all_abalone_add$rss / n) + 2 * (2:p)
abalone_mod_aic
```
```{r, fig.width=10, message=FALSE, warning=FALSE}
plot(abalone_mod_aic ~ I(2:p), ylab = "AIC", xlab = "p, number of parameters",
pch = 20, col = "dodgerblue", type = "b", cex = 2,
main = "AIC vs Model Complexity")
```
- Now we are seeing some interesting results here. previously we saw that t test showing some predictors as non-significant but when we performed the exhaustive search, it is suggesting that we do need all the predictors to create the model with lowest `AIC` value. As it can be seen from the plot that `AIC` goes down and is the least with the size of model with 8 parameters. We will again use all predictors from dataset to create model and look for variables transformation techniques.
- Next in order to stabilize the constant variation, we will perform some response and predictor transformations.
###Response Transformation
####Box-Cox Transformations
- One of the way to stabilize the variance is by using log transforming the response. In order to get the correct order of it, we used boxcox method which is suggesting to use $\lambda$ value of 0. As the at the value of 0, the log-likelyhood maximizes and the intervals are extremely close. Hence we will use transformation of form `log(Rings)` for our additive model.
```{r}
boxcox(abalone_add, plotit = TRUE, lambda = seq(-0.1, 0.1, by = 0.1))
```
####Additive Model with log response transformations
```{r}
abalone_add_log <- lm(log(Rings) ~ Sex + Length + Diameter + Height + Whole_weight + Shucked_weight + Viscera_weight + Shell_weight,data = abalone_train)
summary(abalone_add_log)
```
- After log transforming the response, we see that t test was significant, it also increased the adjusted r squared value from previous additive model. We also see that almost all of the predictors are significant here in this model. lets check the assumptions.
#### Model Assumptions
- Below the Fitted versus Residuals Plot & Q-Q Plots shows that the results have improved a lot after applying log transformation on the response variable.
```{r echo=TRUE, fig.height=4, fig.width=10, message=FALSE, warning=FALSE}
model_assumptions(abalone_add_log,"abalone_add_log")
```
#### RMSE Score
```{r}
kable(log_rmse(abalone_add_log,"Additive Log Model"), digits = 4,format = 'markdown')
```
- However we dont see any improvement in the RMSE Score. Though model assumptions now looks much better. the constant variance issue seems to be improved and qq plot is also looking good.
- Next, we will perform some transformations on predictors and evaluate the models and will see of this helps further for prediction accuracy.
###Predictor Transformations
####Regression Analysis
- In order for us to perform any predictors transformations, let first see how each of the predictors are related to response. The transformation will depend on it shape of the data and relationship between predictors and response.
```{r, echo=TRUE, fig.height=8, fig.width=15}
par(mfrow = c(3, 3),oma=c(0,0,0,0))
grid.arrange(
create_scatter_plot(abalone_train$Length,abalone_train$Rings,"Length","Rings"),
create_scatter_plot(abalone_train$Diameter,abalone_train$Rings,"Diameter","Rings"),
create_scatter_plot(abalone_train$Height,abalone_train$Rings,"Height","Rings"),
create_scatter_plot(abalone_train$Whole_weight,abalone_train$Rings,"Whole_weight","Rings"),
create_scatter_plot(abalone_train$Shell_weight,abalone_train$Rings,"Shell_weight","Rings"),
create_scatter_plot(abalone_train$Shucked_weight,abalone_train$Rings,"Shucked_weight","Rings"),
create_scatter_plot(abalone_train$Viscera_weight,abalone_train$Rings,"Viscera_weight","Rings")
)
```
- We can see the relationship with `Rings` and predictors `Length`,`Diameter`, `Height` is almost linear. Also we can see that relationship between weight predictors are not really linear but could benefit from polynomial transformations. So lets create a model using higher order polynomial of all weight predictors `Whole_weight`,`Viscera_weight`,`Shucked_weight` and `Shell_weight`.
#### Polynomials
The Model assumptions are same after using 2nd order term in the model.
```{r echo=TRUE, fig.height=4, fig.width=10}
abalone_add_poly2 <- lm(log(Rings) ~ Diameter + Length + Height + poly(Whole_weight,2) + poly(Viscera_weight,2) + poly(Shucked_weight,2) + poly(Shell_weight,2) + Sex, data=abalone_train)
model_assumptions(abalone_add_poly2,"Poly2 Log Model")
```
#### RMSE Score
```{r}
kable(log_rmse(abalone_add_poly2,"Poly2 Log Model"), digits = 4,format = 'markdown')
```
- Here we have performed some variable transformations. First we log transformed the response as suggested by `boxcox` method and used polynomial transformations for weight predictors as suggested in pairs plot. after fitting the model, we see that rmse is lower than previous models and it also has better constant variation and Q-Q plots compared to previously fitted additive models. Since we have performed a polynomial transformations with the degree of 2, lets try to fit another model with degree of 3 and check the significance.
```{r, fig.height=8, fig.width=10, message=FALSE, warning=FALSE}
abalone_add_poly3 <- lm(log(Rings) ~ Diameter + Length + Height + poly(Whole_weight,3) + poly(Viscera_weight,3) + poly(Shucked_weight,3) + poly(Shell_weight,3) + Sex, data=abalone_train)
```
#### RMSE Score
```{r}
kable(log_rmse(abalone_add_poly3,"Poly3 Log Model"), digits = 4,format = 'markdown')
```
#### ANOVA *F* Test
```{r}
anova(abalone_add_poly2,abalone_add_poly3)
```
- *F* test has low p-value suggesting that transformation with degree 3 is significant and we saw that rmse went down compare to polynomial model with degree 2. Lets try to fit the model of degree 4 and check the significance.
```{r, fig.height=5, fig.width=10, message=FALSE, warning=FALSE}
abalone_add_poly4 <- lm(log(Rings) ~ Diameter + Length + Height + poly(Whole_weight,4) + poly(Viscera_weight,4) + poly(Shucked_weight,4) + poly(Shell_weight,4) + Sex, data=abalone_train)
```
#### RMSE Score
```{r}
kable(log_rmse(abalone_add_poly4,"Poly4 Log Model"), digits = 4,format = 'markdown')
```
#### ANOVA *F* Test
```{r}
anova(abalone_add_poly3,abalone_add_poly4)
```
- Again we see that it was significant. lets try to fit the model with degree of 5.
```{r, fig.height=4, fig.width=10, message=FALSE, warning=FALSE}
abalone_add_poly5 <- lm(log(Rings) ~ Diameter + Length + Height + poly(Whole_weight,5) + poly(Viscera_weight,5) + poly(Shucked_weight,5) + poly(Shell_weight,5) + Sex, data=abalone_train)
```
#### RMSE Score
```{r}
kable(log_rmse(abalone_add_poly5,"Poly5 Log Model"), digits = 4,format = 'markdown')
```
#### ANOVA *F* Test
```{r}
anova(abalone_add_poly4,abalone_add_poly5)
```
- We again see that test was significant with lower rmse. lets try to fit the model with degree of 6.
```{r, fig.height=4, fig.width=10, message=FALSE, warning=FALSE}
abalone_add_poly6 <- lm(log(Rings) ~ Diameter + Length + Height + poly(Whole_weight,6) + poly(Viscera_weight,6) + poly(Shucked_weight,6) + poly(Shell_weight,6) + Sex, data=abalone_train)
```
#### RMSE Score
```{r}
kable(log_rmse(abalone_add_poly6,"Poly6 Log Model"), digits = 4,format = 'markdown')
```
#### ANOVA *F* Test
```{r}
anova(abalone_add_poly5,abalone_add_poly6)
```
- Now after fitting with polynomial degree of 6 we see that even though F test suggest that it was a significant, the test RMSE went up. This here is an indication that we may have now started overfitting the data i.e. our model is fitting data really closely, which we do not want to be happen.
- Before this we see that there is a very slight difference between the test and train RMSE with polynomial degree of 5 and 4. test RMSE is almost the same. Therefore we are willing to sacrifice very minute improvement (third decimal point) in RMSE over the simpler model. Hence we select the model with the polynomial degree of 4 which is model **abalone_add_poly4**.
```{r}
num_poly=seq(1,10,by = 1)
train_rmse=rep(0,length(num_poly))
test_rmse=rep(0,length(num_poly))
for(d in num_poly){
abalone_add_poly=test_model(d)
rmse=get_log_rmse(abalone_add_poly)
train_rmse[d]=rmse$train
test_rmse[d]=rmse$test
}
```
```{r Fig5, echo=TRUE, fig.height=5, fig.width=10, message=FALSE, warning=FALSE}
plot(train_rmse,
type = "o",
col = "red",
xlab = "Models with # Higher order term",
ylab = "Error (RMSE)",
main = "Train vs Test RMSE",
ylim=c(min(as.vector(train_rmse)),
max(as.vector(test_rmse))),
cex.lab=1.3,
cex.axis=1.3)
lines(test_rmse,
type = "o",
col = "blue")
legend('topright',
c("Train error", "Test error"),
lty = c(1,1),
lwd = c(2.5, 2.5),
col = c("red", "blue"))
```
- We see that there is a very slight difference between the test and train RMSE with polynomial degree of 5 and 4. test RMSE is almost the same. Therefore we are willing to sacrifice very minute improvement in RMSE over the simpler model. Hence we select the model with the polynomial degree of 4 which is model **abalone_add_poly4**.
- Since we have selected the model lets run `AIC` and `BIC` method to select appropriate model further and see if we can make further improvements.
- Now lets calculate and compare the RMSE for higher order term and plot that for both Train & Test data.
### AIC and BIC on poly additive model:
- Since we have selected the model lets run `AIC` and `BIC` method to select appropriate model further.
```{r}
abalone_model_add_aic <- step(abalone_add_poly4, direction="backward", trace=FALSE)
n <- length(resid(abalone_add_poly4))
abalone_model_add_bic <- step(abalone_add_poly4, direction="backward", k=log(n), trace=FALSE)
```
####Compare AIC vs BIC Model Parameters
```{r}
abalone_model_add_aic$call[2]
abalone_model_add_bic$call[2]
```
####Anove F Test
```{r}
anova(abalone_model_add_bic,abalone_model_add_aic)
```
- The model selected by `BIC` does not have predictor `Length` in it. The p-value of the Anova F Test is large, so we fail to reject the null hypothesis. The `abalone_model_add_bic` model is significant,so we will move forward with it and will check model assumptions.
####Model Assumptions (AIC & BIC):
```{r Fig6, echo=TRUE, fig.height=4, fig.width=10, message=FALSE, warning=FALSE}
model_assumptions(abalone_model_add_aic,"abalone_model_add_aic")
```
```{r Fig7, echo=TRUE, fig.height=4, fig.width=10, message=FALSE, warning=FALSE}
model_assumptions(abalone_model_add_bic,"abalone_model_add_bic")
```
- Both constant variance and normality looks good in this case.
#### RMSE Score - AIC
```{r}
kable(log_rmse(abalone_model_add_aic,paste("Additive Model - Degree 4 - AIC ")), digits = 4,format = 'markdown')
```
#### RMSE Score - BIC
```{r, message=FALSE, warning=FALSE}
kable(log_rmse(abalone_model_add_bic,paste("Additive Model - Degree 4 - BIC")), digits = 4,format = 'markdown')
```
- After doing variable selection using `AIC` and `BIC`, we selected the model from `BIC` and checked the t statistics and assumptions. Interestingly `BIC` model is dropping few predictors but also has similar test RMSE as original model we started with (model with polynomial degree of 4). Which suggests that we could drop some of the variables and still maintain lower RMSE. This bring us to the next modification and introduction of interaction terms between the variables selected by `BIC` model above.
- The model assumptions from `BIC` model also looks better.
- Next we will introduce interaction terms and will try to fit the model with predictors suggested by `BIC` method.
###Interaction Model
```{r}
abalone_int <- lm(log(Rings) ~ Height + Diameter + poly(Whole_weight, 4) +
poly(Viscera_weight, 4) + poly(Shucked_weight,4) + poly(Shell_weight, 4) + Sex + Diameter:poly(Shucked_weight, 4) + poly(Shucked_weight, 4):Sex, data=abalone_train)
```
####RMSE Score
```{r}
kable(log_rmse(abalone_int,"Interation Model"), digits = 4,format = 'markdown')
```
#### ANOVA *F* Test
```{r}
anova(abalone_add_poly4,abalone_int)
```
- After fitting the interaction model and performing F test with best additive model we see that test suggest that interaction model is a significant model, with improved adjusted r squared value. Also RMSE got lower Since it is better explaining the variability, we for now will choose the interaction model and will try to run AIC and BIC on interaction model.
- At the same time, we would compare interaction model with several degrees to calculate and compare the RMSE for higher order term and plot that for both Train & Test data.
```{r, message=FALSE, warning=FALSE}
num_poly=seq(1,6,by = 1)
train_rmse_int=rep(0,length(num_poly))
test_rmse_int=rep(0,length(num_poly))
for(d in num_poly){
abalone_int_poly=test_int_model(d)
rmse=get_log_rmse(abalone_int_poly)
train_rmse_int[d]=rmse$train
test_rmse_int[d]=rmse$test
}
```
```{r Fig9, echo=TRUE, fig.height=7, fig.width=10, message=FALSE, warning=FALSE}
plot(train_rmse_int,
type = "o",
col = "red",
xlab = "Models with # Higer order term",
ylab = "Error (RMSE)",
main = "Train vs Test RMSE",
ylim=c(min(as.vector(train_rmse_int)),
max(as.vector(test_rmse_int))),
cex.lab=1.3,
cex.axis=1.3)
lines(test_rmse_int,
type = "o",
col = "blue")
legend('topright',
c("Train error", "Test error"),
lty = c(1,1),
lwd = c(2.5, 2.5),
col = c("red", "blue"))
```
- We can see that that RMSE is getting lower and lower as polynomial degree increases. Though this improvement in RMSE is so minute for this analysis that we can ignore this improvement over model simplicity. Considering this we can see that model with polynomial degree of 4 is performing better so we will move forward with that model.
### AIC and BIC on Interaction model
```{r, message=FALSE, warning=FALSE}
abalone_model_int_aic <- step(abalone_int, direction="backward", trace=FALSE)
n <- length(resid(abalone_int))
abalone_model_int_bic <- step(abalone_int, direction="backward", k=log(n), trace=FALSE)
abalone_model_int_aic$call[2]
abalone_model_int_bic$call[2]
```
#### RMSE Score - BIC/AIC
```{r}
kable(log_rmse(abalone_model_int_bic,paste("Interaction Model - Degree 4 - BIC")), digits = 4,format = 'markdown')
```
- After running AIC and BIC on our interaction model, we see that model selected the same model. Since this is one of the best model we have seen so far with reasonable complexity, we will consider this as one of the candidate models for our comparison as the best fitted model for this analysis.
- Talking about candidate models, during the exhaustive search we have seen that the lowest AIC comes with model when we use all predictors. We can try to build a model with all predictors with the interaction and polynomial degree and see how it stands compare to our first selected candidate model. So lets fit a model with all predictors.
```{r}
abalone_int_full <- lm(log(Rings) ~ Length + Height + Diameter + poly(Whole_weight, 4) + poly(Viscera_weight, 4) + poly(Shucked_weight, 4) + poly(Shell_weight, 4) + Sex + Diameter:poly(Shucked_weight, 4) + poly(Shucked_weight, 4):Sex, data = abalone_train)
```
- During the initial data analysis, we found that distribution of categorical variable `Sex` with factor level of `female` and `male` is extremely similar. Because of this we decided to merged these two factor level in one and have total factor level to be two `infant` and `non-infant`. We created new variable `Infant`. here `non-infant` represents `female` and `male` both. we performed analysis from this approach as well (which can be found on appendix section of this report).
- Lets looks at Infant model analysis and see how this model stands up against our model of choice above.
### Infant Model Analysis
- Remember we talked about taking a different approach for this analysis. We introduced a new categorical predictor names `Infant`. We used existing categorical predictors `Sex` with 3 factor level and create a new with 2 factor levels. We did this because we identified similar distribution on 2 factor levels from original categorical predictor `female` and `male`. New factors levels now are `I` (infant = female and male combined) and `NI` (non infant).
- The analysis with this new categorical is exactly the same as analysis above so we will move fast with this analysis with minimum explanation and details.
#### Additive Infant Models
```{r}
abalone_add_inf <- lm(Rings ~ Infant+Length+Diameter+Height+ Whole_weight
+Shucked_weight+Viscera_weight
+Shell_weight,data = abalone_train)
summary(abalone_add_inf)
```
#### RMSE Score
```{r}
rmse <- function(actual, predicted) {
sqrt(mean((actual - predicted) ^ 2))
}
kable(compare_rmse(abalone_add_inf,"Additive Infant Model"), digits = 4,format = 'markdown')
```
#### Additive Model Assumptions
```{r fig.height=4, fig.width=10, message=FALSE, warning=FALSE}
model_assumptions(abalone_add_inf,"abalone_add_inf")
```
#### Box-Cox Transformations
```{r fig.height=6, fig.width=10, message=FALSE, warning=FALSE}
boxcox(abalone_add_inf, plotit = TRUE, lambda = seq(-0.1, 0.1, by = 0.1))
```
#### Additive Infant Model with log response transformations
```{r}
abalone_add_log_inf <- lm(log(Rings) ~ Infant + Length + Diameter + Height + Whole_weight + Shucked_weight + Viscera_weight + Shell_weight,data = abalone_train)
summary(abalone_add_log)
```
#### RMSE Score
```{r}
kable(log_rmse(abalone_add_log_inf,"Additive Infant Model (Log)"), digits = 4,format = 'markdown')
```
#### Additive Model Assumptions
```{r fig.height=4, fig.width=10, message=FALSE, warning=FALSE}
model_assumptions(abalone_add_log_inf,"abalone_add_log_inf")
```
#### Polynomial Model
```{r}
abalone_add_poly3_int <- lm(log(Rings) ~ Diameter + Length + Height + poly(Whole_weight,3) + poly(Viscera_weight,3) + poly(Shucked_weight,3) + poly(Shell_weight,3) + Infant, data=abalone_train)
```
#### RMSE Score
```{r}
kable(log_rmse(abalone_add_poly3_int,"Polynomial Infant Model"), digits = 4,format = 'markdown')
```
#### Polynomial Model Assumptions
```{r fig.height=4, fig.width=10, message=FALSE, warning=FALSE}
model_assumptions(abalone_add_poly3_int,"abalone_add_poly3_int")
```
#### Anova F Test
```{r}
anova(abalone_add_log_inf,abalone_add_poly3_int)
```
#### Interaction Model
```{r}
abalone_int_infant <- lm(log(Rings) ~ Height + Diameter + poly(Whole_weight, 4) +
poly(Viscera_weight, 4) + poly(Shucked_weight,4) + poly(Shell_weight, 4) + Infant + Diameter:poly(Shucked_weight, 4) + poly(Shucked_weight, 4):Infant, data=abalone_train)
```
#### RMSE Score
```{r}
kable(log_rmse(abalone_int_infant,"Interaction Infant Model"), digits = 4,format = 'markdown')
```
#### Interaction Model Assumptions
```{r fig.height=4, fig.width=10, message=FALSE, warning=FALSE}
model_assumptions(abalone_int_infant,"abalone_int_infant")
```
#### Anova F Test
```{r}
anova(abalone_add_poly3_int,abalone_int_infant)
```
- Here we are selecting the best performing interaction model as one of our candidate models. This model has less complexity as well as the lowest rmse.
- What we see here is that this model has the lowest rmse on unseen data (test data) compare to previous two full models. In addition to this, this model is also less complex than previous two, These characteristic makes this model as one of the candidate model of our choice.
- Now since we have a few candidate model that we like, lets compare these against each other and looks for best model.
### Candidate models
- From the analysis above we have selected interaction model with polynomial degree of 4 as we have seen it has one of the lowest test rmse with good model assumptions. We will consider this as the first choice of one of the candidate model. This model contains some of the predictors and not the ones with high multicollinearity. This model is **abalone_model_int_bic**.
- Another selected model is the interaction model with all predictors with similar lower rmse. Though this model will be have more parameters hence is a more complex model than earlier model but since our goal is prediction, we do not care about complexity of the model. This model is **abalone_int_full**
- One another candidate model will be the interaction model with categorical variable with 2 factor levels. The the beginning or our analysis we saw that distribution of this predictors was similar between level `male` and `female` so we decided to introduced a new variable which essentially had 2 levels, infant and non-infant where non-infant = male and female. This model is also an interaction model with the polynomial degree of **4**. This model is **abalone_int_infant**.
**Note: (The Additive model and related analysis using the infant predictor have been added in the appendix section)**. The entire process of analysis with categorical predictor and factor level with `3` values and `2` values are same.
#### RMSE comparison for candidate models
- Candidate model 1 (abalone_model_int_bic)
```{r}
kable(log_rmse(abalone_model_int_bic,paste("Candidate model 1")), digits = 4,format = 'markdown')
```
- Candidate model 2 (abalone_int__candidate_full)
```{r}
kable(log_rmse(abalone_int_full,paste("Candidate model 2")), digits = 4,format = 'markdown')
```
- Candidate model 3 (abalone_int_infant)
```{r}
kable(log_rmse(abalone_int_infant,paste("Candidate model 3")), digits = 4,format = 'markdown')
```
- As we can see from above that the **Candidate model 3 (abalone_int_infant)** is performing best among all three models.
#### Model assumptions for candidate models
- Candidate model 1 (abalone_model_int_bic)
```{r ,echo=TRUE, fig.height=4, fig.width=10, message=FALSE, warning=FALSE}
model_assumptions(abalone_model_int_bic,"Candidate model 1")
```
- Candidate model 2 (abalone_int_full)
```{r ,echo=TRUE, fig.height=4, fig.width=10, message=FALSE, warning=FALSE}
model_assumptions(abalone_int_full,"Candidate model 2")
```
- Candidate model 3 (abalone_int_infant)
```{r ,echo=TRUE, fig.height=4, fig.width=10, message=FALSE, warning=FALSE}
model_assumptions(abalone_int_infant,"Candidate model 3")
```
- Based on these plots we can see that all of our candidate models are satisfying both constant variance and normality assumptions nicely.
- Next we will compare all of these candidates models for its prediction and confidence interval and observe any influential points in our data. lets look at it.
### Unusual observations
We will take a look the unusual observations present in the train data set for each candidate models. First we will look for the high leverage points, outliers and influential points individually and then get the data points with high leverage, outliers and influence by taking the common data points.
####Candidate model 1 (abalone_model_int_bic)
```{r, message=FALSE, warning=FALSE}
leverage <- find_leverage(abalone_model_int_bic)
outliers <- find_outliers(abalone_model_int_bic)
influence <- find_influence(abalone_model_int_bic)
common_leverage_influence <- intersect(influence,leverage)
common_model_1 <- intersect(outliers,common_leverage_influence)
length(common_model_1)
```
- We see that there are `r length(common_model_1)` observations that are high leverage, outlier and influential points.
####Candidate model 2 (abalone_int_full)
```{r, message=FALSE, warning=FALSE}
leverage <- find_leverage(abalone_int_full)
outliers <- find_outliers(abalone_int_full)
influence <- find_influence(abalone_int_full)
common_leverage_influence <- intersect(influence,leverage)
common_model_2 <- intersect(outliers,common_leverage_influence)
length(common_model_2)
```
- In this model, we see that there are `r length(common_model_2)` observations that are high leverage, outlier and influential points.
####Candidate model 3 (abalone_int_infant)
```{r, message=FALSE, warning=FALSE}
leverage <- find_leverage(abalone_int_infant)
outliers <- find_outliers(abalone_int_infant)
influence <- find_influence(abalone_int_infant)
common_leverage_influence <- intersect(influence,leverage)