Instantly share code, notes, and snippets.

Embed
What would you like to do?
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