Come è già stato menzionato nelle risposte precedenti, la foresta casuale per gli alberi di regressione / regressione non produce previsioni previste per i punti dati al di fuori dell'ambito dell'intervallo di dati di addestramento perché non possono estrapolare (bene). Un albero di regressione è costituito da una gerarchia di nodi, in cui ciascun nodo specifica un test da eseguire su un valore di attributo e ciascun nodo foglia (terminale) specifica una regola per calcolare un output previsto. Nel tuo caso l'osservazione del test scorre attraverso gli alberi verso i nodi fogliari indicando, ad esempio, "se x> 335, quindi y = 15", che vengono quindi mediati da una foresta casuale.
Ecco uno script R che visualizza la situazione con sia la foresta casuale che la regressione lineare. Nel caso della foresta casuale, le previsioni sono costanti per testare i punti dati che sono al di sotto del valore x dei dati di allenamento più basso o al di sopra del valore x dei dati di allenamento più alti.
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()
