Мне нужно сделать свой собственный код дерева регрессии.
Я сделал код, который делает критерий разделения, оценивая наименьшее число SSE и нанося на график это разделение.
Однако я не могу продолжить эту обработку разделения. Как я могу продолжить процесс разделения (что означает встраивание модели дерева в max_depth)?
Еще одна проблема заключается в том, как я могу создать код, который может обрезать мое дерево?
** Мне не следует использовать такие пакеты, как ctree, rpart, которые связаны с пакетами дерева решений.
# Install tidyverse pacakges
install.packages("tidyverse")
# Load libraries
library(MASS)
library(ggplot2)
# Load the dataset (preprocessing outliers)
mammals <- mammals[c(-19,-32:-33),]
print(mammals)
# Visualize the dataset
ggplot(mammals, aes(x = brain, y = body )) + geom_point() + theme_bw()
# Split Criteria : SSE = \sum_{i \in S_1} (y_i - \bar(y)1)^2 +
#\sum_{i \inS_2} (y_i - \bar(y)2)^2
n_data <- nrow(mammals)
# The potential splits are all the values of Mileage found in the dataset.
# Create dataframe to store all potential splits, their associated sum of
# squares
# error (SSE), and the predictions for the left and right groups after the
#split.
SSE.df <- data.frame(brain = sort(mammals$brain),
SSE = numeric(n_data),
left_mean = numeric(n_data),
right_mean = numeric(n_data))
for(i in 1:n_data){
brain <- SSE.df$brain[i]
# split cars into left and right groups by mileage
left <- mammals[mammals$brain <= brain,]
right <- mammals[mammals$brain > brain,]
# calculate left and right predictions/means
SSE.df$left_mean[i] <- mean(left$body)
SSE.df$right_mean[i] <- mean(right$body)
# calculate sum of squares error
SSE.df$SSE[i] <- sum((left$body - SSE.df$left_mean[i])^2) +
sum((right$body - SSE.df$right_mean[i])^2)
}
# plot the SSE for each split on mileage
ggplot(SSE.df, aes(x = brain, y = SSE/1000)) + geom_line() + theme_bw()
# the best split is the mileage with the minimum SSE
best_split <- SSE.df[which.min(SSE.df$SSE),]
best_split
# create datasets with points to plot red lines for the left and right
# means
left_mean <- data.frame(x = c(-Inf, best_split$brain),
y = rep(best_split$left_mean, 2))
right_mean <- data.frame(x = c(best_split$brain, Inf),
y = rep(best_split$right_mean, 2))
ggplot(mammals, aes(x = brain, y = body)) +
geom_point() + theme_bw() +
geom_vline(xintercept = best_split$brain) +
geom_line(data = left_mean, aes(x = x, y = y), color = "red") +
geom_line(data = right_mean, aes(x = x, y = y), color = "red")
Подводя итог, я хочу 3 вещи.
1. код, который строит дерево регрессии maximum_depth.
2. код, который обрезает листья деревьев, чтобы избежать перегрузки.
3. codw, который показывает MSE (средняя квадратическая ошибка) каждого узла.
Спасибо