En el presente análisis se busca a través del conjunto de datos: “TABLON_ENTRENAMIENTO.csv”, entrenar un modelo que realice la predicción de la variable TARGET considerando los inputs dados de las variables (VAR1, VAR2, VAR3, VAR4) del conjunto de datos.
Se aplicaron el modelo de regresión polinómica y el random forest y para probar ambos modelos,se utilizaron los datos contenidos en TABLON_VALIDACION.csv.
setwd("C:/Users/massi/OneDrive/Documents/MASTER BIG DATA E INTELIGENCIA DE NEGOCIOS/Asignatura 3 Tecnicas de analisis de datos/Foro docente Asig. 3 - Tarea Individual")
library(ggplot2)
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(GGally)
## Registered S3 method overwritten by 'GGally':
## method from
## +.gg ggplot2
library(rpart)
library(rpart.plot)
library(randomForest)
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
##
## Attaching package: 'randomForest'
## The following object is masked from 'package:dplyr':
##
## combine
## The following object is masked from 'package:ggplot2':
##
## margin
library(caret)
## Loading required package: lattice
library(mltools)
library(e1071)
##
## Attaching package: 'e1071'
## The following object is masked from 'package:mltools':
##
## skewness
train <- read.csv("TABLON_ENTRENAMIENTO.csv", stringsAsFactors = FALSE,header = TRUE,sep = ";" )
test <- read.csv("TABLON_VALIDACION.csv", stringsAsFactors = FALSE,header = TRUE,sep = ";") #crear nuevo dataset con ambos conjuntos de datos
full <- bind_rows(train,test)
LT=dim(train)[1]
#Revisar la estructura
str(full)
## 'data.frame': 5400 obs. of 5 variables:
## $ TARGET: num 0.128 0.138 0.167 0.277 0.376 ...
## $ VAR1 : int 1 2 3 4 5 6 7 8 9 10 ...
## $ VAR2 : num 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 ...
## $ VAR3 : int 1 1 1 1 1 1 1 1 1 1 ...
## $ VAR4 : int 300 300 300 300 300 300 300 300 300 300 ...
summary(full)
## TARGET VAR1 VAR2 VAR3 VAR4
## Min. :0.1277 Min. : 1.0 Min. : 0.500 Min. :1.000 Min. :300
## 1st Qu.:2.2517 1st Qu.:13.0 1st Qu.: 0.950 1st Qu.:1.000 1st Qu.:300
## Median :3.6129 Median :25.5 Median : 3.250 Median :3.000 Median :400
## Mean :3.0982 Mean :25.5 Mean : 4.004 Mean :3.333 Mean :400
## 3rd Qu.:4.2307 3rd Qu.:38.0 3rd Qu.: 6.375 3rd Qu.:6.000 3rd Qu.:500
## Max. :4.6191 Max. :50.0 Max. :10.000 Max. :6.000 Max. :500
#Verificar si hay valores nulos o NAs en dataset: Full
colSums(is.na(full))
## TARGET VAR1 VAR2 VAR3 VAR4
## 0 0 0 0 0
#Revisar número de observaciones únicas en cada variable
apply(full,2, function(x) length(unique(x)))
## TARGET VAR1 VAR2 VAR3 VAR4
## 5397 50 12 3 3
Todos los datos están completos, no hay valores nulos o NAs y todas las variables son numéricas.
Ahora procedemos a escalar todos los datos del dataset full
full$TARGET <- scale(full$TARGET)
full$VAR1 <- scale(full$VAR1)
full$VAR2 <- scale(full$VAR2)
full$VAR3 <- scale(full$VAR3)
full$VAR4 <- scale(full$VAR4)
#Escalar datos de data set: Test y Train
Histogramas de cada variable del dataset full:
hist(full$TARGET,main="Histograma de la variable TARGET",xlab="TARGET",ylab="Frecuencia",col="Blue")
hist(full$VAR1,main="Histograma de la variable VAR1",xlab="VAR1",ylab="Frecuencia",col="Blue")
hist(full$VAR2,main="Histograma de la variable VAR2",xlab="VAR2",ylab="Frecuencia",col="Blue")
hist(full$VAR3,main="Histograma de la variable VAR3",xlab="VAR3",ylab="Frecuencia",col="Blue")
hist(full$VAR4,main="Histograma de la variable VAR4",xlab="VAR4",ylab="Frecuencia",col="Blue")
Gráfico de cajas del conjunto de datos
boxplot(full, col = "skyblue", border = "black",
xlab = "Variables", ylab = "Valores", main = "Boxplot de Variables")
En los gráficos (Histograma y Boxplot) se muestra poca variabilidad y dispersión de los datos en las variables VAR3 y VAR4.
modelo_polinomico <- lm(TARGET ~ poly(VAR1+VAR2+VAR3+VAR4, degree = 2), data = train)
summary(modelo_polinomico)
##
## Call:
## lm(formula = TARGET ~ poly(VAR1 + VAR2 + VAR3 + VAR4, degree = 2),
## data = train)
##
## Residuals:
## Min 1Q Median 3Q Max
## -3.0564 -0.8370 0.4696 1.0954 1.6978
##
## Coefficients:
## Estimate Std. Error t value
## (Intercept) 3.05931 0.02445 125.130
## poly(VAR1 + VAR2 + VAR3 + VAR4, degree = 2)1 10.03793 1.37219 7.315
## poly(VAR1 + VAR2 + VAR3 + VAR4, degree = 2)2 -1.18827 1.37219 -0.866
## Pr(>|t|)
## (Intercept) < 2e-16 ***
## poly(VAR1 + VAR2 + VAR3 + VAR4, degree = 2)1 3.24e-13 ***
## poly(VAR1 + VAR2 + VAR3 + VAR4, degree = 2)2 0.387
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.372 on 3147 degrees of freedom
## Multiple R-squared: 0.01695, Adjusted R-squared: 0.01633
## F-statistic: 27.13 on 2 and 3147 DF, p-value: 2.077e-12
Predicción del modelo
predicciones_modelo.polinomico <- predict(modelo_polinomico, newdata = test)
Métricas de rendimiento
#MSE
mse <- mean((test$TARGET - predicciones_modelo.polinomico)^2)
print(mse)
## [1] 1.946968
#R cuadrado Score
r_cuadrado <- 1 - sum((test$TARGET - predicciones_modelo.polinomico)^2) / sum((test$TARGET - mean(test$TARGET))^2)
print(r_cuadrado)
## [1] 0.01244817
El modelo de regresión polinómica con grado 2, no explica bien la variabilidad de los datos puesto que el resultado de R cuadrado no es próximo a 1. No hay un buen ajuste del modelo. Se intentará ajustar el modelo de regresión polinómica a grado 5.
modelo_polinomico.2 <- lm(TARGET ~ poly(VAR1+VAR2+VAR3+VAR4, degree = 5), data = train)
summary(modelo_polinomico.2)
##
## Call:
## lm(formula = TARGET ~ poly(VAR1 + VAR2 + VAR3 + VAR4, degree = 5),
## data = train)
##
## Residuals:
## Min 1Q Median 3Q Max
## -3.9337 -0.4360 0.2627 0.7601 2.2735
##
## Coefficients:
## Estimate Std. Error t value
## (Intercept) 3.05931 0.01793 170.584
## poly(VAR1 + VAR2 + VAR3 + VAR4, degree = 5)1 10.03793 1.00656 9.972
## poly(VAR1 + VAR2 + VAR3 + VAR4, degree = 5)2 -1.18827 1.00656 -1.181
## poly(VAR1 + VAR2 + VAR3 + VAR4, degree = 5)3 38.35946 1.00656 38.109
## poly(VAR1 + VAR2 + VAR3 + VAR4, degree = 5)4 -6.50474 1.00656 -6.462
## poly(VAR1 + VAR2 + VAR3 + VAR4, degree = 5)5 35.01965 1.00656 34.791
## Pr(>|t|)
## (Intercept) < 2e-16 ***
## poly(VAR1 + VAR2 + VAR3 + VAR4, degree = 5)1 < 2e-16 ***
## poly(VAR1 + VAR2 + VAR3 + VAR4, degree = 5)2 0.238
## poly(VAR1 + VAR2 + VAR3 + VAR4, degree = 5)3 < 2e-16 ***
## poly(VAR1 + VAR2 + VAR3 + VAR4, degree = 5)4 1.19e-10 ***
## poly(VAR1 + VAR2 + VAR3 + VAR4, degree = 5)5 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.007 on 3144 degrees of freedom
## Multiple R-squared: 0.4715, Adjusted R-squared: 0.4707
## F-statistic: 561.1 on 5 and 3144 DF, p-value: < 2.2e-16
Predicción del modelo
predicciones_modelo.polinomico.2 <- predict(modelo_polinomico.2, newdata = test)
Métricas de rendimiento
#MSE
mse.2 <- mean((test$TARGET - predicciones_modelo.polinomico.2)^2)
print(mse.2)
## [1] 1.017319
#Varianza objetivo de la variable TARGET
varianza_objetivo <- var(test$TARGET)
print(varianza_objetivo)
## [1] 1.972387
#R cuadrado Score
r_cuadrado.2 <- 1 - sum((test$TARGET - predicciones_modelo.polinomico.2)^2) / sum((test$TARGET - mean(test$TARGET))^2)
print(r_cuadrado.2)
## [1] 0.4839899
Realizando el ajuste a grado 5, el R cuadrado resulta de un 0.48 y El MSE es menor que la varianza de la variable objetivo. Sin embargo, R cuadrado resultó 0.48 lo que indica que el modelo está generando predicciones no tan cercanas a los valores de TARGET.
modelo.forest <- randomForest(TARGET ~ .,
data = train,
ntree = 3,
mtry = 2,
replace = TRUE)
print(modelo.forest)
##
## Call:
## randomForest(formula = TARGET ~ ., data = train, ntree = 3, mtry = 2, replace = TRUE)
## Type of random forest: regression
## Number of trees: 3
## No. of variables tried at each split: 2
##
## Mean of squared residuals: 0.08413289
## % Var explained: 95.6
Predicción del modelo
predicciones_modelo.forest <- predict(modelo.forest, newdata = test)
Métricas de rendimiento
#MSE
mse.3 <- mean((test$TARGET - predicciones_modelo.forest)^2)
print(mse.3)
## [1] 0.03176323
#R cuadrado Score
r_cuadrado.3 <- 1 - sum((test$TARGET - predicciones_modelo.forest)^2) / sum((test$TARGET - mean(test$TARGET))^2)
print(r_cuadrado.3)
## [1] 0.9838889
Este modelo tiene un alto rendimiento, basado en los resultados de MSE y R cuadrado, el modelo tiene buena precisión ya que las predicciones de TARGET están cerca de los valores reales. El modelo se ajusta a los datos.Además, el resultado de R cuadrado de 0.98 implica que el 98% de la variabilidad en la variable objetivo se explica por el modelo.
Luego de generar los modelos de regresión polinómica y random forest, se determina que el modelo de mayor rendimiento es el random forest fundamentándose en los resultados de MSE y R cuadrado y la naturaleza de las observaciones contenidas en TARGET (una variable cuantitativa continua).