正如在之前的答案中已经提到的那样,回归/回归树的随机森林不会产生超出训练数据范围范围的数据点的预期预测,因为它们无法推断(很好)。回归树由节点的层次结构组成,其中每个节点指定要对属性值执行的测试,每个叶(终端)节点指定计算预测输出的规则。在您的情况下,测试观察通过树流向叶节点,例如“如果 x > 335,则 y = 15”,然后由随机森林平均。
这是一个 R 脚本,使用随机森林和线性回归来可视化情况。在随机森林的情况下,对于低于最低训练数据 x 值或高于最高训练数据 x 值的测试数据点的预测是恒定的。
library(datasets)
library(randomForest)
library(ggplot2)
library(ggthemes)
# Import mtcars (Motor Trend Car Road Tests) dataset
data(mtcars)
# Define training data
train_data = data.frame(
x = mtcars$hp, # Gross horsepower
y = mtcars$qsec) # 1/4 mile time
# Train random forest model for regression
random_forest <- randomForest(x = matrix(train_data$x),
y = matrix(train_data$y), ntree = 20)
# Train linear regression model using ordinary least squares (OLS) estimator
linear_regr <- lm(y ~ x, train_data)
# Create testing data
test_data = data.frame(x = seq(0, 400))
# Predict targets for testing data points
test_data$y_predicted_rf <- predict(random_forest, matrix(test_data$x))
test_data$y_predicted_linreg <- predict(linear_regr, test_data)
# Visualize
ggplot2::ggplot() +
# Training data points
ggplot2::geom_point(data = train_data, size = 2,
ggplot2::aes(x = x, y = y, color = "Training data")) +
# Random forest predictions
ggplot2::geom_line(data = test_data, size = 2, alpha = 0.7,
ggplot2::aes(x = x, y = y_predicted_rf,
color = "Predicted with random forest")) +
# Linear regression predictions
ggplot2::geom_line(data = test_data, size = 2, alpha = 0.7,
ggplot2::aes(x = x, y = y_predicted_linreg,
color = "Predicted with linear regression")) +
# Hide legend title, change legend location and add axis labels
ggplot2::theme(legend.title = element_blank(),
legend.position = "bottom") + labs(y = "1/4 mile time",
x = "Gross horsepower") +
ggthemes::scale_colour_colorblind()