La regresión lineal es un método supervisado de análisis de datos que busca modelar la relación entre una variable dependiente y una o más variables independientes mediante la ecuación de una línea recta. Este método es útil para predecir valores y comprender las relaciones entre variables, permitiendo identificar tendencias y patrones en los datos.
#Importamos los datos
library(readxl)
## Warning: package 'readxl' was built under R version 4.3.3
train_1 <- read_excel("C:/Users/Valeria/Downloads/train_1.xlsx")
View(train_1)
library(readxl)
test_2 <- read_excel("C:/Users/Valeria/Downloads/test_2.xlsx")
View(test_2)
#Verificar estructura de Datos
str(train_1)
## tibble [1,460 × 11] (S3: tbl_df/tbl/data.frame)
## $ Id : num [1:1460] 1 2 3 4 5 6 7 8 9 10 ...
## $ LotArea : num [1:1460] 8450 9600 11250 9550 14260 ...
## $ Utilities : chr [1:1460] "AllPub" "AllPub" "AllPub" "AllPub" ...
## $ BldgType : chr [1:1460] "1Fam" "1Fam" "1Fam" "1Fam" ...
## $ YearBuilt : num [1:1460] 2003 1976 2001 1915 2000 ...
## $ FullBath : num [1:1460] 2 2 2 1 2 1 2 2 2 1 ...
## $ BedroomAbvGr: num [1:1460] 3 3 3 3 4 1 3 3 2 2 ...
## $ KitchenQual : chr [1:1460] "Gd" "TA" "Gd" "Gd" ...
## $ GarageCars : num [1:1460] 2 2 2 3 3 2 2 2 2 1 ...
## $ Fence : chr [1:1460] "NA" "NA" "NA" "NA" ...
## $ SalePrice : num [1:1460] 208500 181500 223500 140000 250000 ...
str(test_2)
## tibble [1,459 × 11] (S3: tbl_df/tbl/data.frame)
## $ Id : num [1:1459] 1461 1462 1463 1464 1465 ...
## $ LotArea : num [1:1459] 11622 14267 13830 9978 5005 ...
## $ Utilities : chr [1:1459] "AllPub" "AllPub" "AllPub" "AllPub" ...
## $ BldgType : chr [1:1459] "1Fam" "1Fam" "1Fam" "1Fam" ...
## $ YearBuilt : num [1:1459] 1961 1958 1997 1998 1992 ...
## $ FullBath : num [1:1459] 1 1 2 2 2 2 2 2 1 1 ...
## $ BedroomAbvGr: num [1:1459] 2 3 3 3 2 3 3 3 2 2 ...
## $ KitchenQual : chr [1:1459] "TA" "Gd" "TA" "Gd" ...
## $ GarageCars : num [1:1459] 1 1 2 2 2 2 2 2 2 2 ...
## $ Fence : chr [1:1459] "MnPrv" "NA" "MnPrv" "NA" ...
## $ SalePrice : num [1:1459] 169277 187758 183584 179317 150730 ...
## Creamos modelo de regresión lineal
regresion<- lm(SalePrice ~ LotArea + YearBuilt +
FullBath + KitchenQual+ Utilities + BldgType +
BedroomAbvGr + GarageCars + Fence , data = train_1)
# Resumen del modelo
summary(regresion)
##
## Call:
## lm(formula = SalePrice ~ LotArea + YearBuilt + FullBath + KitchenQual +
## Utilities + BldgType + BedroomAbvGr + GarageCars + Fence,
## data = train_1)
##
## Residuals:
## Min 1Q Median 3Q Max
## -227612 -24800 -3913 18135 361080
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -5.727e+05 1.072e+05 -5.343 1.06e-07 ***
## LotArea 1.099e+00 1.243e-01 8.847 < 2e-16 ***
## YearBuilt 3.727e+02 5.498e+01 6.778 1.78e-11 ***
## FullBath 2.910e+04 2.971e+03 9.793 < 2e-16 ***
## KitchenQualFa -1.222e+05 9.372e+03 -13.038 < 2e-16 ***
## KitchenQualGd -9.517e+04 4.968e+03 -19.155 < 2e-16 ***
## KitchenQualTA -1.226e+05 5.428e+03 -22.587 < 2e-16 ***
## UtilitiesNoSeWa -4.624e+04 4.524e+04 -1.022 0.306822
## BldgType2fmCon -1.637e+04 8.524e+03 -1.921 0.054927 .
## BldgTypeDuplex -3.952e+04 6.676e+03 -5.920 4.03e-09 ***
## BldgTypeTwnhs -3.061e+04 7.271e+03 -4.210 2.71e-05 ***
## BldgTypeTwnhsE -1.741e+04 4.931e+03 -3.531 0.000427 ***
## BedroomAbvGr 6.803e+03 1.760e+03 3.864 0.000116 ***
## GarageCars 2.872e+04 2.076e+03 13.832 < 2e-16 ***
## FenceGdWo -3.141e+03 8.578e+03 -0.366 0.714297
## FenceMnPrv -2.667e+03 6.944e+03 -0.384 0.701012
## FenceMnWw -8.503e+03 1.489e+04 -0.571 0.568143
## FenceNA -7.823e+02 6.084e+03 -0.129 0.897706
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 45120 on 1442 degrees of freedom
## Multiple R-squared: 0.6812, Adjusted R-squared: 0.6774
## F-statistic: 181.2 on 17 and 1442 DF, p-value: < 2.2e-16
#Validando las predicciones (Test/Prueba)
library(caTools)
## Warning: package 'caTools' was built under R version 4.3.3
set.seed(123)
split = sample.split(train_1$SalePrice, SplitRatio = 0.7)
trainset = subset(train_1, split == TRUE)
testset = subset(train_1, split == FALSE)
# Utilizar test_2 como conjunto de prueba
testset = test_2
# Ajustar modelo de regresión lineal al conjunto de entrenamiento
lm_model = lm(formula = SalePrice ~ LotArea + YearBuilt +
FullBath + BldgType + BedroomAbvGr + GarageCars , data = trainset)
coef(lm_model)
## (Intercept) LotArea YearBuilt FullBath BldgType2fmCon
## -995312.7472 1.2984 521.0203 44055.4421 -21493.4915
## BldgTypeDuplex BldgTypeTwnhs BldgTypeTwnhsE BedroomAbvGr GarageCars
## -58090.8169 -40725.6046 -21379.2431 254.2989 41380.7007
# Analizando Resultados con los datos de Prueba
ypred = predict(lm_model, newdata = testset)
#Grafiquemos los resultados (entrenamiento) - LotArea Vs SalePrice
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.3.3
ggplot() +
geom_point(aes(x = trainset$LotArea, y = trainset$SalePrice), colour = 'red') +
geom_line(aes(x = trainset$LotArea, y = predict(lm_model, newdata = trainset)), colour = 'blue') +
ggtitle('Precio de Venta vs Tamaño de Lote (Entrenamiento)') +
xlab('Tamaño de Lote') +
ylab('Precio de Venta')
#Grafiquemos los resultados (entrenamiento) - YearBuilt Vs SalePrice
ggplot(data = trainset, aes(x = YearBuilt, y = SalePrice)) + geom_point() +
geom_smooth(method = "lm", se = TRUE, color = "firebrick") +
theme_bw() + labs(x = "Año de Construccion", y = "Precio de Venta")
## `geom_smooth()` using formula = 'y ~ x'
#Grafiquemos los resultados (prueba) - YearBuilt Vs SalePrice
ggplot() + geom_point(aes(x = testset$YearBuilt, y = testset$SalePrice),
colour = 'blue') +
geom_line(aes(x = testset$YearBuilt, y = predict(lm_model, newdata = testset)),
colour = 'red') +
ggtitle('Año de construccion vs Tamaño de Lote (Prueba)') +
xlab('Año de construccion') +
ylab('Precio de Venta')
#Grafiquemos los resultados (prueba) - LotArea Vs SalePrice
ggplot(data = testset, aes(x = LotArea, y = SalePrice)) + geom_point() +
geom_smooth(method = "lm", se = TRUE, color = "firebrick") +
theme_bw() + labs(x = "Tamaño de Lote", y = "Precio de Venta")
## `geom_smooth()` using formula = 'y ~ x'
#Diagnostico del modelo
residuos <- rstandard(regresion)
valores.ajustados <- fitted(regresion)
plot(valores.ajustados, residuos)
En el analisis de los datos de finca raiz en los Estados Unidos, pudimos identificar que las variables como el precio de venta, tamaño del lote, tipo de vivienda,Años de construccion, entre otras son significativas para determinar una casa idonea para la compra/venta.