How to train a neural network in R

In this recipe, we shall learn how to train a neural network in R. We shall be training a straightforward neural network using the neuralnet package in R.

Recipe Objective: How to train a neural network in R?

A neural network is a network that attempts to recognize underlying relationships of any data using a method that is similar to how the human brain works. It's a collection of connected input/output units with a weight assigned to each connection. The network learns by modifying the weights to predict the accurate class label of the provided inputs throughout the learning phase. We will be training a straightforward neural network using the neuralnet package in R. The steps for the same are as follows-

​Should I Learn Python or R for Data Science? Unlock the Answer

Step 1: Define the training set.

#creating training data set
Sci = c(70,71,72,73,68,69,65,69,80,68)
Mat = c(91,92,93,94,65,69,61,55,91,79)
Eng = c(82,83,84,85,73,66,50,62,95,68)
Pass = c(1,1,1,1,0,0,0,0,1,0)
df=data.frame(Sci,Mat,Eng,Pass)

We are creating our sample dataframe with three subjects- Science, Maths, English, and a Pass column which indicates if the student has passed or not. One shows pass, and 0 shows fail. The model should be able to predict if the student passes or fails.

Step 2: Install and load neuralnet package

#installing and loading neuralnet package
install.packages("neuralnet")
library("neuralnet")

Step 3: Fit neural network

#fitting the model
nn=neuralnet(Pass~Sci+Mat+Eng,data=df, hidden=3,act.fct = "logistic",
linear.output = FALSE)
#Pass~Sci+Mat+Eng, Pass is label and Sci,Mat,Eng are features.
#df is dataframe,
#hidden=3 stands for a single hidden layer with 3 neurons
#act.fct = "logistic" is used for smoothing the result.
#linear.ouput=FALSE is set FALSE for apply act.fct

Step 4: Plot the neural network

plot(nn)

Step 5: Create a test dataset

#creating tesing set
sci = c(80,75,65,68)
mat = c(95,92,69,45)
eng = c(85,83,55,50)
test=data.frame(sci,mat,eng)

Step 6: Predict results for the test dataset

#prediction
predict=compute(nn,test)
predict$net.result

probab<- predict$net.result

#converting probabilities into 1 and 0
pre <- ifelse(probab>0.5, 1, 0)
pre

	    [,1]
[1,]    1
[2,]    1
[3,]    1
[4,]    0

The predicted output for the testing set is 1, 1, 1, 0.
The neural network can be used for similarly making predictions for real datasets.

What Users are saying..

profile image

Ed Godalle

Director Data Analytics at EY / EY Tech
linkedin profile url

I am the Director of Data Analytics with over 10+ years of IT experience. I have a background in SQL, Python, and Big Data working with Accenture, IBM, and Infosys. I am looking to enhance my skills... Read More

Relevant Projects

OpenCV Project for Beginners to Learn Computer Vision Basics
In this OpenCV project, you will learn computer vision basics and the fundamentals of OpenCV library using Python.

Locality Sensitive Hashing Python Code for Look-Alike Modelling
In this deep learning project, you will find similar images (lookalikes) using deep learning and locality sensitive hashing to find customers who are most likely to click on an ad.

Build Time Series Models for Gaussian Processes in Python
Time Series Project - A hands-on approach to Gaussian Processes for Time Series Modelling in Python

Recommender System Machine Learning Project for Beginners-4
Collaborative Filtering Recommender System Project - Comparison of different model based and memory based methods to build recommendation system using collaborative filtering.

A/B Testing Approach for Comparing Performance of ML Models
The objective of this project is to compare the performance of BERT and DistilBERT models for building an efficient Question and Answering system. Using A/B testing approach, we explore the effectiveness and efficiency of both models and determine which one is better suited for Q&A tasks.

Tensorflow Transfer Learning Model for Image Classification
Image Classification Project - Build an Image Classification Model on a Dataset of T-Shirt Images for Binary Classification

Build a Graph Based Recommendation System in Python -Part 1
Python Recommender Systems Project - Learn to build a graph based recommendation system in eCommerce to recommend products.

Recommender System Machine Learning Project for Beginners-2
Recommender System Machine Learning Project for Beginners Part 2- Learn how to build a recommender system for market basket analysis using association rule mining.

MLOps Project for a Mask R-CNN on GCP using uWSGI Flask
MLOps on GCP - Solved end-to-end MLOps Project to deploy a Mask RCNN Model for Image Segmentation as a Web Application using uWSGI Flask, Docker, and TensorFlow.

End-to-End Snowflake Healthcare Analytics Project on AWS-2
In this AWS Snowflake project, you will build an end to end retraining pipeline by checking Data and Model Drift and learn how to redeploy the model if needed