Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
---
title: "R Notebook"
output: pdf_notebook
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning = F, message = F)
```
```{r warning=FALSE, message=FALSE}
library(tidyverse)
library(randomForest)
library(cowplot)
library(gridExtra)
```
```{r}
rents <- read.csv('./data/rent.csv')
glimpse(rents)
```
```{r}
features <- c('bathrooms', 'bedrooms', 'longitude', 'latitude', 'price')
df <- rents[,features]
df$price <- log(df$price)
# with random column
df['random'] <- runif(nrow(df))
head(df)
```
## PLOTTING FUNCTIONS
```{r}
create_rfplot <- function(rf, type){
imp <- importance(rf, type=type, scale = F)
featureImportance <- data.frame(Feature=row.names(imp), Importance=imp[,1])
p <- ggplot(featureImportance, aes(x=reorder(Feature, Importance), y=Importance)) +
geom_bar(stat="identity", fill="#53cfff", width = 0.65) +
coord_flip() +
theme_light(base_size=20) +
theme(axis.title.x=element_blank(),
axis.title.y=element_blank(),
axis.text.x = element_text(size = 15, color = "black"),
axis.text.y = element_text(size = 15, color = "black"))
return(p)
}
create_ggplot <- function(featureImportance){
p <- ggplot(featureImportance, aes(x=reorder(Feature, Importance), y=Importance)) +
geom_bar(stat="identity", fill="#53cfff", width = 0.65) +
coord_flip() +
theme_light(base_size=20) +
theme(axis.title.x=element_blank(),
axis.title.y=element_blank(),
axis.text.x = element_text(size = 15, color = "black"),
axis.text.y = element_text(size = 15, color = "black"))
return(p)
}
```
## BUILT-IN IMPORTANCE
**Important Note: Unscaled Feature importances are used while assessing built-in feature importances**
"Here are the definitions of the variable importance measures. The first measure is computed from permuting OOB data: For each tree, the prediction error on the out-of-bag portion of the data is recorded (error rate for classification, MSE for regression). Then the same is done after permuting each predictor variable. The difference between the two are then averaged over all trees, and normalized by the standard deviation of the differences. If the standard deviation of the differences is equal to 0 for a variable, the division is not done (but the average is almost always equal to 0 in that case).
The second measure is the total decrease in node impurities from splitting on the variable, averaged over all trees. For classification, the node impurity is measured by the Gini index. For regression, it is measured by residual sum of squares."
From : http://ugrad.stat.ubc.ca/R/library/randomForest/html/importance.html
#### TYPE 1 = Mean decrease in MSE by **Permutation**
```{r}
# without random column
rf1 <- randomForest(price~., data = df[, 1:5], mtry=4,
ntree = 40, importance=T)
importance(rf1, scale=F)
p1 <- create_rfplot(rf1, type = 1)
#ggsave('../article/images/regr_permute_R.svg',
#plot = p1, device = 'svg', height = 4, width = 6)
```
```{r}
# with random column
rf2 <- randomForest(price~., data = df, mtry = 4,
ntree = 40, importance=T)
importance(rf2, scale=F)
p2 <- create_rfplot(rf2, type = 1)
#ggsave('../article/images/regr_permute_random_R.svg',
#plot = p2, device = 'svg', height = 4, width = 6)
imp1 <- data.frame(importance(rf2, type = 1, scale=F))
write.csv(imp1, file="./data/imp_R_regr_MSE.csv")
```
#### TYPE 2 = Mean decrease in node impurity (RSS) by splitting on columns, **Python's default**
```{r}
# without random column
rf1 <- randomForest(price~., data = df[, 1:5], mtry=4,
ntree = 40, importance=T)
p1 <- create_rfplot(rf1, type = 2)
#ggsave('../article/images/regr_dflt_R.svg',
#plot = p1, device = 'svg', height = 4, width = 6)
```
```{r}
# with random column
rf2 <- randomForest(price~., data = df, mtry = 4,
ntree = 40, importance=T)
p2 <- create_rfplot(rf2, type = 2)
#ggsave('../article/images/regr_dflt_random_R.svg',
#plot = p2, device = 'svg', height = 4, width = 6)
imp1 <- data.frame(importance(rf2, type = 2,scale=F))
write.csv(imp1, file="./data/imp_R_regr_RSS.csv")
```
## EXAMINE COST BY DROPPING
```{r, eval=F}
# PARAMS : ntree = 40, mtry = 2, nodesize = 1
get_drop_imp <- function(df, columns){
X <- df[,c(columns, 'price')] # data
rf <- randomForest(price~., data = X,
ntree = 40, mtry=2, nodesize=1, importance=T)
full_rsq <- mean(rf$rsq) # R-squared
imp <- c()
for (c in columns){
X_sub <- X[, !(colnames(X) == c)]
rf <- randomForest(price~., data = X_sub,
ntree = 40, mtry=2, nodesize=1, importance=T)
sub_rsq <- mean(rf$rsq) # R-squared
diff_rsq <- full_rsq - sub_rsq
imp <- c(imp, diff_rsq)
}
featureImportance <- data.frame(Feature=columns, Importance=imp)
return(featureImportance)
}
```
```{r, eval=F}
columns <- c('bathrooms', 'bedrooms', 'longitude', 'latitude')
featureImportance <- get_drop_imp(df, columns)
p1 <- create_ggplot(featureImportance)
#ggsave('../article/images/regr_drop_R.svg',
#plot = p1, device = 'svg', height = 4, width = 6)
```
```{r, eval=F}
columns <- c('bathrooms', 'bedrooms', 'longitude', 'latitude', 'random')
featureImportance <- get_drop_imp(df, columns)
p2 <- create_ggplot(featureImportance)
#ggsave('../article/images/regr_drop_random_R.svg',
#plot = p2, device = 'svg', height = 4, width = 6)
write.csv(featureImportance, file="./data/imp_R_regr_drop.csv")
```