代码:
library(tidyverse) # utility functions
library(rpart) # for regression trees
library(randomForest) # for random forests
library(modelr)
split_data = resample_partition(melb_data,c(test=.3,train=.7))
get_mae <- function(maxdepth, target, predictors, training_data, testing_data){
predictors <- paste(predictors, collapse="+")
formula <- as.formula(paste(target,"~",predictors,sep = ""))
model <- rpart(formula, data = training_data,
control = rpart.control(maxdepth = maxdepth))
mae <- mae(model, testing_data)
return(mae)
}
target <- "Price"
predictors <- c("Rooms","Bathroom","Landsize","BuildingArea",
"YearBuilt","Lattitude","Longtitude")
for(i in 1:10){
mae <- get_mae(maxdepth = 3, target = target, predictors = predictors, training_data = split_data$train, testing_data = split_data$test)
print(glue::glue("Maxdepth: ",i,"\t MAE: ",mae))
}
输出 :
Maxdepth: 1 MAE: 356628.697268696
Maxdepth: 2 MAE: 356628.697268696
Maxdepth: 3 MAE: 356628.697268696
Maxdepth: 4 MAE: 356628.697268696
Maxdepth: 5 MAE: 356628.697268696
Maxdepth: 6 MAE: 356628.697268696
Maxdepth: 7 MAE: 356628.697268696
Maxdepth: 8 MAE: 356628.697268696
Maxdepth: 9 MAE: 356628.697268696
Maxdepth: 10 MAE: 356628.697268696