#ANN
#install.packages("ANN2")
library(ANN2)
# Example on zip dataset
# Prepare test and train sets
zip.train <- read.table("./zip.train",
                        col.names=c("cl",paste("x",1:256,sep="")))
zip.test <- read.table("./zip.test",
                       col.names=c("cl",paste("x",1:256,sep="")))
zip = rbind(zip.train,zip.test)
N.tr = nrow(zip.train)
N.te = nrow(zip.test)
X_train<- zip.train[, -1]
y_train<- as.factor(zip.train[, 1])
X_test<- zip.test[,-1]
y_test<- as.factor(zip.test[, 1])

# Train neural network on classification task
NN <- neuralnetwork(X = X_train, 
                    y = y_train, 
                    hidden.layers = c(15,15,15),
                    activ.functions="tanh",
                    optim.type = 'sgd', 
                    learn.rates = 0.001, 
                    val.prop = 0.1,
                    loss.type='log')
plot(NN)
# Make predictions
y_pred <- predict(NN, newdata = X_test)
# Plot predictions
tab = table(y_test,y_pred$pred)
show(tab)
cat("Err=",1-sum(diag(tab))/nrow(X_test),"\n")

#show examples
plotCase=53  # from 1 to 2007
drawing=matrix(as.numeric(zip.test[plotCase,-1]),ncol=16)
image(1:16,1:16,drawing[, seq(16,1,-1)])
show(c(zip.test[plotCase,1],y_pred$predictions[plotCase]))
show(round(y_pred$probabilities[plotCase,]*100))

