Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python
  • R Language
  • Python for Data Science
  • NumPy
  • Pandas
  • OpenCV
  • Data Analysis
  • ML Math
  • Machine Learning
  • NLP
  • Deep Learning
  • Deep Learning Interview Questions
  • Machine Learning
  • ML Projects
  • ML Interview Questions
Open In App
Next Article:
Regression using k-Nearest Neighbors in R Programming
Next article icon

How Neural Networks are used for Regression in R Programming?

Last Updated : 21 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Neural networks consist of simple input/output units called neurons (inspired by neurons of the human brain). These input/output units are interconnected and each connection has a weight associated with it. Neural networks are flexible and can be used for both classification and regression. In this article, we will see how neural networks can be applied to regression problems.

Regression helps in establishing a relationship between a dependent variable and one or more independent variables. Regression models work well only when the regression equation is a good fit for the data. Most regression models will not fit the data perfectly. Although neural networks are complex and computationally expensive, they are flexible and can dynamically pick the best type of regression, and if that is not enough, hidden layers can be added to improve prediction. 

Stey by Step Implementation in R

Now let us construct a neural network in R programming that solves a regression problem. We will use the Boston dataset to predict the median value of owner-occupied homes (per 1000 dollars). 

Step 1: Load the dataset as follows

R
# Import Required packages set.seed(500) library(neuralnet) library(MASS)  # Boston dataset from MASS data <- Boston 

Step 2: Before feeding the data into a neural network, it is good practice to perform normalization. There is a number of ways to perform normalization. We will use the min-max method and scale the data in the interval [0,1]. The data is then split into training (75%) and testing (25%) set.

R
# Normalize the data maxs <- apply(data, 2, max)  mins <- apply(data, 2, min) scaled <- as.data.frame(scale(data, center = mins,                                scale = maxs - mins))  # Split the data into training and testing set index <- sample(1:nrow(data), round(0.75 * nrow(data))) train_ <- scaled[index,] test_ <- scaled[-index,] 

Step 3: Now, we can create a neural network using the neuralnet library. Modify the parameters and calculate the mean squared error (MSE). Use the parameters with the least MSE. We will use two hidden layers having 5 and 3 neurons. The number of neurons should be between the input layer size and the output layer size, usually 2/3 of the input size. However, modifying and testing the neural network, again and again, is the best way to find the parameters that best fit your model. When this neural network is trained, it will perform gradient descent to find coefficients that fit the data until it arrives at the optimal weights (in this case regression coefficients) for the model.

R
# Build Neural Network nn <- neuralnet(medv ~ crim + zn + indus + chas + nox                  + rm + age + dis + rad + tax +                  ptratio + black + lstat,                  data = train_, hidden = c(5, 3),                  linear.output = TRUE)  # Predict on test data pr.nn <- compute(nn, test_[,1:13])  # Compute mean squared error pr.nn_ <- pr.nn$net.result * (max(data$medv) - min(data$medv))                                                + min(data$medv) test.r <- (test_$medv) * (max(data$medv) - min(data$medv)) +                                                min(data$medv) MSE.nn <- sum((test.r - pr.nn_)^2) / nrow(test_)  # Plot the neural network plot(nn) 

Output:

 Neural Networks are used for Regression in R Programming Output

Step 4: We can see in the plot that the black lines show connections between each layer with its weights and the blue lines show the bias added in each step. The neural network is essentially a black box so we cannot say much about the weights.

R
# Plot regression line plot(test.r, pr.nn_, col = "red",       main = 'Real vs Predicted') abline(0, 1, lwd = 2) 

Output:

 Neural Networks are used for Regression in R Programming Output

We can see that the predictions (red circles) made by the neural network are in general concentrated around the line (a perfect alignment with the line would indicate an MSE of 0 and thus an ideal prediction).



Next Article
Regression using k-Nearest Neighbors in R Programming

A

akshisaxena
Improve
Article Tags :
  • AI-ML-DS
  • Machine Learning
  • R Language
  • data-science
Practice Tags :
  • Machine Learning

Similar Reads

  • How Neural Networks are used for Classification in R Programming
    Neural Networks is a well known word in machine learning and data science. Neural networks are used almost in every machine learning application because of its reliability and mathematical power. In this article let's deal with applications of neural networks in classification problems by using R pr
    4 min read
  • Single Layered Neural Networks in R Programming
    Neural networks also known as neural nets is a type of algorithm in machine learning and artificial intelligence that works the same as the human brain operates. The artificial neurons in the neural network depict the same behavior of neurons in the human brain. Neural networks are used in risk anal
    5 min read
  • Building a Simple Neural Network in R Programming
    The term Neural Networks refers to the system of neurons either organic or artificial in nature. In artificial intelligence reference, neural networks are a set of algorithms that are designed to recognize a pattern like a human brain. They interpret sensory data through a kind of machine perception
    12 min read
  • Regression using k-Nearest Neighbors in R Programming
    Machine learning is a subset of Artificial Intelligence that provides a machine with the ability to learn automatically without being explicitly programmed. The machine in such cases improves from the experience without human intervention and adjusts actions accordingly. It is primarily of 3 types:
    5 min read
  • Regression and its Types in R Programming
    Regression analysis is a statistical tool to estimate the relationship between two or more variables. There is always one response variable and one or more predictor variables. Regression analysis is widely used to fit the data accordingly and further, predicting the data for forecasting. It helps b
    5 min read
  • Elastic Net Regression in R Programming
    Elastic Net regression is a classification algorithm that overcomes the limitations of the lasso(least absolute shrinkage and selection operator) method which uses a penalty function in its L1 regularization. Elastic Net regression is a hybrid approach that blends both penalizations of the L2 and L1
    3 min read
  • Decision Tree for Regression in R Programming
    Decision tree is a type of algorithm in machine learning that uses decisions as the features to represent the result in the form of a tree-like structure. It is a common tool used to visually represent the decisions made by the algorithm. Decision trees use both classification and regression. Regres
    4 min read
  • Multi Layered Neural Networks in R Programming
    A series or set of algorithms that try to recognize the underlying relationship in a data set through a definite process that mimics the operation of the human brain is known as a Neural Network. Hence, the neural networks could refer to the neurons of the human, either artificial or organic in natu
    6 min read
  • Polynomial Regression in R Programming
    Polynomial Regression is a form of linear regression in which the relationship between the independent variable x and dependent variable y is modeled as an nth degree polynomial. Polynomial regression fits a nonlinear relationship between the value of x and the corresponding conditional mean of y, d
    4 min read
  • Random Forest Approach for Regression in R Programming
    Random Forest approach is a supervised learning algorithm. It builds the multiple decision trees which are known as forest and glue them together to urge a more accurate and stable prediction. The random forest approach is similar to the ensemble technique called as Bagging. In this approach, multip
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences