Probamos la normalidad en la variable mpg, como ejemplo
de variable dependiente.
# Histograma y prueba de normalidad
p_hist <- ggplot(mtcars, aes(x = mpg)) +
geom_histogram(bins = 10, fill = "lightblue", color = "black") +
ggtitle("Histograma de mpg")
ggplotly(p_hist)
qqnorm(mtcars$mpg)
qqline(mtcars$mpg, col = "red")
# Prueba de Shapiro-Wilk
shapiro.test(mtcars$mpg)
##
## Shapiro-Wilk normality test
##
## data: mtcars$mpg
## W = 0.94756, p-value = 0.1229
summary(mtcars)
## mpg cyl disp hp
## Min. :10.40 Min. :4.000 Min. : 71.1 Min. : 52.0
## 1st Qu.:15.43 1st Qu.:4.000 1st Qu.:120.8 1st Qu.: 96.5
## Median :19.20 Median :6.000 Median :196.3 Median :123.0
## Mean :20.09 Mean :6.188 Mean :230.7 Mean :146.7
## 3rd Qu.:22.80 3rd Qu.:8.000 3rd Qu.:326.0 3rd Qu.:180.0
## Max. :33.90 Max. :8.000 Max. :472.0 Max. :335.0
## drat wt qsec vs
## Min. :2.760 Min. :1.513 Min. :14.50 Min. :0.0000
## 1st Qu.:3.080 1st Qu.:2.581 1st Qu.:16.89 1st Qu.:0.0000
## Median :3.695 Median :3.325 Median :17.71 Median :0.0000
## Mean :3.597 Mean :3.217 Mean :17.85 Mean :0.4375
## 3rd Qu.:3.920 3rd Qu.:3.610 3rd Qu.:18.90 3rd Qu.:1.0000
## Max. :4.930 Max. :5.424 Max. :22.90 Max. :1.0000
## am gear carb
## Min. :0.0000 Min. :3.000 Min. :1.000
## 1st Qu.:0.0000 1st Qu.:3.000 1st Qu.:2.000
## Median :0.0000 Median :4.000 Median :2.000
## Mean :0.4062 Mean :3.688 Mean :2.812
## 3rd Qu.:1.0000 3rd Qu.:4.000 3rd Qu.:4.000
## Max. :1.0000 Max. :5.000 Max. :8.000
# Boxplots interactivos
p1 <- ggplot(mtcars, aes(x = "", y = mpg)) + geom_boxplot() + ggtitle("mpg")
p2 <- ggplot(mtcars, aes(x = "", y = hp)) + geom_boxplot() + ggtitle("hp")
p3 <- ggplot(mtcars, aes(x = "", y = wt)) + geom_boxplot() + ggtitle("wt")
subplot(ggplotly(p1), ggplotly(p2), ggplotly(p3), nrows = 1, margin = 0.05)
wt)loess_model1 <- loess(mpg ~ wt, data = mtcars)
mtcars$pred_loess1 <- predict(loess_model1)
p_loess1 <- ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
geom_line(aes(y = pred_loess1), color = "blue", size = 1.2) +
ggtitle("LOESS: mpg ~ wt")
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
ggplotly(p_loess1)
wt y
hp)loess_model2 <- loess(mpg ~ wt + hp, data = mtcars)
mtcars$loess_pred <- predict(loess_model2)
p_loess2 <- ggplot(mtcars, aes(x = mpg, y = loess_pred)) +
geom_point() +
geom_abline(slope = 1, intercept = 0, color = "red") +
ggtitle("Predicción LOESS vs Real")
ggplotly(p_loess2)
# Nuevo ejemplo de predicción
nuevo <- data.frame(wt = 3, hp = 110)
predict(loess_model2, newdata = nuevo)
## 1
## 20.46099
wt)set.seed(123)
rf1 <- randomForest(mpg ~ wt, data = mtcars, importance = TRUE)
print(rf1)
##
## Call:
## randomForest(formula = mpg ~ wt, data = mtcars, importance = TRUE)
## Type of random forest: regression
## Number of trees: 500
## No. of variables tried at each split: 1
##
## Mean of squared residuals: 10.0435
## % Var explained: 71.46
wt y
hp)rf2 <- randomForest(mpg ~ wt + hp, data = mtcars, importance = TRUE)
print(rf2)
##
## Call:
## randomForest(formula = mpg ~ wt + hp, data = mtcars, importance = TRUE)
## Type of random forest: regression
## Number of trees: 500
## No. of variables tried at each split: 1
##
## Mean of squared residuals: 5.932878
## % Var explained: 83.14
varImpPlot(rf2)
predict(rf2, newdata = data.frame(wt = 3, hp = 110))
## 1
## 21.15276
Para explorar las relaciones entre las variables del conjunto de datos, creamos un mapa de calor interactivo de la matriz de correlación.
cor_matrix <- cor(mtcars)
p_corr <- plot_ly(
x = colnames(cor_matrix),
y = colnames(cor_matrix),
z = cor_matrix,
type = "heatmap",
colorscale = "RdBu",
zmin = -1, zmax = 1
) %>%
layout(
title = "Correlation Matrix of mtcars Variables",
xaxis = list(title = ""),
yaxis = list(title = "")
)
p_corr
Una matriz de diagrama de dispersión ayuda a visualizar las
relaciones por pares entre mpg, wt y
hp.
p_scatter <- plot_ly(mtcars) %>%
add_trace(
x = ~wt, y = ~mpg, type = "scatter", mode = "markers",
name = "wt vs mpg", marker = list(color = "blue")
) %>%
add_trace(
x = ~hp, y = ~mpg, type = "scatter", mode = "markers",
name = "hp vs mpg", marker = list(color = "red")
) %>%
add_trace(
x = ~wt, y = ~hp, type = "scatter", mode = "markers",
name = "wt vs hp", marker = list(color = "green")
) %>%
layout(
title = "Scatter Plot Matrix: mpg, wt, hp",
xaxis = list(title = "wt / hp"),
yaxis = list(title = "mpg / hp")
)
p_scatter
##5.3 Gráficos de residuos para la evaluación de modelos
Gráficos de residuos para modelos LOESS y de Bosque Aleatorio para evaluar errores de predicción.
# Calculate residuals
mtcars$loess_resid <- mtcars$mpg - mtcars$loess_pred
mtcars$rf_pred <- predict(rf2)
mtcars$rf_resid <- mtcars$mpg - mtcars$rf_pred
# LOESS Residual Plot
p_resid_loess <- ggplot(mtcars, aes(x = loess_pred, y = loess_resid)) +
geom_point() +
geom_hline(yintercept = 0, color = "red") +
ggtitle("LOESS Residuals") +
xlab("Predicted mpg") + ylab("Residuals")
p_resid_loess <- ggplotly(p_resid_loess)
# Random Forest Residual Plot
p_resid_rf <- ggplot(mtcars, aes(x = rf_pred, y = rf_resid)) +
geom_point() +
geom_hline(yintercept = 0, color = "red") +
ggtitle("Random Forest Residuals") +
xlab("Predicted mpg") + ylab("Residuals")
p_resid_rf <- ggplotly(p_resid_rf)
subplot(p_resid_loess, p_resid_rf, nrows = 1, margin = 0.05, titleX = TRUE, titleY = TRUE)
##5.4 Gráfico interactivo de importancia de variables para el modelo de Bosque aleatorio
Versión interactiva del gráfico de importancia de variables para el modelo de Bosque aleatorio.
imp <- as.data.frame(importance(rf2))
imp$Variable <- rownames(imp)
p_varimp <- plot_ly(
data = imp,
x = ~`%IncMSE`, y = ~Variable, type = "bar",
marker = list(color = "lightgreen")
) %>%
layout(
title = "Random Forest Variable Importance",
xaxis = list(title = "% Increase in MSE"),
yaxis = list(title = "Variable")
)
p_varimp
Un diagrama de dispersión 3D para visualizar la relación entre mpg, wt y hp con la superficie de predicción LOESS.
p_3d <- plot_ly(mtcars) %>%
add_markers(
x = ~wt, y = ~hp, z = ~mpg,
marker = list(size = 5, color = ~mpg, colorscale = "Viridis"),
name = "Actual"
) %>%
add_markers(
x = ~wt, y = ~hp, z = ~loess_pred,
marker = list(size = 5, color = "red", opacity = 0.5),
name = "Predicted"
) %>%
layout(
title = "3D Scatter: mpg vs wt and hp (LOESS Predictions)",
scene = list(
xaxis = list(title = "wt"),
yaxis = list(title = "hp"),
zaxis = list(title = "mpg")
)
)
p_3d