El dataset seleccionado contiene variables relacionadas con hábitos de salud y características físicas, lo que lo hace ideal para predecir condiciones médicas como enfermedades cardíacas. La relación entre variables como ejercicio, sueño, nutrición y salud cardiovascular.
*Paso 1: Instalar, cargar y referenciar librerias
library(readr)
library(neuralnet)
## Warning: package 'neuralnet' was built under R version 4.4.3
library(corrplot)
## Warning: package 'corrplot' was built under R version 4.4.3
## corrplot 0.95 loaded
# Cargar datos
datos <- read_csv("C:/R/U3/health_activity_data.csv")
## Rows: 1000 Columns: 16
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (5): Gender, Blood_Pressure, Smoker, Diabetic, Heart_Disease
## dbl (11): ID, Age, Height_cm, Weight_kg, BMI, Daily_Steps, Calories_Intake, ...
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
Variables numéricas: Age, Height_cm, Weight_kg, BMI, Daily_Steps, Calories_Intake, Hours_of_Sleep, Heart_Rate, Exercise_Hours_per_Week
Variable objetivo: Heart_Disease (binaria: Yes/No)
# Identificar y eliminar NA's
sum(is.na(datos))
## [1] 0
datos <- na.omit(datos)
# Convertir variable objetivo a numérica binaria
datos$Heart_Disease <- ifelse(datos$Heart_Disease == "Yes", 1, 0)
# Función de normalización
normalizar <- function(x) {
return((x - min(x)) / (max(x) - min(x)))
}
# Aplicar a columnas numéricas
datos[, sapply(datos, is.numeric)] <- lapply(datos[, sapply(datos, is.numeric)], normalizar)
cor_matrix <- cor(datos[, sapply(datos, is.numeric)])
corrplot(cor_matrix, method = "color", type = "upper")
# Dividir datos
set.seed(123)
train_index <- sample(1:nrow(datos), 0.8*nrow(datos))
train <- datos[train_index, ]
test <- datos[-train_index, ]
# Fórmula del modelo
formula <- Heart_Disease ~ Age + Height_cm + Weight_kg + BMI + Daily_Steps +
Calories_Intake + Hours_of_Sleep + Heart_Rate + Exercise_Hours_per_Week
# Configuración de capas
red_neuronal <- neuralnet(
formula,
data = train,
hidden = c(5), # Capa oculta con 5 neuronas
linear.output = FALSE,
act.fct = "logistic"
)
La elección de 5 neuronas en capa oculta se basó en:
Regla empírica: (neuronas entrada + salida)/2 = (9+1)/2 ≈ 5
Balance entre complejidad y prevención de sobreajuste
# Predicciones
pred <- compute(red_neuronal, test[, -which(names(test) == "Heart_Disease")])
pred_class <- ifelse(pred$net.result > 0.5, 1, 0)
# Matriz de confusión
conf_matrix <- table(Real = test$Heart_Disease, Predicho = pred_class)
print(conf_matrix)
## Predicho
## Real 0 1
## 0 178 4
## 1 18 0
# Cálculo de precisión
accuracy <- sum(diag(conf_matrix))/sum(conf_matrix)
print(paste("Precisión:", round(accuracy*100, 2), "%"))
## [1] "Precisión: 89 %"
Si la precisión inicial es insuficiente, considerar:
1.- Normalización de datos numéricos
2.- Transformación de variable objetivo
3.- División 80-20 entrenamiento/prueba
4.- Uso de función de activación logística
5.- Evaluación con matriz de confusión