library(gdata)
data <- read.xls("http://archive.ics.uci.edu/ml/machine-learning-databases/concrete/compressive/Concrete_Data.xls")

names(data) <- paste("V", 1:ncol(data), sep="")

summary(data)

select <- sample(1:nrow(data), size=nrow(data) * 0.5)

train.x <- data[select, 1:8]
train.x <- scale(train.x)

train.d <- data[select, 9]
#	train.d <- scale(train.d)
train.d <- train.d / 100

test.x <- data[-select, 1:8]
test.x <- scale(
	test.x,
	center=attr(train.x, "scaled:center"),
	scale=attr(train.x, "scaled:scale")
)

test.d <- data[-select, 9]
test.d <- test.d / 100

library(nnet)

net <- nnet(train.x, train.d, size=10, maxit=1000, decay=0)

train.y <- predict(net)

plotResult <- function(t, r) {
	m <- lm(r ~ t, list(t=t, r=r))
	plot(t, r, pch=20)
	abline(m, col="green")
	abline(0, 1, lty="dotted")
	legend(
		"bottomright",
		c("Data", "d = y", "Fit"),
		pch=c(20, -1, -1),
		lty=c("blank", "dotted", "solid"),
		col=c("black", "black", "green"),
	)
}

oldPar <- par(no.readonly=TRUE)

par(mfcol=c(1, 2), ask=TRUE)

plotResult(train.d, train.y)
title(main="Training set")

test.y <- predict(net, test.x)
plotResult(test.d, test.y)
title(main="Test set")

par(oldPar)

cat("Error on training set: ", net$value, "\n")
cat("Error on test set: ", sum((test.d - test.y)^2), "\n")
