Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active June 5, 2019 11:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save primaryobjects/f5d940ba6cd11d4d7fd0 to your computer and use it in GitHub Desktop.
Save primaryobjects/f5d940ba6cd11d4d7fd0 to your computer and use it in GitHub Desktop.
A simple neural network in R to predict the square root of numbers.
library(caret)
# Generate 50 random numbers uniformly distributed between 0 and 100.
training <- data.frame(x = runif(50, min=0, max=100))
training$y <- sqrt(training$x)
# Generate some squared numbers.
cv <- data.frame(x = (1:10)^2)
cv$y <- sqrt(cv$x)
fit <- train(y ~ ., data = training, method = 'neuralnet', tuneGrid = expand.grid(layer1 = c(6), layer2 = 0, layer3 = 0))
results <- predict(fit, newdata = cv)
conf <- table(results, cv$y)
cbind(cv, predict = round(predict(fit, newdata = cv)))
With Rounding
---
x y predict
1 1 1 2
2 4 2 2
3 9 3 3
4 16 4 4
5 25 5 5
6 36 6 6
7 49 7 7
8 64 8 8
9 81 9 9
10 100 10 10
Raw
---
x y predict
1 1 1 1.556684143
2 4 2 2.114010068
3 9 3 2.975641028
4 16 4 3.987989475
5 25 5 5.004697727
6 36 6 5.998886923
7 49 7 6.997019411
8 64 8 8.000357771
9 81 9 9.003102803
10 100 10 9.992746337
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment