Last active
October 27, 2018 14:22
-
-
Save cgarbin/b28dbf6e081395487c0aa828662376a2 to your computer and use it in GitHub Desktop.
A simple R neuralnet for mlbnech::circle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Always start with a clean environment to avoid subtle bugs | |
rm(list = ls()) | |
# To get repeatable results with random numbers (easier to debug multiple runs) | |
set.seed(123) | |
# Create a circle data set, change labels to -1/1, convert to data.frame | |
library(mlbench) | |
circle <- mlbench.circle(500, 2) | |
labels <- sign(as.numeric(circle$classes) - 1.5) | |
circle <- data.frame(cbind(circle$x[, 1:2], labels)) | |
# Split in training and test sets | |
train_index <- sample(nrow(circle), nrow(circle) * 0.3) | |
training_set <- circle[train_index,] | |
test_set <- circle[-train_index,] | |
# Split test set into features and labels | |
class_index <- dim(training_set)[2] | |
test_set_features <- test_set[,-class_index] | |
test_set_labels <- test_set[,class_index] | |
# Train a classifier, shows results on the test set | |
library(neuralnet) | |
classifier <- neuralnet(labels ~ V1 + V2, training_set, hidden = c(5, 5), rep = 3) | |
best_rep <- which.min(classifier$result.matrix["error", ]) | |
predicted <- compute(classifier, test_set_features, rep = best_rep) | |
predicted_label <- sign(predicted$net.result) | |
cm <- table(predicted_label, test_set_labels) | |
print(cm) | |
accuracy <- (sum(diag(cm))) / sum(cm) | |
print(accuracy) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment