library(nnet)
library(pixmap)

readFaceImages <- function(file) {

	x <- scan(file, what=character())
	x <- substring(x, 35)

	Y <- sapply(x, function(z) strsplit(z, "_", fixed=TRUE)[[1]])
	Y <- t(Y)
	Y <- Y[, 2:4]
	colnames(Y) <- paste("Y", 1:3, sep="")
	Y <- data.frame(Y)

	images <- sapply(
		x,
		function(file) {
			image <- read.pnm(file)
			as.vector(t(attr(image, "grey")))
		}
	)
	images <- t(images)

	list(images=images, Y=Y)
}

list1 <- readFaceImages("all_train.list")
list2 <- readFaceImages("all_test1.list")

trainingData <- cbind(data.frame(list1$images), list1$Y[1])

net <- nnet(Y1 ~ ., data=trainingData, size=4, MaxNWts=4000, maxit=500, decay=1e-3)

t1 <- table(predict(net, type="class"), list1$Y[[1]])
print(t1)
cat("Accuracy on training set: ", 100 * sum(diag(t1)) / sum(t1), "%\n", sep="")

testData <- data.frame(list2$images)
t2 <- table(predict(net, testData, type="class"), list2$Y[[1]])
print(t2)
cat("Accuracy on test set: ", 100 * sum(diag(t2)) / sum(t2), "%\n", sep="")
