Librerias
library(caret)
library(ggplot2)
library(lattice)
library(rpart)
library(rpart.plot)
library(party)
library(gmodels)
library(grid)
library(mvtnorm)
library(modeltools)
library(stats4)
library(dplyr)
library(strucchange)
library(zoo)
library(Metrics)
library(Hmisc)
Base de datos
bd <- read.csv("C:\\Users\\maria\\OneDrive\\Desktop\\AD 2023\\PERIODO 2\\DATA MINING\\Datos bienes y raices CDMXF.csv", stringsAsFactors = TRUE)
bd$Estacionamiento <- as.numeric(bd$Estacionamiento)
bd$Precio <- as.numeric(bd$Precio)
Limpieza de datos
conteorango <- sum(bd$Precio >= 0 & bd$Precio < 100, na.rm = TRUE)
conteorango
## [1] 1
bd$Precio <- replace(bd$Precio, bd$Precio >= 0 & bd$Precio < 100, NA)
bd$Precio[is.na(bd$Precio)] <- median(bd$Precio, na.rm = TRUE)
#Eliminar valores extremos adicionales usando el rango intercuartil
q1 <- quantile(bd$Precio, 0.25, na.rm=TRUE)
q3 <- quantile(bd$Precio, 0.75, na.rm=TRUE)
rangointq <- q3 - q1
limite_inferior <- q1 - 1.5 * rangointq
limite_superior <- q3 + 1.5 * rangointq
bd <- subset(bd, Precio >= limite_inferior & Precio <= limite_superior)
summary(bd$Precio)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 116.0 828.8 1712.5 2982.1 4212.5 12500.0
# Cambiar los valores
bd$Cocina_equip <- gsub("Sí|Si ", "Si", bd$Cocina_equip)
bd$Gimnasio <- gsub("Sí|Si ", "Si", bd$Gimnasio)
bd$Amueblado <- gsub("Sí|Si ", "Si", bd$Amueblado)
bd$Alberca <- gsub("Sí|Si ", "Si", bd$Alberca)
bd$Alberca <- gsub("si|si ", "Si", bd$Alberca)
bd$Terraza <- gsub("Sí|Si ", "Si", bd$Terraza)
bd$Elevador <- gsub("Sí|Si ", "Si", bd$Elevador)
bd$Elevador <- gsub("si|si ", "Si", bd$Elevador)
bd$Cocina_equip <- gsub("No ", "No", bd$Cocina_equip)
bd$Gimnasio <- gsub("No ", "No", bd$Gimnasio)
bd$Amueblado <- gsub("No ", "No", bd$Amueblado)
bd$Alberca <- gsub("No ", "No", bd$Alberca)
bd$Terraza <- gsub("No ", "No", bd$Terraza)
bd$Elevador <- gsub("No ", "No", bd$Elevador)
unique(bd$Gimnasio)
## [1] "Si" "No"
# Visualizar los datos
summary(bd)
## Alcaldia Colonia X1
## Iztapalapa : 94 Santa Fe : 22 Min. :0.350
## Tlahuac : 82 San Angel : 13 1st Qu.:1.020
## Alvaro Obregon : 79 San Jer\xf3nimo L\xedndice: 11 Median :1.400
## Gustavo A. Madero : 79 Miguel Hidalgo : 11 Mean :1.385
## Coyoacan : 45 Lomas Estrella : 10 3rd Qu.:1.550
## Venustiano Carranza: 33 Tepalcates : 10 Max. :2.800
## (Other) :192 (Other) :527
## X2 X3 X4 X5
## Min. :3.810 Min. :31.70 Min. : 6.07 Min. :18.46
## 1st Qu.:4.980 1st Qu.:40.21 1st Qu.:16.35 1st Qu.:24.42
## Median :5.620 Median :42.85 Median :18.21 Median :26.78
## Mean :5.353 Mean :42.59 Mean :17.49 Mean :26.63
## 3rd Qu.:5.680 3rd Qu.:46.56 3rd Qu.:20.05 3rd Qu.:28.25
## Max. :6.780 Max. :51.23 Max. :23.46 Max. :32.20
##
## X6 X7 X8 X9
## Min. :0.480 Min. : 0.030 Min. :0.02000 Min. : 3.170
## 1st Qu.:2.280 1st Qu.: 0.280 1st Qu.:0.03000 1st Qu.: 6.980
## Median :3.190 Median : 0.300 Median :0.05000 Median : 8.250
## Mean :3.484 Mean : 1.075 Mean :0.08091 Mean : 8.007
## 3rd Qu.:4.540 3rd Qu.: 0.710 3rd Qu.:0.10000 3rd Qu.: 9.560
## Max. :8.530 Max. :10.210 Max. :0.23000 Max. :13.060
##
## X10 Cocina_equip Gimnasio Amueblado
## Min. :15.15 Length:604 Length:604 Length:604
## 1st Qu.:36.60 Class :character Class :character Class :character
## Median :43.86 Mode :character Mode :character Mode :character
## Mean :41.10
## 3rd Qu.:50.08
## Max. :63.97
##
## Alberca Terraza Elevador m2_construido
## Length:604 Length:604 Length:604 Min. : 34.00
## Class :character Class :character Class :character 1st Qu.: 56.75
## Mode :character Mode :character Mode :character Median : 70.00
## Mean : 88.01
## 3rd Qu.:100.00
## Max. :450.00
##
## Banos Recamaras Estacionamiento Precio
## Min. :1.00 Min. :1.000 Min. :1.000 Min. : 116.0
## 1st Qu.:1.00 1st Qu.:2.000 1st Qu.:2.000 1st Qu.: 828.8
## Median :1.00 Median :2.000 Median :2.000 Median : 1712.5
## Mean :1.56 Mean :2.262 Mean :2.295 Mean : 2982.1
## 3rd Qu.:2.00 3rd Qu.:3.000 3rd Qu.:3.000 3rd Qu.: 4212.5
## Max. :5.00 Max. :5.000 Max. :7.000 Max. :12500.0
##
#Conversión a factores
for (i in colnames(bd)) {
if (is.character(bd[[i]])) {
bd[[i]] <- as.factor(bd[[i]])
}
}
# Visualizar los datos
summary(bd)
## Alcaldia Colonia X1
## Iztapalapa : 94 Santa Fe : 22 Min. :0.350
## Tlahuac : 82 San Angel : 13 1st Qu.:1.020
## Alvaro Obregon : 79 San Jer\xf3nimo L\xedndice: 11 Median :1.400
## Gustavo A. Madero : 79 Miguel Hidalgo : 11 Mean :1.385
## Coyoacan : 45 Lomas Estrella : 10 3rd Qu.:1.550
## Venustiano Carranza: 33 Tepalcates : 10 Max. :2.800
## (Other) :192 (Other) :527
## X2 X3 X4 X5
## Min. :3.810 Min. :31.70 Min. : 6.07 Min. :18.46
## 1st Qu.:4.980 1st Qu.:40.21 1st Qu.:16.35 1st Qu.:24.42
## Median :5.620 Median :42.85 Median :18.21 Median :26.78
## Mean :5.353 Mean :42.59 Mean :17.49 Mean :26.63
## 3rd Qu.:5.680 3rd Qu.:46.56 3rd Qu.:20.05 3rd Qu.:28.25
## Max. :6.780 Max. :51.23 Max. :23.46 Max. :32.20
##
## X6 X7 X8 X9
## Min. :0.480 Min. : 0.030 Min. :0.02000 Min. : 3.170
## 1st Qu.:2.280 1st Qu.: 0.280 1st Qu.:0.03000 1st Qu.: 6.980
## Median :3.190 Median : 0.300 Median :0.05000 Median : 8.250
## Mean :3.484 Mean : 1.075 Mean :0.08091 Mean : 8.007
## 3rd Qu.:4.540 3rd Qu.: 0.710 3rd Qu.:0.10000 3rd Qu.: 9.560
## Max. :8.530 Max. :10.210 Max. :0.23000 Max. :13.060
##
## X10 Cocina_equip Gimnasio Amueblado Alberca Terraza Elevador
## Min. :15.15 No: 62 No:456 No:591 No:524 No:338 No:295
## 1st Qu.:36.60 Si:542 Si:148 Si: 13 Si: 80 Si:266 Si:309
## Median :43.86
## Mean :41.10
## 3rd Qu.:50.08
## Max. :63.97
##
## m2_construido Banos Recamaras Estacionamiento
## Min. : 34.00 Min. :1.00 Min. :1.000 Min. :1.000
## 1st Qu.: 56.75 1st Qu.:1.00 1st Qu.:2.000 1st Qu.:2.000
## Median : 70.00 Median :1.00 Median :2.000 Median :2.000
## Mean : 88.01 Mean :1.56 Mean :2.262 Mean :2.295
## 3rd Qu.:100.00 3rd Qu.:2.00 3rd Qu.:3.000 3rd Qu.:3.000
## Max. :450.00 Max. :5.00 Max. :5.000 Max. :7.000
##
## Precio
## Min. : 116.0
## 1st Qu.: 828.8
## Median : 1712.5
## Mean : 2982.1
## 3rd Qu.: 4212.5
## Max. :12500.0
##
Obsevaciones: - En la variable de precio, los valores aparecen estár en dolares por lo cual es necesario hacer una transformación de los datos. Tomaremos la tasa de dolares actual el cual es el 1 USD = 17.46 MX. Sin embargo los numeros son muy bajos, por lo cual es necesario hacer una mayor investigación para poder encontrar el trasfondo de esto. - Existen varias variables con valores de texto como lo son: estacionamieto, elevador, Cocina_equip, Gimnasio, Amueblado, Alcaldia y Colonia. Cada una de estas se debe de tratar de una manera diferente. - Las variables categóricas son: Cocina_equip, Gimnasio, Amueblado, Alberca, Terraza, Estacionamiento y Elevador. Estas variables se deberán de transformar en factores para poder ser analizadas. - Se analizo el caso de las variables podemos ver que en la base de datos se enlistan 16 Alcaldías y 313 colonias. Cambiaremos la variable colonia a factor para poder meterlas en el análisis. - Tras haber considerado el caso de la variable colonia, se llego a la conclusión que esta es una variable muy importante dado que hay colonias de muy buen nombre que aumentan el valor de una propiedad y otras que lo disminuyen. Por lo cual aunque sean 313 registros únicos, se trasnformará esta variable a factor para poder utilizarla durante el modelo.
Clusterizacion
# Seleccionar solo las variables numéricas
datos <- bd[sapply(bd, is.numeric)]
columnas_a_excluir <- c("Precio", "m2_construido", "Banos", "Recamaras", "Estacionamiento")
datos <- datos[, !names(datos) %in% columnas_a_excluir]
# Escalar las variables numéricas
datos_escalados <- scale(datos[, 1:10])
# Calcular las medianas de las variables numéricas escaladas
medianas <- apply(datos_escalados, 2, median)
set.seed(123) # Para reproducibilidad
k <- 3 # Cambia este valor por el número de clusters que deseas
kmeans_model <- kmeans(datos_escalados, centers = k, nstart = 100)
print(kmeans_model)
## K-means clustering with 3 clusters of sizes 227, 295, 82
##
## Cluster means:
## X1 X2 X3 X4 X5 X6 X7
## 1 0.9460259 -0.4955174 0.9850028 0.8946752 0.9406937 1.0355970 0.4666946
## 2 -0.2802831 0.3391070 -0.2066299 -0.1353385 -0.4020742 -0.4077093 -0.2267267
## 3 -1.6105412 0.1517789 -1.9834121 -1.9898343 -1.1576289 -1.4000766 -0.4762841
## X8 X9 X10
## 1 1.1493586 0.8274492 1.0026138
## 2 -0.6254214 -0.1490393 -0.2595404
## 3 -0.9317692 -1.7544436 -1.8418161
##
## Clustering vector:
## 1 2 4 5 6 8 9 10 11 12 13 14 15 17 18 19 20 21 22 23
## 1 1 1 1 1 2 1 2 1 2 2 1 3 2 3 2 2 3 1 2
## 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 42 43 44 45
## 2 1 2 2 1 1 2 1 1 2 2 1 2 2 1 2 1 2 2 2
## 46 47 49 50 51 53 54 55 56 57 58 61 62 63 64 65 66 67 68 69
## 2 2 2 1 1 2 3 2 1 3 3 1 1 2 1 3 1 2 1 2
## 70 71 72 73 74 75 76 77 78 82 83 84 85 86 87 88 89 90 91 92
## 2 1 2 2 2 2 2 2 1 1 2 2 1 3 2 2 1 2 2 1
## 94 96 97 98 99 100 101 102 103 104 105 106 107 108 110 111 112 113 115 116
## 2 2 1 1 2 3 1 3 1 2 2 1 2 3 1 1 2 2 3 2
## 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
## 1 2 1 2 2 2 1 2 1 2 1 1 2 2 2 2 1 3 3 3
## 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
## 1 1 2 3 2 1 3 1 1 2 2 2 2 2 1 2 2 1 1 1
## 157 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
## 3 2 1 2 3 1 2 2 1 2 1 1 2 1 2 1 2 2 2 2
## 178 179 180 181 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
## 1 2 1 3 2 1 2 1 1 2 1 2 2 1 2 1 2 1 2 2
## 199 200 201 202 203 204 207 208 209 210 212 213 214 216 217 218 219 221 222 223
## 1 2 3 1 2 1 1 2 2 2 2 2 2 2 2 1 2 2 2 1
## 224 225 226 227 228 229 230 231 232 233 234 235 237 238 239 240 241 242 243 244
## 1 3 3 2 3 2 1 2 1 2 2 1 3 2 2 2 2 2 2 1
## 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 262 263 264 265
## 2 1 2 1 1 1 1 2 2 1 1 1 1 3 2 1 2 1 2 2
## 266 267 268 270 271 272 273 274 275 276 277 278 279 280 281 283 284 285 286 287
## 2 2 2 2 2 2 3 2 2 2 2 2 3 3 1 1 1 2 2 1
## 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
## 3 3 1 2 3 1 2 2 3 1 1 1 1 2 2 2 2 1 3 2
## 308 309 310 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
## 1 1 1 1 3 1 2 2 3 1 1 2 2 2 1 2 1 2 2 1
## 329 330 332 333 334 335 336 337 338 339 340 341 342 343 345 346 347 348 349 350
## 2 2 2 2 2 2 1 2 3 2 2 3 3 2 1 3 1 2 1 1
## 351 352 353 354 355 356 358 359 360 361 362 363 364 365 366 367 368 369 370 371
## 2 2 2 2 3 1 1 2 1 2 1 2 1 1 1 2 2 2 2 1
## 372 373 374 375 377 378 379 380 381 382 383 384 385 386 387 388 389 390 393 394
## 2 2 3 2 3 1 1 1 3 3 2 1 2 1 3 2 1 2 2 2
## 395 396 397 398 399 400 401 402 403 404 405 407 408 409 410 411 413 414 415 416
## 1 2 2 1 1 1 2 2 2 2 3 2 2 2 1 1 1 1 1 2
## 417 418 419 420 421 422 424 425 426 427 428 429 431 432 433 434 435 436 437 438
## 2 3 1 1 2 2 3 1 1 1 3 1 1 3 1 3 2 1 2 2
## 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
## 2 2 1 2 3 2 2 1 1 1 2 1 3 1 2 2 2 2 2 1
## 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
## 2 3 1 2 1 2 2 2 1 1 2 2 1 2 1 2 2 1 1 2
## 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 495 496 497 498 499
## 3 1 1 2 3 2 2 1 2 1 2 1 3 3 1 1 3 2 1 1
## 500 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
## 2 1 3 2 1 1 2 1 2 2 2 2 1 3 1 3 1 1 3 2
## 522 523 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
## 1 1 2 2 1 2 2 3 1 2 1 2 2 1 1 2 2 1 1 1
## 543 544 545 546 547 548 549 551 552 553 556 557 558 559 560 561 562 563 564 565
## 2 2 1 2 2 1 1 1 2 2 2 3 2 2 3 1 2 2 3 2
## 566 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 586 587 588
## 1 2 3 1 2 1 1 2 2 2 2 1 1 1 2 3 1 1 3 2
## 589 590 591 592 593 594 596 597 598 599 600 601 602 603 604 605 606 607 608 609
## 3 2 1 3 2 2 1 3 2 2 2 2 1 2 2 2 1 1 1 3
## 610 611 612 613 615 616 617 618 620 621 622 624 625 626 627 628 629 630 631 632
## 2 2 1 2 3 2 3 3 2 1 2 1 1 1 1 2 2 2 2 2
## 634 635 636 637 638 639 641 642 643 644 645 646 647 648 649 650 651 652 653 654
## 1 2 1 3 1 2 1 2 1 3 2 2 2 2 2 2 1 1 2 3
## 655 656 657 658
## 3 1 1 2
##
## Within cluster sum of squares by cluster:
## [1] 1112.2723 812.0914 185.9224
## (between_SS / total_SS = 65.0 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss" "tot.withinss"
## [6] "betweenss" "size" "iter" "ifault"
# Ajustar el modelo k-means para diferentes valores de k
set.seed(123) # Para reproducibilidad
wcss <- vector() # Inicializar vector para almacenar los valores de WCSS
max_k <- 10 # Puedes cambiar esto para probar con más clústeres si lo deseas
for (k in 1:max_k) {
kmeans_model2 <- kmeans(datos_escalados, centers = k, nstart = 25)
wcss[k] <- kmeans_model2$tot.withinss
}
# Graficar el método del codo
par(mar = c(4, 4, 1, 1)) # Los números representan los márgenes inferior, izquierdo, superior y derecho respectivamente.
plot(1:max_k, wcss, type = "b", xlab = "Numero de Clusters", ylab = "WCSS", main = "Metodo del Codo", pch = 19, frame = FALSE)
# Establecer una semilla para la reproducibilidad
set.seed(123)
# Realizar K-means con 5 clusters
kmeans_result <- kmeans(datos_escalados, centers = 5) #NOMBRAR CLUSTERS
kmeans_result$centers
## X1 X2 X3 X4 X5 X6
## 1 -1.61054123 0.1517789 -1.98341212 -1.9898343 -1.1576289 -1.4000766
## 2 0.83129248 -0.4176112 1.00262343 0.8901079 0.8774928 0.9141513
## 3 -0.01380956 -0.5973366 -0.46567348 0.1525445 -0.2913054 -0.3501166
## 4 0.92576834 -1.1314610 0.15396022 0.3263983 0.8817878 1.0629117
## 5 -0.44693327 0.9850995 -0.04668226 -0.2566352 -0.5587026 -0.5125792
## X7 X8 X9 X10
## 1 -0.47628407 -0.9317692 -1.7544436 -1.8418161
## 2 0.02205604 1.1037744 0.9104497 1.0211069
## 3 -0.36755174 -0.5325598 0.7087798 0.2237588
## 4 2.71141810 0.7286057 -0.4198435 0.1927141
## 5 -0.37914502 -0.7556900 -0.4421846 -0.4652172
# Tabla de centroides nos ayuda a definir el nombre del cluster
# en esta tabla estan todas las variables, tenemos que separar las relevantes.
# Añadir la columna de clusters al DataFrame original
bd2 <- bd
bd2$Cluster <- kmeans_result$cluster
NOMBRES DE CLUSTERS
cluster 1: POPULAR - valores positivos (9) - viviendas con hacinamieto (acumulacion de personas) - no disponen de energia electrica - no disponen de computadora
cluster 2: PLATA - valores positivos (1) - niños entre 6 y 14 años no asisten a la escuela - no hacinamiento - no analfabetas - educacion basica completa
cluster 3: BASICO - ninguna variable mayor a 1, pero si tienen algunas positivas (4) - niños entre 6 y 14 años si asisten a la escuela - si energia electrica - no celular
cluster 4: TRADICIONAL - ninguna variable mayor a 1, pero si tienen algunas positivas (3) - niños entre 6 y 14 años no asisten a la escuela - si energia electrica - si servicios de salud
cluster 5: PREMIUM - ninguna variable mayor a 1, pero si tienen una positivas (1) - no analfabetas - jovenes entre 15 y 24 si asisten a la escuela - si educacion basica - si servicios de salud - no hacinamiento - si celular - si computadora
Separar datos por clusters
datos2 <- bd2[, 13:24]
cluster1 <- datos2[datos2$Cluster == "1", ]
cluster2 <- datos2[datos2$Cluster == "2", ]
cluster3 <- datos2[datos2$Cluster == "3", ]
cluster4 <- datos2[datos2$Cluster == "4", ]
cluster5 <- datos2[datos2$Cluster == "5", ]
CART CLUSTER 1
# Establecer la semilla para reproducibilidad
set.seed(123)
# Paso 1: Dividir el conjunto de datos en entrenamiento (50%) y temporal (50%)
trainIndex1 <- createDataPartition(cluster1$Precio, p = 0.5, list = FALSE, times = 1)
train <- cluster1[trainIndex1, ]
temp <- cluster1[-trainIndex1, ]
# Paso 2: Dividir el conjunto temporal en validación (50% de temp) y prueba (50% de temp)
trainIndex2 <- createDataPartition(temp$Precio, p = 0.5, list = FALSE, times = 1)
validation <- temp[trainIndex2, ]
test <- temp[-trainIndex2, ]
##### ARBOLES ######################################################
# Construir el árbol de decisión
tree <- rpart(Precio ~ ., data = train, method = "anova", control = rpart.control(cp = 0))
rpart.plot(tree)
rpart.plot(tree,digits = 4,fallen.leaves = TRUE, type = 3,extra = 101)
# Visualizar la curva de complejidad
plotcp(tree)
################# Validación Cruzada ##################################
preproc <- preProcess(validation, method = "medianImpute")
validation_clean <- predict(preproc, cluster2)
# Definir el método de control de entrenamiento para la validación cruzada k-fold 10 pliegues o subconjuntos. El modelo se entrena 10 veces
ctrl <- trainControl(method = "cv", number = 100)
# Entrenar el modelo con validación cruzada
tree_model_cv <- train(Precio ~ ., data = validation_clean,
method = "rpart",
trControl = ctrl,
tuneLength = 10)
## Warning in nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,
## : There were missing values in resampled performance measures.
# Ver los resultados
print(tree_model_cv)
## CART
##
## 203 samples
## 11 predictor
##
## No pre-processing
## Resampling: Cross-Validated (100 fold)
## Summary of sample sizes: 201, 201, 201, 201, 201, 201, ...
## Resampling results across tuning parameters:
##
## cp RMSE Rsquared MAE
## 0.0002834503 584.4122 0.9784656 499.7506
## 0.0003427219 586.0774 0.9806928 500.2982
## 0.0005650667 581.8320 0.9795297 496.0889
## 0.0006290269 584.0035 0.9795297 497.9024
## 0.0007199857 584.7713 0.9780567 498.9911
## 0.0021646650 590.4890 0.9773115 503.9503
## 0.0035914010 583.2191 0.9805349 498.6450
## 0.0115531286 614.6026 0.9724640 530.6868
## 0.0302727869 654.7828 1.0000000 563.6262
## 0.7208815849 1003.1627 1.0000000 843.6315
##
## RMSE was used to select the optimal model using the smallest value.
## The final value used for the model was cp = 0.0005650667.
# Elegir un valor de cp basado en la gráfica y podar el árbol
#(El valor que mas minimiza el error)
pruned_tree <- prune(tree, cp = 0.00196)
# Visualizar el árbol podado
rpart.plot(pruned_tree)
* no se uso el arbol podado debido a la simplicidad del modelo
original
###############################
# Realizar predicciones en el conjunto de prueba
predictions <- predict(tree, newdata = test, type = "vector")
# Convertir las predicciones a numeric
predictions <- as.numeric(predictions)
test$Precio <- as.numeric(test$Precio)
#Evaluacion del modelo
#buscamos un valor pequeño
mae <- mae(predictions, test$Precio)
mae
## [1] 1306.899
mse <- mse(predictions, test$Precio)
mse
## [1] 2813056
rmse <- sqrt(mse)
rmse
## [1] 1677.217
#buscamos ser lo mas cercano a 1 (prediccion perfecta)
r_squared <- R2(predictions, test$Precio)
r_squared
## [1] 0.686818
#0.6868 indica un modelo acertivo
CART CLUSTER 2
# Establecer la semilla para reproducibilidad
set.seed(123)
# Paso 1: Dividir el conjunto de datos en entrenamiento (50%) y temporal (50%)
trainIndex1.2 <- createDataPartition(cluster2$Precio, p = 0.5, list = FALSE, times = 1)
train2 <- cluster2[trainIndex1, ]
temp2 <- cluster2[-trainIndex1, ]
# Paso 2: Dividir el conjunto temporal en validación (50% de temp) y prueba (50% de temp)
trainIndex2.2 <- createDataPartition(temp$Precio, p = 0.5, list = FALSE, times = 1)
validation2 <- temp2[trainIndex2.2, ]
test2 <- temp2[-trainIndex2.2, ]
##### ARBOLES ######################################################
# Construir el árbol de decisión
tree2 <- rpart(Precio ~ ., data = train2, method = "anova", control = rpart.control(cp = 0))
rpart.plot(tree2)
rpart.plot(tree2,digits = 4,fallen.leaves = TRUE, type = 3,extra = 101)
# Visualizar la curva de complejidad
plotcp(tree2)
En este árbol de decisiones podemos ver que el principal criterio para determinar el valor de una casa, son los metros cuadrados de construcción .
Fuimos capaces de encontrar diferentes rangos de precios, dependiendo de los M^2 construidos:
Se puede ver que existe una gran diferencia de precios en los inmuebles mayores a 83 m^2, comparado con los otros, teniendo más del doble de valor por una suma pequeña de metros de construcción. Es por eso que en esta zona, si se quiere aumentar el valor d euna casa, es escencial que tenga más de 83 m^2 de construcción. En el caso contrario en caso de que se quiera comprar se recomienda comprar en el segundo rango dado que es una diferencia minima de precio comparada con el tercer rango y se recibe una mayor cantidad de espacio.
################# Validación Cruzada ##################################
preproc2 <- preProcess(validation2, method = "medianImpute")
validation_clean2 <- predict(preproc2, cluster2)
# Definir el método de control de entrenamiento para la validación cruzada k-fold 10 pliegues o subconjuntos. El modelo se entrena 10 veces
ctrl2 <- trainControl(method = "cv", number = 100)
# Entrenar el modelo con validación cruzada
tree_model_cv_2 <- train(Precio ~ ., data = validation_clean2,
method = "rpart",
trControl = ctrl,
tuneLength = 10)
## Warning in nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,
## : There were missing values in resampled performance measures.
# Ver los resultados
print(tree_model_cv_2)
## CART
##
## 203 samples
## 11 predictor
##
## No pre-processing
## Resampling: Cross-Validated (100 fold)
## Summary of sample sizes: 201, 201, 201, 200, 201, 201, ...
## Resampling results across tuning parameters:
##
## cp RMSE Rsquared MAE
## 0.0002834503 567.2789 0.9951335 489.1554
## 0.0003427219 566.1145 0.9955893 488.3207
## 0.0005650667 560.7730 0.9981814 483.5602
## 0.0006290269 563.0155 0.9981814 485.7536
## 0.0007199857 562.8556 0.9981593 485.6492
## 0.0021646650 564.0630 0.9977082 488.7791
## 0.0035914010 563.4225 0.9971404 485.5317
## 0.0115531286 594.7455 0.9996607 514.5757
## 0.0302727869 639.0332 0.9980681 549.0796
## 0.7208815849 986.8585 1.0000000 835.2946
##
## RMSE was used to select the optimal model using the smallest value.
## The final value used for the model was cp = 0.0005650667.
# Elegir un valor de cp basado en la gráfica y podar el árbol
#(El valor que mas minimiza el error)
pruned_tree2 <- prune(tree2, cp = 0.00031)
# Visualizar el árbol podado
rpart.plot(pruned_tree2)
*no se uso el arbol podado debido a la simplicidad del original
###############################
# Alinear los niveles de Cocina_equip
test2$Cocina_equip <- factor(test2$Cocina_equip, levels = levels(train2$Cocina_equip))
# Realizar predicciones en el conjunto de prueba
predictions2 <- predict(tree2, newdata = test2, type = "vector")
# Convertir las predicciones a numeric
predictions2 <- as.numeric(predictions2)
test2$Precio <- as.numeric(test2$Precio)
#Evaluacion del modelo
#buscamos un valor pequeño
mae2 <- mae(predictions2, test$Precio)
## Warning in actual - predicted: longer object length is not a multiple of
## shorter object length
mae2
## [1] 3286.232
mse2 <- mse(predictions2, test$Precio)
## Warning in actual - predicted: longer object length is not a multiple of
## shorter object length
mse2
## [1] 19695380
rmse2 <- sqrt(mse2)
rmse2
## [1] 4437.948
#buscamos ser lo mas cercano a 1 (prediccion perfecta)
r_squared2 <- R2(predictions2, test2$Precio)
r_squared2
## [1] 0.4582048
#0.6475 indica un modelo acertivo
CART CLUSTER 3
# Establecer la semilla para reproducibilidad
set.seed(123)
# Paso 1: Dividir el conjunto de datos en entrenamiento (50%) y temporal (50%)
trainIndex1.3 <- createDataPartition(cluster3$Precio, p = 0.5, list = FALSE, times = 1)
train3 <- cluster3[trainIndex1.3, ]
temp3 <- cluster3[-trainIndex1.3, ]
# Paso 2: Dividir el conjunto temporal en validación (50% de temp) y prueba (50% de temp)
trainIndex2.3 <- createDataPartition(temp3$Precio, p = 0.5, list = FALSE, times = 1)
validation3 <- temp3[trainIndex2.3, ]
test3 <- temp3[-trainIndex2.3, ]
##### ARBOLES ######################################################
# Construir el árbol de decisión
tree3 <- rpart(Precio ~ ., data = train3, method = "anova", control = rpart.control(cp = 0))
rpart.plot(tree3)
rpart.plot(tree3,digits = 4,fallen.leaves = TRUE, type = 3,extra = 101)
# Visualizar la curva de complejidad
plotcp(tree3)
En este cluster podemos ver tres variables que determinan el precio: el número de recámaras, su estatus de terrazas y sus metros^2. - Si el inmueble tiene terraza, entonces el precio será de 1017 miles de pesos - Si no tiene terraza pero tiene más de tres recámaras su valor será 849.7 miles de pesos - Si no tiene terraza, tiene menos de 3 recámaras y tiene más de 63 m^2; su precio será de 704.4 miles de pesos. - Si no tiene terraza, cuenta con menos de 3 recámara y tiene menos de 63 m^2 su precio será de 561.3 miles de pesos
################# Validación Cruzada ##################################
preproc3 <- preProcess(validation3, method = "medianImpute")
validation_clean3 <- predict(preproc3, cluster3)
# Definir el método de control de entrenamiento para la validación cruzada k-fold 10 pliegues o subconjuntos. El modelo se entrena 10 veces
ctrl3 <- trainControl(method = "cv", number = 100)
# Entrenar el modelo con validación cruzada
tree_model_cv_3 <- train(Precio ~ ., data = validation_clean3,
method = "rpart",
trControl = ctrl,
tuneLength = 10)
## Warning in nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,
## : There were missing values in resampled performance measures.
# Ver los resultados
print(tree_model_cv_3)
## CART
##
## 86 samples
## 11 predictors
##
## No pre-processing
## Resampling: Cross-Validated (100 fold)
## Summary of sample sizes: 85, 85, 85, 85, 85, 85, ...
## Resampling results across tuning parameters:
##
## cp RMSE Rsquared MAE
## 0.00000000 254.5218 NaN 254.5218
## 0.01951037 260.5640 NaN 260.5640
## 0.03902075 250.9251 NaN 250.9251
## 0.05853112 250.9251 NaN 250.9251
## 0.07804149 250.9251 NaN 250.9251
## 0.09755187 250.9251 NaN 250.9251
## 0.11706224 250.9251 NaN 250.9251
## 0.13657261 250.9251 NaN 250.9251
## 0.15608299 265.3102 NaN 265.3102
## 0.17559336 302.9673 NaN 302.9673
##
## RMSE was used to select the optimal model using the smallest value.
## The final value used for the model was cp = 0.1365726.
# Elegir un valor de cp basado en la gráfica y podar el árbol
#(El valor que mas minimiza el error)
pruned_tree3 <- prune(tree3, cp = 0.13657)
# Visualizar el árbol podado
rpart.plot(pruned_tree3)
* no se uso el arbol podado debido a la simplicidad del modelo
original
###############################
# Realizar predicciones en el conjunto de prueba
predictions3 <- predict(tree3, newdata = test3, type = "vector")
# Convertir las predicciones a numeric
predictions3 <- as.numeric(predictions3)
test3$Precio <- as.numeric(test3$Precio)
#Evaluacion del modelo
#buscamos un valor pequeño
mae3 <- mae(predictions3, test3$Precio)
mae3
## [1] 300.5093
mse3 <- mse(predictions3, test3$Precio)
mse3
## [1] 138412.5
rmse3 <- sqrt(mse3)
rmse3
## [1] 372.0383
#buscamos ser lo mas cercano a 1 (prediccion perfecta)
r_squared3 <- R2(predictions3, test3$Precio)
r_squared3
## [1] 0.07631214
#0.07 indica que no hay suficiente evidencia para decir que es un modelo acertivo
CART CLUSTER 4
# Establecer la semilla para reproducibilidad
set.seed(123)
# Paso 1: Dividir el conjunto de datos en entrenamiento (50%) y temporal (50%)
trainIndex1.4 <- createDataPartition(cluster4$Precio, p = 0.5, list = FALSE, times = 1)
train4 <- cluster4[trainIndex1.4, ]
temp4 <- cluster4[-trainIndex1.4, ]
# Paso 2: Dividir el conjunto temporal en validación (50% de temp) y prueba (50% de temp)
trainIndex2.4 <- createDataPartition(temp4$Precio, p = 0.5, list = FALSE, times = 1)
validation4 <- temp4[trainIndex2.4, ]
test4 <- temp4[-trainIndex2.4, ]
##### ARBOLES ######################################################
# Construir el árbol de decisión
tree4 <- rpart(Precio ~ ., data = train4, method = "anova", control = rpart.control(cp = 0))
rpart.plot(tree4)
rpart.plot(tree4,digits = 4,fallen.leaves = TRUE, type = 3,extra = 101)
# Visualizar la curva de complejidad
plotcp(tree4)
En este caso podemos notar que el único determinante para el precio del producto es si el inmueble tiene más o menos de 96 m^2 de consturcción: - En caso de tener más, tendrá un valor de 4636 miles de pesos - En caso de tener menos, su valor es de solo 2223 miles de pesos.
Se puede observar que hay una gran variedad de precios en este cluster y que solo se debe de enfocar en los m^2 construidos.
################# Validación Cruzada ##################################
preproc4 <- preProcess(validation4, method = "medianImpute")
validation_clean4 <- predict(preproc4, cluster4)
# Definir el método de control de entrenamiento para la validación cruzada k-fold 10 pliegues o subconjuntos. El modelo se entrena 10 veces
ctrl4 <- trainControl(method = "cv", number = 100)
# Entrenar el modelo con validación cruzada
tree_model_cv_4 <- train(Precio ~ ., data = validation_clean4,
method = "rpart",
trControl = ctrl,
tuneLength = 10)
## Warning in nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,
## : There were missing values in resampled performance measures.
# Ver los resultados
print(tree_model_cv_4)
## CART
##
## 50 samples
## 11 predictors
##
## No pre-processing
## Resampling: Cross-Validated (100 fold)
## Summary of sample sizes: 49, 49, 49, 49, 49, 49, ...
## Resampling results across tuning parameters:
##
## cp RMSE Rsquared MAE
## 0.00000000 864.1092 NaN 864.1092
## 0.04681156 927.4732 NaN 927.4732
## 0.09362312 1084.4067 NaN 1084.4067
## 0.14043468 1084.4067 NaN 1084.4067
## 0.18724623 1084.4067 NaN 1084.4067
## 0.23405779 1084.4067 NaN 1084.4067
## 0.28086935 1084.4067 NaN 1084.4067
## 0.32768091 1084.4067 NaN 1084.4067
## 0.37449247 1299.7210 NaN 1299.7210
## 0.42130403 1576.7822 NaN 1576.7822
##
## RMSE was used to select the optimal model using the smallest value.
## The final value used for the model was cp = 0.
# Elegir un valor de cp basado en la gráfica y podar el árbol
#(El valor que mas minimiza el error)
pruned_tree4 <- prune(tree4, cp = 0.13657)
# Visualizar el árbol podado
rpart.plot(pruned_tree4)
* no se uso el arbol podado debido a la simplicidad del modelo
original
###############################
# Realizar predicciones en el conjunto de prueba
predictions4 <- predict(tree4, newdata = test4, type = "vector")
# Convertir las predicciones a numeric
predictions4<- as.numeric(predictions4)
test4$Precio <- as.numeric(test4$Precio)
#Evaluacion del modelo
#buscamos un valor pequeño
mae4 <- mae(predictions4, test4$Precio)
mae4
## [1] 1179.25
mse4 <- mse(predictions4, test4$Precio)
mse4
## [1] 2559534
rmse4 <- sqrt(mse4)
rmse4
## [1] 1599.854
#buscamos ser lo mas cercano a 1 (prediccion perfecta)
r_squared4 <- R2(predictions4, test4$Precio)
r_squared4
## [1] 0.1856749
#0.185 indica que no hay suficiente evidencia para decir que es un modelo acertivo
AL TENER 2 CLUSTERS CON CARACTERISTICAS SIMILARES (PROPIEDAD BASICA Y PROPIEDAD TRADICIONAL) TIENE SENTIDO QUE AMBOS MODELOS NO SEAN LO SUFICIENTEMENTE PRECISOS PUES NO HAY LOS SUFICIENTES REGISTROS PARA ENTRENARLOS A DIFERENCIAR UNO DEL OTRO.
CART CLUSTER 5
# Establecer la semilla para reproducibilidad
set.seed(123)
# Paso 1: Dividir el conjunto de datos en entrenamiento (50%) y temporal (50%)
trainIndex1.5 <- createDataPartition(cluster5$Precio, p = 0.5, list = FALSE, times = 1)
train5 <- cluster5[trainIndex1.5, ]
temp5 <- cluster5[-trainIndex1.5, ]
# Paso 2: Dividir el conjunto temporal en validación (50% de temp) y prueba (50% de temp)
trainIndex2.5 <- createDataPartition(temp5$Precio, p = 0.5, list = FALSE, times = 1)
validation5 <- temp5[trainIndex2.5, ]
test5 <- temp5[-trainIndex2.5, ]
##### ARBOLES ######################################################
# Construir el árbol de decisión
tree5 <- rpart(Precio ~ ., data = train5, method = "anova", control = rpart.control(cp = 0))
rpart.plot(tree5)
rpart.plot(tree5,digits = 4,fallen.leaves = TRUE, type = 3,extra = 101)
# Visualizar la curva de complejidad
plotcp(tree5)
En este modelo podemos ver que el hay tres determinante para el precio de un inmueble: la cantidad de m^2 construidos, el número de baños y si tiene terraza o no. Podemos encontrar los siguiente escenarios.
Podemos ver en este caso que el mayor determinante para subir precio del inmueble es que éste tenga terraza.
################# Validación Cruzada ##################################
preproc5 <- preProcess(validation5, method = "medianImpute")
validation_clean5 <- predict(preproc5, cluster5)
# Definir el método de control de entrenamiento para la validación cruzada k-fold 10 pliegues o subconjuntos. El modelo se entrena 10 veces
ctrl5 <- trainControl(method = "cv", number = 100)
# Entrenar el modelo con validación cruzada
tree_model_cv_5 <- train(Precio ~ ., data = validation_clean5,
method = "rpart",
trControl = ctrl,
tuneLength = 10)
## Warning in nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,
## : There were missing values in resampled performance measures.
# Ver los resultados
print(tree_model_cv_5)
## CART
##
## 183 samples
## 11 predictor
##
## No pre-processing
## Resampling: Cross-Validated (100 fold)
## Summary of sample sizes: 181, 182, 181, 181, 181, 181, ...
## Resampling results across tuning parameters:
##
## cp RMSE Rsquared MAE
## 0.005263546 1421.137 1 1296.446
## 0.005794178 1455.417 1 1338.265
## 0.006091701 1435.915 1 1320.283
## 0.008032659 1438.087 1 1317.056
## 0.009008367 1426.416 1 1310.813
## 0.016882122 1412.646 1 1290.048
## 0.024773861 1485.126 1 1356.467
## 0.055071677 1712.048 1 1568.312
## 0.083200306 1968.459 1 1808.835
## 0.636359286 3162.966 1 2996.273
##
## RMSE was used to select the optimal model using the smallest value.
## The final value used for the model was cp = 0.01688212.
# Elegir un valor de cp basado en la gráfica y podar el árbol
#(El valor que mas minimiza el error)
pruned_tree5 <- prune(tree5, cp = 0.0052)
# Visualizar el árbol podado
rpart.plot(pruned_tree5)
* no se uso el arbol podado debido a la simplicidad del modelo
###############################
# Realizar predicciones en el conjunto de prueba
predictions5 <- predict(tree5, newdata = test5, type = "vector")
# Convertir las predicciones a numeric
predictions5<- as.numeric(predictions5)
test5$Precio <- as.numeric(test5$Precio)
#Evaluacion del modelo
#buscamos un valor pequeño
mae5 <- mae(predictions5, test5$Precio)
mae5
## [1] 1322.535
mse5 <- mse(predictions5, test5$Precio)
mse5
## [1] 3450167
rmse5 <- sqrt(mse5)
rmse5
## [1] 1857.463
#buscamos ser lo mas cercano a 1 (prediccion perfecta)
r_squared5 <- R2(predictions5, test5$Precio)
r_squared5
## [1] 0.7191369
#0.719 indica un modelo acertivo
NOMBRAR CLUSTERS
bd2$Cluster[bd2$Cluster == 1] = "Propiedad Popular"
bd2$Cluster[bd2$Cluster == 2] = "Propiedad Plata"
bd2$Cluster[bd2$Cluster == 3] = "Propiedad Basica"
bd2$Cluster[bd2$Cluster == 4] = "Propiedad Tradicional"
bd2$Cluster[bd2$Cluster == 5] = "Propiedad Premium"
TABLA DE CONTINGENCIA
contingency <- table(bd2$Cluster, bd2$Alcaldia)
contingency <- prop.table(contingency, margin = 1) * 100
contingency
##
## Alvaro Obregon Azcapotzalco Benito Ju\xe1rez Coyoacan
## Propiedad Basica 0.000000 0.000000 0.000000 0.000000
## Propiedad Plata 0.000000 0.000000 0.000000 0.000000
## Propiedad Popular 0.000000 0.000000 31.707317 54.878049
## Propiedad Premium 43.169399 16.393443 0.000000 0.000000
## Propiedad Tradicional 0.000000 0.000000 0.000000 0.000000
##
## Cuahtemoc Cuajimalpa Gustavo A. Madero Iztacalco
## Propiedad Basica 0.000000 0.000000 91.860465 8.139535
## Propiedad Plata 0.000000 0.000000 0.000000 0.000000
## Propiedad Popular 0.000000 0.000000 0.000000 0.000000
## Propiedad Premium 14.754098 7.650273 0.000000 0.000000
## Propiedad Tradicional 0.000000 0.000000 0.000000 0.000000
##
## Iztapalapa La Magdalena Contreras Miguel Hidalgo
## Propiedad Basica 0.000000 0.000000 0.000000
## Propiedad Plata 46.305419 7.881773 0.000000
## Propiedad Popular 0.000000 0.000000 13.414634
## Propiedad Premium 0.000000 0.000000 0.000000
## Propiedad Tradicional 0.000000 0.000000 0.000000
##
## Milpa alta Tlahuac Tlalpan Venustiano Carranza
## Propiedad Basica 0.000000 0.000000 0.000000 0.000000
## Propiedad Plata 5.418719 40.394089 0.000000 0.000000
## Propiedad Popular 0.000000 0.000000 0.000000 0.000000
## Propiedad Premium 0.000000 0.000000 0.000000 18.032787
## Propiedad Tradicional 0.000000 0.000000 52.000000 0.000000
##
## Xochimilco
## Propiedad Basica 0.000000
## Propiedad Plata 0.000000
## Propiedad Popular 0.000000
## Propiedad Premium 0.000000
## Propiedad Tradicional 48.000000
DISTRIBUCION DE ALCALDIAS POR CLUSTERS
Propiedad popular: - Benito Juárez 32% - Coyoacan 55% - Miguel Hidalgo 13%
Propiedas básica: - A. Madero 92% - Iztacalco 8%
Propiedad tradicional -Tlalpan
Propiedad plata - Iztapalapa 46% - La Magdalena Contreras 8% - Milpa Alta 5% - Tlahuac 40%
Propiedad premium - Alvaro obregon 43% - Azcapotzalco 16% - Cuahtemoc 15% - Cuajimalpa 8% - Venustiano Carranza 18%
PREDICCIONES
datos_prueba <- read.csv("C:\\Users\\maria\\OneDrive\\Desktop\\PRUEBA1.csv", stringsAsFactors = TRUE)
prediccion1 <- predict(tree, newdata= datos_prueba)
prediccion2 <- predict(tree2, newdata= datos_prueba)
prediccion3 <- predict(tree3, newdata= datos_prueba)
prediccion4 <- predict(tree4, newdata= datos_prueba)
prediccion5 <- predict(tree5, newdata= datos_prueba)
cat(
paste("Esta es una demostracion de los que costaria una casa con las mismas caracteristicas en cada tipo de prpiedad (sub-market)"),
paste("Propiedad Popular:", prediccion1[1]),
paste("Propiedad Basica:", prediccion3[1]),
paste("Propiedad Tradicional:", prediccion4[1]),
paste("Propiedad Plata:", prediccion2[1]),
paste("Propiedad Premium:", prediccion4[1]),
sep = "\n"
)
## Esta es una demostracion de los que costaria una casa con las mismas caracteristicas en cada tipo de prpiedad (sub-market)
## Propiedad Popular: 9287.125
## Propiedad Basica: 1016.81818181818
## Propiedad Tradicional: 4635.5
## Propiedad Plata: 3093
## Propiedad Premium: 4635.5