neuralnet

# install.packages('neuralnet')
library("neuralnet")
## Loading required package: grid
## Loading required package: MASS

# Going to create a neural network to perform sqare rooting Type
# ?neuralnet for more information on the neuralnet library

# Generate 50 random numbers uniformly distributed between 0 and 100 And
# store them as a dataframe
traininginput <- as.data.frame(runif(50, min = 0, max = 100))
trainingoutput <- sqrt(traininginput)

# Column bind the data into one variable
trainingdata <- cbind(traininginput, trainingoutput)
colnames(trainingdata) <- c("Input", "Output")

# Train the neural network Going to have 10 hidden layers Threshold is a
# numeric value specifying the threshold for the partial derivatives of
# the error function as stopping criteria.
net.sqrt <- neuralnet(Output ~ Input, trainingdata, hidden = 10, threshold = 0.01)
print(net.sqrt)
## Call: neuralnet(formula = Output ~ Input, data = trainingdata, hidden = 10,     threshold = 0.01)
## 
## 1 repetition was calculated.
## 
##             Error Reached Threshold Steps
## 1 0.0008231226122    0.009991374784  6185

# Plot the neural network
plot(net.sqrt)

# Test the neural network on some training data
testdata <- as.data.frame((1:10)^2)  #Generate some squared numbers
net.results <- compute(net.sqrt, testdata)  #Run them through the neural network

# Lets see what properties net.sqrt has
ls(net.results)
## [1] "net.result" "neurons"

# Lets see the results
print(net.results$net.result)
##               [,1]
##  [1,] 0.9172252797
##  [2,] 1.9996997877
##  [3,] 3.0022204380
##  [4,] 3.9963370603
##  [5,] 4.9991734168
##  [6,] 6.0033634560
##  [7,] 6.9925553698
##  [8,] 7.9967317407
##  [9,] 9.0082663336
## [10,] 9.9661994294

# Lets display a better version of the results
cleanoutput <- cbind(testdata, sqrt(testdata), as.data.frame(net.results$net.result))
colnames(cleanoutput) <- c("Input", "Expected Output", "Neural Net Output")
print(cleanoutput)
##    Input Expected Output Neural Net Output
## 1      1               1      0.9172252797
## 2      4               2      1.9996997877
## 3      9               3      3.0022204380
## 4     16               4      3.9963370603
## 5     25               5      4.9991734168
## 6     36               6      6.0033634560
## 7     49               7      6.9925553698
## 8     64               8      7.9967317407
## 9     81               9      9.0082663336
## 10   100              10      9.9661994294