data <- Weekly
attach(data)
itrain <- createDataPartition(y = Direction, p = 0.75, list = FALSE)
train <- data[itrain,]
test <- data[-itrain,]
Given the pair plot, the volume has been exponentially increased. It seems to come from the dot-com bubble. Other than that, there is no clear sign on the relationship between variables.
par(mar = c(1,1,1,1))
pairs(train)
Just for fun, let’s see whether the stock return shows the normal curve. It clearly shows the normal curve.
library(gridExtra)
lag1 <- qplot(x = Lag1, data = train, main = "Histogram of Lag 1")
lag2 <- qplot(x = Lag2, data = train, main = "Histogram of Lag 2")
lag3 <- qplot(x = Lag3, data = train, main = "Histogram of Lag 3")
lag4 <- qplot(x = Lag4, data = train, main = "Histogram of Lag 4")
lag5 <- qplot(x = Lag5, data = train, main = "Histogram of Lag 5")
Today <- qplot(x = Today, data = train, main = "Histogram of Lag 6")
grid.arrange(lag1,lag2,lag3,lag4,lag5,Today, nrow = 3, ncol = 2)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
ctrl <- trainControl(method = "repeatedcv", number = 10)
glm.fit <- train(Direction ~ . -Year -Today,data = train, trControl = ctrl, method = "glm",
family = "binomial")
summary(glm.fit)
##
## Call:
## NULL
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.8109 -1.2578 0.9954 1.0806 1.3938
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.30620 0.09930 3.084 0.00204 **
## Lag1 -0.05166 0.03083 -1.676 0.09376 .
## Lag2 0.02653 0.03033 0.875 0.38173
## Lag3 -0.02157 0.03139 -0.687 0.49190
## Lag4 -0.01613 0.03113 -0.518 0.60429
## Lag5 -0.04326 0.03043 -1.422 0.15509
## Volume -0.04179 0.04270 -0.979 0.32774
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 1122.4 on 816 degrees of freedom
## Residual deviance: 1115.1 on 810 degrees of freedom
## AIC: 1129.1
##
## Number of Fisher Scoring iterations: 4
pred <- predict(glm.fit, test)
cm.glm <- confusionMatrix(test$Direction,pred)
cm.glm
## Confusion Matrix and Statistics
##
## Reference
## Prediction Down Up
## Down 12 109
## Up 22 129
##
## Accuracy : 0.5184
## 95% CI : (0.4572, 0.5791)
## No Information Rate : 0.875
## P-Value [Acc > NIR] : 1
##
## Kappa : -0.0501
## Mcnemar's Test P-Value : 5.741e-14
##
## Sensitivity : 0.35294
## Specificity : 0.54202
## Pos Pred Value : 0.09917
## Neg Pred Value : 0.85430
## Prevalence : 0.12500
## Detection Rate : 0.04412
## Detection Prevalence : 0.44485
## Balanced Accuracy : 0.44748
##
## 'Positive' Class : Down
##
glm.fit <- train(Direction ~ Lag2, data = train, trControl = ctrl, method = "glm", family = "binomial")
pred <- predict(glm.fit, test)
cm.glm <- confusionMatrix(test$Direction, pred)
cm.glm
## Confusion Matrix and Statistics
##
## Reference
## Prediction Down Up
## Down 1 120
## Up 1 150
##
## Accuracy : 0.5551
## 95% CI : (0.4939, 0.6152)
## No Information Rate : 0.9926
## P-Value [Acc > NIR] : 1
##
## Kappa : 0.0018
## Mcnemar's Test P-Value : <2e-16
##
## Sensitivity : 0.500000
## Specificity : 0.555556
## Pos Pred Value : 0.008264
## Neg Pred Value : 0.993377
## Prevalence : 0.007353
## Detection Rate : 0.003676
## Detection Prevalence : 0.444853
## Balanced Accuracy : 0.527778
##
## 'Positive' Class : Down
##
lda.fit <- train(Direction ~ Lag2, data = train, trControl = ctrl, method = "lda")
## Loading required package: MASS
pred.lda <- predict(lda.fit, test)
cm.lda <- confusionMatrix(test$Direction, pred.lda)
cm.lda
## Confusion Matrix and Statistics
##
## Reference
## Prediction Down Up
## Down 1 120
## Up 1 150
##
## Accuracy : 0.5551
## 95% CI : (0.4939, 0.6152)
## No Information Rate : 0.9926
## P-Value [Acc > NIR] : 1
##
## Kappa : 0.0018
## Mcnemar's Test P-Value : <2e-16
##
## Sensitivity : 0.500000
## Specificity : 0.555556
## Pos Pred Value : 0.008264
## Neg Pred Value : 0.993377
## Prevalence : 0.007353
## Detection Rate : 0.003676
## Detection Prevalence : 0.444853
## Balanced Accuracy : 0.527778
##
## 'Positive' Class : Down
##
qda.fit <- train(Direction ~ Lag2, data = train, trControl = ctrl, method = "qda")
pred.qda <- predict(qda.fit, test)
cm.qda <- confusionMatrix(test$Direction, pred.qda)
cm.qda
## Confusion Matrix and Statistics
##
## Reference
## Prediction Down Up
## Down 0 121
## Up 0 151
##
## Accuracy : 0.5551
## 95% CI : (0.4939, 0.6152)
## No Information Rate : 1
## P-Value [Acc > NIR] : 1
##
## Kappa : 0
## Mcnemar's Test P-Value : <2e-16
##
## Sensitivity : NA
## Specificity : 0.5551
## Pos Pred Value : NA
## Neg Pred Value : NA
## Prevalence : 0.0000
## Detection Rate : 0.0000
## Detection Prevalence : 0.4449
## Balanced Accuracy : NA
##
## 'Positive' Class : Down
##
knn.fit <- train(Direction ~ Lag2, data = train, trControl = ctrl, method = "knn", tuneLength = 1)
pred.knn <- predict(knn.fit, test)
cm.knn <- confusionMatrix(test$Direction, pred.knn)
cm.knn
## Confusion Matrix and Statistics
##
## Reference
## Prediction Down Up
## Down 50 71
## Up 57 94
##
## Accuracy : 0.5294
## 95% CI : (0.4682, 0.59)
## No Information Rate : 0.6066
## P-Value [Acc > NIR] : 0.9959
##
## Kappa : 0.0362
## Mcnemar's Test P-Value : 0.2505
##
## Sensitivity : 0.4673
## Specificity : 0.5697
## Pos Pred Value : 0.4132
## Neg Pred Value : 0.6225
## Prevalence : 0.3934
## Detection Rate : 0.1838
## Detection Prevalence : 0.4449
## Balanced Accuracy : 0.5185
##
## 'Positive' Class : Down
##
detach(data)
library(knitr)
compr <- list(cm.glm$overall,cm.lda$overall,cm.qda$overall,cm.knn$overall)
compr <- data.frame(do.call(rbind, compr), row.names = c("glm", "lda", "qda", "knn"))
kable(compr)
| Accuracy | Kappa | AccuracyLower | AccuracyUpper | AccuracyNull | AccuracyPValue | McnemarPValue | |
|---|---|---|---|---|---|---|---|
| glm | 0.5551471 | 0.0018197 | 0.4939236 | 0.6151558 | 0.9926471 | 1.0000000 | 0.000000 |
| lda | 0.5551471 | 0.0018197 | 0.4939236 | 0.6151558 | 0.9926471 | 1.0000000 | 0.000000 |
| qda | 0.5551471 | 0.0000000 | 0.4939236 | 0.6151558 | 1.0000000 | 1.0000000 | 0.000000 |
| knn | 0.5294118 | 0.0361553 | 0.4682146 | 0.5899612 | 0.6066176 | 0.9959414 | 0.250536 |
library(dplyr)
##
## Attaching package: 'dplyr'
## The following object is masked from 'package:MASS':
##
## select
## The following object is masked from 'package:gridExtra':
##
## combine
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
data <- Auto
attach(data)
## The following object is masked from package:ggplot2:
##
## mpg
mpg <- as.numeric(mpg)
acceleration <- as.numeric(acceleration)
displacement <- as.numeric(displacement)
horsepower <- as.numeric(horsepower)
origin <- as.factor(origin)
weight <- as.numeric(weight)
year <- as.factor(year)
cylinders <- as.factor(cylinders)
data <- mutate(data, mpg01 = ifelse(mpg < median(mpg), 0, 1))
data$mpg01 <- as.factor(data$mpg01)
attach(data)
## The following objects are masked _by_ .GlobalEnv:
##
## acceleration, cylinders, displacement, horsepower, mpg,
## origin, weight, year
## The following objects are masked from data (pos = 3):
##
## acceleration, cylinders, displacement, horsepower, mpg, name,
## origin, weight, year
## The following object is masked from package:ggplot2:
##
## mpg
set.seed(1354)
iTrain <- createDataPartition(y = mpg01, p = 0.75, list = FALSE)
Train <- data[iTrain, ]
Test <- data[-iTrain, ]
detach(data)
First, all qualitative variables shows high correlation with mpg. Also it’s interesting that three variables, displacement, horsepower, and weight, show the nonlinearity as respect to mpg. But, each explanatory variables shows correlation with each, called corlinearity.
attach(Train)
## The following objects are masked _by_ .GlobalEnv:
##
## acceleration, cylinders, displacement, horsepower, mpg,
## origin, weight, year
## The following objects are masked from data:
##
## acceleration, cylinders, displacement, horsepower, mpg, name,
## origin, weight, year
## The following object is masked from package:ggplot2:
##
## mpg
DumforPairs <- Train[,-c(2, 7, 8,9, 10)]
pairs(DumforPairs)
Second, those are the box plot as respect to mpg01
b.q.1 <- qplot(x = mpg01, y = displacement, data = Train, geom = "boxplot",
main = "Displacement")
b.q.2 <- qplot(x = mpg01, y = horsepower, data = Train, geom = "boxplot",
main = "Horsepower")
b.q.3 <- qplot(x = mpg01, y = weight, data = Train, geom = "boxplot",
main = "Weight")
b.q.4 <- qplot(x = mpg01, y = acceleration, data = Train, geom = "boxplot",
main = "Acceleration")
grid.arrange(b.q.1, b.q.2, b.q.3, b.q.4, ncol = 2)
Unlike other variables, Acceleration shows any significant difference as respect to the fuel efficiency, e.g. mpg.
ctrl <- trainControl(method = "repeatedcv")
names(Train)
## [1] "mpg" "cylinders" "displacement" "horsepower"
## [5] "weight" "acceleration" "year" "origin"
## [9] "name" "mpg01"
fit.LDA <- train(mpg01 ~. - name - mpg, data = Train, trControl = ctrl, method = "lda")
pred.LDA <- predict(fit.LDA, Test)
cm.LDA <- confusionMatrix(pred.LDA, Test$mpg01)
1 - cm.LDA$overall[[1]]
## [1] 0.09183673
d1 <- data.frame(cm.LDA$byClass)
ctrl <- trainControl(method = "repeatedcv")
fit.QDA <- train(mpg01 ~. - name - mpg, data = Train, trControl = ctrl, method = "qda")
pred.QDA <- predict(fit.QDA, Test)
cm.QDA <- confusionMatrix(pred.QDA, Test$mpg01)
1 - cm.QDA$overall[[1]]
## [1] 0.1122449
d2 <- data.frame(cm.QDA$byClass)
ctrl <- trainControl(method = "repeatedcv")
fit.glm <- train(mpg01 ~. - name - mpg, data = Train, trControl = ctrl, method = "glm", family = "binomial")
pred.glm <- predict(fit.glm, Test)
cm.glm <- confusionMatrix(pred.glm, Test$mpg01)
1 - cm.glm$overall[[1]]
## [1] 0.122449
ctrl <- trainControl(method = "repeatedcv")
fit.knn <- train(mpg01 ~. - name - mpg, data = Train, trControl = ctrl, method = "knn", preProcess = c("center", "scale"), tuneLength = 20)
pred.knn <- predict(fit.knn, Test)
cm.knn <- confusionMatrix(pred.knn, Test$mpg01)
result <- fit.knn$results
kable(result[1:5,])
| k | Accuracy | Kappa | AccuracySD | KappaSD |
|---|---|---|---|---|
| 5 | 0.9050411 | 0.8097348 | 0.0545497 | 0.1095113 |
| 7 | 0.9052791 | 0.8100772 | 0.0652501 | 0.1313458 |
| 9 | 0.9050411 | 0.8096010 | 0.0613871 | 0.1236705 |
| 11 | 0.9017077 | 0.8029344 | 0.0625845 | 0.1260201 |
| 13 | 0.9017077 | 0.8029344 | 0.0625845 | 0.1260201 |
After preprocessing the data, k=7 shows the highest accuracy.
d3 <- data.frame(cm.glm$byClass)
d4 <- data.frame(cm.knn$byClass)
D <- cbind(d1,d2,d3,d4); colnames(D) <- c("LDA", "QDA", "GLM", "KNN")
ac <- cbind(cm.LDA$overall[1], cm.QDA$overall[1], cm.glm$overall[1], cm.knn$overall[1])
colnames(ac) <- c("LDA", "QDA", "GLM", "KNN")
D <- rbind(ac,D)
kable(D[1:5, ])
| LDA | QDA | GLM | KNN | |
|---|---|---|---|---|
| Accuracy | 0.9081633 | 0.8877551 | 0.8775510 | 0.9081633 |
| Sensitivity | 0.8367347 | 0.8571429 | 0.8163265 | 0.8367347 |
| Specificity | 0.9795918 | 0.9183673 | 0.9387755 | 0.9795918 |
| Pos Pred Value | 0.9761905 | 0.9130435 | 0.9302326 | 0.9761905 |
| Neg Pred Value | 0.8571429 | 0.8653846 | 0.8363636 | 0.8571429 |
| First, both LDA a | nd KNN shows | the highest | overall acc | uracy. For specificity, LDA ranked the first followed by KNN. If the purpose for the prediction is to find the car having high fuel efficiency, it is better off chosing LDA as a predictive model. |
library(MASS)
data <- Boston
kable(head(Boston))
| crim | zn | indus | chas | nox | rm | age | dis | rad | tax | ptratio | black | lstat | medv |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0.00632 | 18 | 2.31 | 0 | 0.538 | 6.575 | 65.2 | 4.0900 | 1 | 296 | 15.3 | 396.90 | 4.98 | 24.0 |
| 0.02731 | 0 | 7.07 | 0 | 0.469 | 6.421 | 78.9 | 4.9671 | 2 | 242 | 17.8 | 396.90 | 9.14 | 21.6 |
| 0.02729 | 0 | 7.07 | 0 | 0.469 | 7.185 | 61.1 | 4.9671 | 2 | 242 | 17.8 | 392.83 | 4.03 | 34.7 |
| 0.03237 | 0 | 2.18 | 0 | 0.458 | 6.998 | 45.8 | 6.0622 | 3 | 222 | 18.7 | 394.63 | 2.94 | 33.4 |
| 0.06905 | 0 | 2.18 | 0 | 0.458 | 7.147 | 54.2 | 6.0622 | 3 | 222 | 18.7 | 396.90 | 5.33 | 36.2 |
| 0.02985 | 0 | 2.18 | 0 | 0.458 | 6.430 | 58.7 | 6.0622 | 3 | 222 | 18.7 | 394.12 | 5.21 | 28.7 |
It turned out the classes of varaibles in the data are quite messy. For further analysis, I chagned the classes of variables according to the code book in help page.
The data, boston, has 14 variables along with 506 observations. We would predict the degree of high crime rate with ohter 13 variables. First, we need to manipulate, then split the data for further analysis.
set.seed(34596)
iTrain <- createDataPartition(y = data$Mcrim, p = 0.75, list = FALSE)
Train <- data[iTrain, ]
Test <- data[-iTrain, ]
Here is the summary of the data.
summary(data)
## crim zn indus chas
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
## 1st Qu.: 0.08204 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000
## nox rm age dis
## Min. :0.3850 Min. :3.561 Min. : 2.90 Min. : 1.130
## 1st Qu.:0.4490 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100
## Median :0.5380 Median :6.208 Median : 77.50 Median : 3.207
## Mean :0.5547 Mean :6.285 Mean : 68.57 Mean : 3.795
## 3rd Qu.:0.6240 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188
## Max. :0.8710 Max. :8.780 Max. :100.00 Max. :12.127
## rad tax ptratio black
## Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
## 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
## Median : 5.000 Median :330.0 Median :19.05 Median :391.44
## Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
## 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
## Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
## lstat medv Mcrim
## Min. : 1.73 Min. : 5.00 0:253
## 1st Qu.: 6.95 1st Qu.:17.02 1:253
## Median :11.36 Median :21.20
## Mean :12.65 Mean :22.53
## 3rd Qu.:16.95 3rd Qu.:25.00
## Max. :37.97 Max. :50.00
The interesting factor in the Boston data is chas variable. The variable indicates whether the town bounds Charls river. Does the closeness to Charls river show the relationship with crime rate? With the table, we can see whether the relation exists. The per centage of crime goes above median if the town is far from the river is 49%. And that of crime goes above median if the town bounds the river is 62.5%.
attach(Train)
table(chas,Mcrim)
## Mcrim
## chas 0 1
## 0 181 175
## 1 9 15
Next, let’s look at the box plot as respect to the degree of crime, Mcrim.
q1 <- qplot(x = Mcrim, y = log(zn)+1, data = Train, geom = "boxplot", main = "Zone")
## used log to scale zone variables.
q2 <- qplot(x = Mcrim, y = indus, data = Train, geom = "boxplot", main = "Indus")
q3 <- qplot(x = Mcrim, y = nox, data = Train, geom = "boxplot", main = "nitrogen oxides")
q4 <- qplot(x = Mcrim, y = rm, data = Train, geom = "boxplot", main = "Avg Rooms")
q5 <- qplot(x = Mcrim, y = age, data = Train, geom = "boxplot", main = "Home Units Age")
q6 <- qplot(x = Mcrim, y = dis, data = Train, geom = "boxplot", main = "Distance")
q7 <- qplot(x = Mcrim, y = tax, data = Train, geom = "boxplot", main = "Prop. Tax")
q8 <- qplot(x = Mcrim, y = ptratio, data = Train, geom = "boxplot", main = "Education")
q9 <- qplot(x = Mcrim, y = black, data = Train, geom = "boxplot", main = "Black Pop.")
q10 <- qplot(x = Mcrim, y = lstat, data = Train, geom = "boxplot", main = "Lower Status")
q11 <- qplot(x = Mcrim, y = medv, data = Train, geom = "boxplot", main = "Med Val of Home")
grid.arrange(q1,q2,q3,q4,q5,q6,q7,q8,q9,q10,q11, ncol = 6)
## Warning: Removed 280 rows containing non-finite values (stat_boxplot).
Given the graph, five variables, nitroge oxides, Med val Home Value, Distance, Home units Age, lower Status, shows the distinctive characteristics as respect to the degree of crime.
Then, here is the predictive analysis with 3 different models, LDA, GLM, KNN.
ctrl <- trainControl(method = "repeatedcv")
dat <- Train[,-1]
dim(dat)
## [1] 380 14
findLinearCombos(dat)
## $linearCombos
## list()
##
## $remove
## NULL
fit.lda <- train(Mcrim ~ . ,trControl = ctrl, data = dat, method = "lda")
fit.lda$finalModel
## Call:
## lda(x, grouping = y)
##
## Prior probabilities of groups:
## 0 1
## 0.5 0.5
##
## Group means:
## zn indus chas nox rm age dis
## 0 20.794737 6.993211 0.04736842 0.4718932 6.402337 50.71842 5.07392
## 1 1.168421 15.186211 0.07894737 0.6348263 6.209737 85.11842 2.50559
## rad tax ptratio black lstat medv
## 0 4.178947 305.4895 17.97316 388.6874 9.310579 25.28789
## 1 15.063158 511.7211 19.07526 324.9032 16.026737 19.91684
##
## Coefficients of linear discriminants:
## LD1
## zn -0.003741868
## indus 0.008592637
## chas -0.039542626
## nox 7.869796901
## rm 0.070604292
## age 0.010587569
## dis -0.012376907
## rad 0.076987991
## tax -0.001008256
## ptratio 0.071785521
## black -0.001020335
## lstat 0.016760765
## medv 0.038316240
pred.lda <- predict(fit.lda, Test)
fit.glm <- train(Mcrim ~ . ,trControl = ctrl, data = dat, method = "glm", family = "binomial")
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
pred.glm <- predict(fit.glm, Test)
fit.knn <- train(Mcrim ~ . ,trControl = ctrl, data = dat, method = "knn", preProcess = c("center", "scale"), tuneLength = 20)
pred.knn <- predict(fit.knn,Test)
In this model, GLM shows the highest accuracy.
cm.lda <- confusionMatrix(Test$Mcrim, pred.lda)
cm.glm <- confusionMatrix(Test$Mcrim, pred.glm)
cm.knn <- confusionMatrix(Test$Mcrim, pred.knn)
D <- data.frame(rbind(cm.lda$byClass, cm.glm$byClass, cm.knn$byClass), row.names = c("LDA", "GLM", "KNN"))
ac <- cbind(cm.lda$overall[1], cm.glm$overall[1], cm.knn$overall[1])
colnames(ac) <- c("LDA", "GLM", "KNN")
D <- rbind(ac,t(D))
kable(D[1:5, ])
| LDA | GLM | KNN | |
|---|---|---|---|
| Accuracy | 0.8492063 | 0.8888889 | 0.9047619 |
| Sensitivity | 0.7972973 | 0.8550725 | 0.8695652 |
| Specificity | 0.9230769 | 0.9298246 | 0.9473684 |
| Pos.Pred.Value | 0.9365079 | 0.9365079 | 0.9523810 |
| Neg.Pred.Value | 0.7619048 | 0.8412698 | 0.8571429 |