---
title: "DT"
author: "Matene Zamaninia"
date: "11/1/2021"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```



```{r}

library(ggplot2)
library(rpart)   ## FOR Decision Trees
library(rattle)  ## FOR Decision Tree Vis
library(rpart.plot)
library(RColorBrewer)
library(Cairo)
library(network)

##If you install from the source....
#Sys.setenv(NOAWT=TRUE)
## ONCE: install.packages("wordcloud")
library(wordcloud)
library(randomForest)

library(tidyverse)
library(partykit)
library(caret)
library(rpart)
library(randomForest)
library(rpart.plot)
library(C50)
library(printr)
library(ROSE)
library(ggplot2)
library(dplyr)
library(class)
library(e1071)
library(corrplot)
library(faraway)
library(pROC)
library(epiDisplay)
library(binaryLogic)


```

# Read data 

```{r}
data <- read.csv("Final_cleaning.csv")



df <- as.data.frame(data)
```



```{r}
variables <- c()
variables <- subset(df, EBikeProfileID==1, select = c("Battery","BikeTypeName","EBikeStateID","Latitude", "Longitude", "dmiles", "day_of_week", "binned_hours", "Weekdays_ends"))

df <- variables
colnames(df)


```





# Data Reformatting 
```{r}

# 1) Battery. turn into three binned facotrs. 

df$Battery.label <- cut(df$Battery, breaks = 2, labels = c("0-50", "50-100"))

#2) Turning the values of Bike Type Name to integers and then ordered factors so as to be able to use them 


# 
# list <- c()
# for (i in 1:NROW(df)){
#   if (df$BikeTypeName[i] == "DUB-General"){
#     list[i] = 0}
#   else if (df$BikeTypeName[i] == "Workshop"){
#      list[i] = 1}
#   else{
#     list[i] = 2 }
# }
# df$BikeTypeint <- list

# unique(df$BikeTypeint)

#3) Day of week to integers

list <- c()
for (i in 1:NROW(df)){
  if (df$day_of_week[i] == "Monday"){
    list[i] = 1}
  else if (df$day_of_week[i] == "Tuesday"){
     list[i] = 2}
  else if (df$day_of_week[i] == "Wednesday"){
     list[i] = 3}
  else if (df$day_of_week[i] == "Thursday"){
     list[i] = 4}
  else if (df$day_of_week[i] == "Friday"){
     list[i] = 5}
  else if (df$day_of_week[i] == "Saturday"){
     list[i] = 6}
  else if (df$day_of_week[i] == "Sunday"){
     list[i] = 7}
}

df$weekday_int <- list

unique(df$Weekdays_ends)

df$Weekdays_ends <- as.factor(df$Weekdays_ends)
str(df)

df$BikeTypeName <- as.factor(df$BikeTypeName)
df$EBikeStateID <- as.factor(df$EBikeStateID)
df$weekday_int <- as.factor(df$weekday_int)


```

```{r}
model_data <- df[,c(2,3,6,8, 9, 10)]

colnames(model_data)

GoPlot <- function(x) {
  
  G <-ggplot(data=model_data, aes(.data[[x]], y="") ) +
  geom_bar(stat="identity", aes(fill =.data[[x]])) 
  
  return(G)
}

## Use the function in lappy
lapply(names(model_data), function(x) GoPlot(x))




```

```{r}
DataSize=nrow(model_data) ## how many rows?
TrainingSet_Size<-floor(DataSize*(3/4)) ## Size for training set
TestSet_Size <- DataSize - TrainingSet_Size ## Size for testing set

## Random sample WITHOUT replacement (why?)
## set a seed if you want it to be the same each time you
## run the code. The number (like 1234) does not matter
set.seed(1234)

## This is the sample of row numbers
MyTrainSample <- sample(nrow(model_data),
                                    TrainingSet_Size,replace=FALSE)

## Use the sample of row numbers to grab those rows only from
## the dataframe....
MyTrainingSET <- model_data[MyTrainSample,]
  

table(MyTrainingSET$Battery.label)

## Use the NOT those row numbers (called -) to get the
## other row numbers not in the training to use to create
## the test set.

## Training and Testing datasets MUST be disjoint. Why?
MyTestSET <- model_data[-MyTrainSample,]
table(MyTestSET$Battery.label)

```


```{r}
TestKnownLabels <- MyTestSET$Battery.label
MyTestSET <- MyTestSET[ , -which(names(MyTestSET) %in% c("Battery.label"))]
```




```{r}

library(rpart)

DT <- rpart(MyTrainingSET$Battery.label ~ ., data = MyTrainingSET, method="class")
summary(DT)

rpart.plot(DT, extra = 106, main = "no cp")



DT1 <- rpart(MyTrainingSET$Battery.label ~ ., data = MyTrainingSET, cp = 0.005, method="class")
summary(DT1)

rpart.plot(DT1, box.palette = "Blues", main = "cp = 0.005")



DT2 <- rpart(MyTrainingSET$Battery.label ~ ., data = MyTrainingSET, cp = 0.0005, method="class")
summary(DT2)

rpart.plot(DT2, box.palette = "Blues", extra = 106, main= "cp 0.0005")


```




```{r}
## DT---------------------------------

DT_Prediction= predict(DT, MyTestSET, type="class")
## Confusion Matrix
table(DT_Prediction,TestKnownLabels) ## one way to make a confu mat
## VIS..................
fancyRpartPlot(DT, main = "Default CP")



DT_Prediction= predict(DT1, MyTestSET, type="class")
## Confusion Matrix
table(DT_Prediction,TestKnownLabels) ## one way to make a confu mat
## VIS..................
fancyRpartPlot(DT1, main = "0.005 CP")


DT_Prediction= predict(DT2, MyTestSET, type="class")
## Confusion Matrix
table(DT_Prediction,TestKnownLabels) ## one way to make a confu mat



confusionMatrix(DT_Prediction, TestKnownLabels)
## VIS..................
fancyRpartPlot(DT2,main= "cp 0.0005")




```




```{r}

forest1 <- randomForest(MyTrainingSET$Battery.label ~ .,data = MyTrainingSET,ntree = 20,mtry = 5)
forest1

plot(forest1, main = "")
varImpPlot(forest1)

g <- predict(forest1, newdata = MyTrainingSET)
cf <- confusionMatrix(MyTrainingSET$Battery.label,g)

cf


varImpPlot(forest1)
```






```{r}
fit <- rpart(Battery.label~. , data =MyTrainingSET)
df <- data.frame(imp = fit$variable.importance)
df2 <- df %>% 
  tibble::rownames_to_column() %>% 
  dplyr::rename("variable" = rowname) %>% 
  dplyr::arrange(imp) %>%
  dplyr::mutate(variable = forcats::fct_inorder(variable))



ggplot2::ggplot(df2) +
  geom_col(aes(x = variable, y = imp),
           col = "yellow", show.legend = F) +
  coord_flip() +
  theme_light()

```






























