library(RSNNS) # function compute accuracy # input: # model: list(weights, bias) # x: a n*d matrix in which each row is a datum point # y: a n*1 matrix in which each row is the target of x[i,] # output: classification error compute.accuracy <- function(model, x, y) { n.cases <- dim(x)[1] pred <- (predict(model, x) > 0.5) * 1. acc <- sum((y == pred)*1.)/n.cases return(acc) } # function compute error # input: # x: a n*d matrix in which each row is a datum point # y: a n*1 matrix in which each row is the target of x[i,] # ratio: n_train / n_test # output: list(x.train, y.train, x.test, y.test) split.data <- function(x, y, ratio) { ncases <- dim(x)[1] ntrain <- round(ncases * ratio / (ratio+1)) list( x.train = x[1:ntrain,], y.train = as.matrix(y[1:ntrain,]), x.test = x[(ntrain+1):ncases,], y.test = as.matrix(y[(ntrain+1):ncases,])) } ############################################################ maxit <- 100 learn.rate <- 0.2 size = c(5) # load data from the file 'leftright.dat' dat0 <- read.table("leftright.dat") # randomize the order rand = sample(nrow(dat0)) dat = dat0[rand,] in.dim <- dim(dat)[2] - 1 x <- as.matrix(dat[,1:in.dim]) x <- normalizeData(x) y <- as.matrix((dat[,in.dim+1] == dat[1,in.dim+1]) * 1) # split the dataset splitdat <- split.data(x, y, 10) # train a multilayer perceptron model <- mlp(splitdat$x.train, splitdat$y.train, maxit = maxit, size = size, learnFuncParams = learn.rate) # report result plotIterativeError(model) cat("accuracy: ", compute.accuracy(model, splitdat$x.test, splitdat$y.test), "\n")