# instalar librerias
install.packages(c("mlbench","caret","Hmisc","e1071"))
# cargar libreries
library(mlbench)
library(caret)
library(Hmisc)
library(e1071)

# 1. import data
data("PimaIndiansDiabetes")
dataset <- PimaIndiansDiabetes

# 2. Descriptiva de los datos
x <- dataset[1:8]
y <- dataset[,9]

summary(dataset)
cor(x)

# 3. Visualizar los datos
featurePlot(x=x,y=y,plot="pairs") # matrixplot
scales <- list(x=list(relation="free"),y=list(relation="free"))
featurePlot(x=x,y=y,plot="box",scales = scales)
featurePlot(x=x,y=y,plot="density",scales = scales)

# 4. Limpiar los datos
# los valores ánomalos
# valores qeu no existen y quitar toda la fila o bien hacer un promedio para rellnar los NA
dataset$pressure[dataset$pressure==0]<-NA
dataset$mass[dataset$mass==0] <- NA
dataset$glucose[dataset$glucose==0] <- NA

detach("package:e1071", unload=TRUE)
dataset$pressure <- with(dataset,impute(pressure,mean))
dataset$mass <- with(dataset,impute(mass,mean))
dataset$glucose <- with(dataset,impute(glucose,mean))
library(e1071)

# 5.Evaluar algoritmos
# Definir subgrupos para calcular el modelo
control <- trainControl(method = "repeatedcv",number = 10,repeats = 3)

# GLM
set.seed(2018)
fit.glm <- train(diabetes~.,data = dataset, method = "glm", metric = "Accuracy",trControl = control)

# LDA
set.seed(2018)
fit.lda <- train(diabetes~.,data = dataset, method = "glm", metric = "Accuracy",trControl = control)

# SVM
set.seed(2018)
grid <- expand.grid(.sigma = c(0.01,0.05,0.1),.C=c(1))
fit.svm <- train(diabetes~.,data = dataset, method = "svmRadial", tuneGrid = grid,metric = "Accuracy",trControl = control)

# CART
set.seed(2018)
grid <- expand.grid(.cp=c(0.01,0.05,0.1))
fit.cart <- train(diabetes~.,data = dataset, method = "rpart", tuneGrid = grid,metric = "Accuracy",trControl = control)

# KNN
set.seed(2018)
grid <- expand.grid(.k=c(1,3,5,7))
fit.knn <- train(diabetes~.,data = dataset, method = "knn", tuneGrid = grid,metric = "Accuracy",trControl = control)


# 6.Seleccionar el mejor algoritmo
results <- resamples(list(GLM=fit.glm,LDA=fit.lda,SVM=fit.svm,CART = fit.cart,KNN=fit.knn))
summary(results)
dotplot(results)

# seleccionamos el lda

# 7. Predicción del modelo
# make predictions
predictions <- predict(fit.lda, x)
# summarize accuracy
table(predictions, y)
accuracy <- (452+144)/768
