# Instalar paquetes de funciones
install.packages(c("mlbench","caret","corrplot","e1071"))
# Cargar paquetes de funciones
library(mlbench)
library(caret)
library(corrplot)
library(e1071)

# 1. Leer datos
data(Glass)
dataset <- Glass

# 2. Describir los datos
head(dataset)
dim(dataset)

x <- dataset[,1:9]
y <- dataset[,10]

cor(x) #correlation

# 3. Visualizar los datos
# boxplot por separado
par(mfrow = c(3,3))
for (i in 1:9){
  boxplot(dataset[,i],main=names(dataset)[i])
}
# histograma
par(mfrow = c(3,3))
for (i in 1:9){
  hist(dataset[,i],main=names(dataset)[i])
}
# densidad
par(mfrow = c(3,3))
for (i in 1:9){
  plot(density(dataset[,i]),main=names(dataset)[i])
}

pairs(dataset)
pairs(dataset,col=dataset$Type)

pairs(dataset[,3:4],col=dataset$Type)

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)

par(mfrow = c(1,1))
correlations <- cor(x)
corrplot(correlations,method="circle")

# 4. Transform data
dataset[,1:9] <- scale(dataset[,1:9])

# 5. Evaluar algoritmos
# Definir los subgrupos / control
control <- trainControl(method ="repeatedcv",number = 10,repeats = 3)

# LDA
set.seed(2018)
fit.lda <- train(Type~.,data = dataset,method ="lda",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(Type~.,data = dataset, method = "svmRadial",metric="Accuracy",tunGrid =grid,trControl= control)

# CART
set.seed(2018)
fit.rf <- train(Type~.,data = dataset, method = "rf",metric="Accuracy",tunGrid =grid,trControl= control)

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

# Comparar algoritmos
results <- resamples(list(LDA = fit.lda ,SVM = fit.svm, RF = fit.rf))
summary(results)
dotplot(results)
