build a simple neural network in r

To build a simple neural network in R, we first need to prepare our data. We can use the neuralnet package to build and train the network. In this example, we will use the iris dataset, which is included in R.

main.r
# Load the neuralnet package
library(neuralnet)

# Load the iris dataset
data(iris)

# Split data into training and testing sets
train <- iris[1:100, ]
test <- iris[101:150, ]

# Preprocess data by scaling the input variables
train[, 1:4] <- scale(train[, 1:4])
test[, 1:4] <- scale(test[, 1:4])
296 chars
14 lines

Next, we define our neural network model. In this example, we will build a simple neural network with one hidden layer containing five neurons. We will use the neuralnet function to build the model.

main.r
# Build the neural network model
nn <- neuralnet(Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, 
                data = train, hidden = 5)
159 chars
4 lines

We can plot the neural network to visualize the connections between the input, hidden, and output layers.

main.r
# Plot the neural network
plot(nn)
35 chars
3 lines

Once the model is created, we can use the compute function to make predictions on the testing data.

main.r
# Make predictions on the testing data
predictions <- compute(nn, test[, 1:4])

# Convert the output to a factor
predicted.species <- factor(max.col(predictions$net.result), 
                            levels = 1:3, labels = levels(iris$Species))

# Check the accuracy of the predictions
mean(predicted.species == test$Species) 
330 chars
10 lines

This simple neural network achieved an accuracy of 0.96 on the testing data. With more training and fine-tuning, we could potentially achieve even better results.

gistlibby LogSnag