Skip to content

Instantly share code, notes, and snippets.

@mick001
Last active August 19, 2016 12:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mick001/eff123479739d9d03a7da7939716cc08 to your computer and use it in GitHub Desktop.
Save mick001/eff123479739d9d03a7da7939716cc08 to your computer and use it in GitHub Desktop.
Multilable prediction in R using neuralnet package.
require(neuralnet) # neuralnet,compute, functions
require(nnet) # class.ind function
# Clearing workspace
rm( list=ls() )
# Set seed
set.seed(100)
# Loading data
data(iris)
data_ <- iris
# Normalizing data in the 0-1 interval in a tedious way :)
data_$Sepal.Length <- (data_$Sepal.Length - min(data_$Sepal.Length))/(max(data_$Sepal.Length)-min(data_$Sepal.Length))
data_$Sepal.Width <- (data_$Sepal.Width - min(data_$Sepal.Width))/(max(data_$Sepal.Width)-min(data_$Sepal.Width))
data_$Petal.Length <- (data_$Petal.Length - min(data_$Petal.Length))/(max(data_$Petal.Length)-min(data_$Petal.Length))
data_$Petal.Width <- (data_$Petal.Width - min(data_$Petal.Width))/(max(data_$Petal.Width)-min(data_$Petal.Width))
head(data_)
# Generate training set and fix categorical variable to be predicted
train <- cbind(data_[, 1:4], class.ind(as.factor(data_$Species)))
head(train)
nn <- neuralnet(setosa + versicolor + virginica ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width,
data = train,
hidden = c(4,3),
act.fct = "logistic",
linear.output = F)
nn
# Compute predictions
pr.nn <- compute(nn, train[, 1:4])
# Extract results
pr.nn_ <- pr.nn$net.result
head(pr.nn_)
View(pr.nn_)
# Accuracy (training set)
original_values <- max.col(train[, 5:7])
pr.nn_2 <- max.col(pr.nn_)
mean(pr.nn_2 == original_values)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment