The Wayback Machine - https://web.archive.org/web/20241121164006/https://www.geeksforgeeks.org/elastic-net-regression-in-r-programming/
Open In App

Elastic Net Regression in R Programming

Last Updated : 28 Jul, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 regularization of lasso and ridge methods.

It finds an estimator in a two-stage procedure i.e first for each fixed λ2 it finds the ridge regression coefficients and then does a lasso regression type shrinkage which does a double amount of shrinkage which eventually leads to increased bias and poor predictions. Rescaling the coefficients of the naive version of the elastic net by multiplying the estimated coefficients by (1 + λ2) is done to improve the prediction performance. Elastic Net regression is used in:

  • Metric learning
  • Portfolio optimization
  • Cancer prognosis

Elastic Net regression always aims at minimizing the following loss function:

formula elastic net

Elastic Net also allows us to tune the alpha parameter where alpha = 0 corresponds to Ridge regression and alpha = 1 to Lasso regression. Similarly, when alpha = 0, the penalty function reduces to the L1(ridge) regularization, and when alpha = 1, the penalty function reduces to L2(lasso) regularization. Therefore, we can choose an alpha value between 0 and 1 to optimize the Elastic Net and this will shrink some coefficients and set some to 0 for sparse selection. In Elastic Net regression, the lambda hyper-parameter is mostly and heavily dependent on the alpha hyper-parameter. Now let’s implement elastic net regression in R programming.

Implementation in R

The Dataset

mtcars(motor trend car road test) comprises fuel consumption, performance and 10 aspects of automobile design for 32 automobiles. It comes pre-installed with dplyr package in R.




# Installing the package
install.packages("dplyr")
    
# Loading package
library(dplyr)
    
# Summary of dataset in package
summary(mtcars)


Output:
output

Performing Elastic Net Regression on Dataset

Using the Elastic Net regression algorithm on the dataset by training the model using features or variables in the dataset.




# Installing Packages
install.packages("dplyr")
install.packages("glmnet")
install.packages("ggplot2")
install.packages("caret")
  
# X and Y datasets
X <- mtcars %>% 
     select(disp) %>% 
     scale(center = TRUE, scale = FALSE) %>% 
     as.matrix()
Y <- mtcars %>% 
    select(-disp) %>% 
    as.matrix()
  
# Model Building : Elastic Net Regression
control <- trainControl(method = "repeatedcv",
                              number = 5,
                              repeats = 5,
                              search = "random",
                              verboseIter = TRUE)
  
# Training ELastic Net Regression model
elastic_model <- train(disp ~ .,
                           data = cbind(X, Y),
                           method = "glmnet",
                           preProcess = c("center", "scale"),
                           tuneLength = 25,
                           trControl = control)
  
elastic_model
  
# Model Prediction
x_hat_pre <- predict(elastic_model, Y)
x_hat_pre
  
# Multiple R-squared
rsq <- cor(X, x_hat_pre)^2
rsq
  
# Plot
plot(elastic_model, main = "Elastic Net Regression")


Output:

  • Training of Elastic Net Regression model:
    output

    The Elastic Net regression model is trained to find the optimum alpha and lambda values.

  • Model elastic_model:
    output

    The Elastic Net regression model uses the alpha value as 0.6242021 and lambda value as 1.801398. RMSE was used to select the optimal model using the smallest value.

  • Model Prediction:
    output

    The model is predicted using the Y dataset and values are shown.

  • Multiple R-Squared:
    output

    The multiple R-Squared values of disp is 0.9514679.

  • Plot:
    output

    The mixing percentage is plotted with RMSE scores with different values of the regularization parameter.

  • So, Elastic Net regression applications are used in many sectors of industry and with full capacity.



    Previous Article
    Next Article

Similar Reads

Implementation of Elastic Net Regression From Scratch
Prerequisites: Linear RegressionGradient DescentLasso & Ridge RegressionIntroduction: Elastic-Net Regression is a modification of Linear Regression which shares the same hypothetical function for prediction. The cost function of Linear Regression is represented by J. [Tex]\frac{1}{m} \sum_{i=1}^{m}\left(y^{(i)}-h\left(x^{(i)}\right)\right)^{2}[
5 min read
Lasso vs Ridge vs Elastic Net | ML
Bias: Biases are the underlying assumptions that are made by data to simplify the target function. Bias does help us generalize the data better and make the model less sensitive to single data points. It also decreases the training time because of the decrease in complexity of target function High bias suggest that there is more assumption taken on
6 min read
Implementation of Lasso, Ridge and Elastic Net
In this article, we will look into the implementation of different regularization techniques. First, we will start with multiple linear regression. For that, we require the python3 environment with sci-kit learn and pandas preinstall. We can also use google collaboratory or any other jupyter notebook environment.First, we need to import some packag
7 min read
ML | Linear Regression vs Logistic Regression
Linear Regression is a machine learning algorithm based on supervised regression algorithm. Regression models a target prediction value based on independent variables. It is mostly used for finding out the relationship between variables and forecasting. Different regression models differ based on – the kind of relationship between the dependent and
3 min read
How to improve the performance of segmented regression using quantile regression in R?
Segmented regression, also known as piecewise or broken-line regression is a powerful statistical technique used to identify changes in the relationship between a dependent variable and one or more independent variables. Quantile regression, on the other hand, estimates the conditional quantiles of a response variable distribution in the linear mod
8 min read
Is least squares regression the same as linear regression
Yes, Least squares regression and linear regression are closely related in machine learning, but they’re not quite the same. Linear regression is a type of predictive model that assumes a linear relationship between input features and the output variable. Least squares is a common method used to find the best-fitting line in linear regression by mi
2 min read
The Difference between Linear Regression and Nonlinear Regression Models
areRegression analysis is a fundamental tool in statistical modelling used to understand the relationship between a dependent variable and one or more independent variables. Two primary types of regression models are linear regression and nonlinear regression. This article delves into the key differences between these models, their applications, an
7 min read
Elastic Load Balancer in AWS
In simplest terms, cloud computing means storing and accessing the data and programs on remote servers that are hosted on the internet instead of the computer’s hard drive or local server. It is also referred to as Internet-based computing. What are Amazon Web Services?Amazon Web Services is a subsidiary of Amazon.com that provides on-demand cloud
5 min read
Poisson Regression in R Programming
A Poisson Regression model is used to model count data and model response variables (Y-values) that are counts. It shows which X-values work on the Y-value and more categorically, it counts data: discrete data with non-negative integer values that count something. In other words, it shows which explanatory variables have a notable effect on the res
2 min read
Logistic Regression in R Programming
Logistic regression in R Programming is a classification algorithm used to find the probability of event success and event failure. Logistic regression is used when the dependent variable is binary(0/1, True/False, Yes/No) in nature. The logit function is used as a link function in a binomial distribution. A binary outcome variable's probability ca
8 min read
Regression Analysis in R Programming
In statistics, Logistic Regression is a model that takes response variables (dependent variable) and features (independent variables) to determine the estimated probability of an event. A logistic model is used when the response variable has categorical values such as 0 or 1. For example, a student will pass/fail, a mail is a spam or not, determini
6 min read
Perform Linear Regression Analysis in R Programming - lm() Function
lm() function in R Language is a linear model function, used for linear regression analysis. Syntax: lm(formula) Parameters: formula: model description, such as x ~ y Example 1: # R program to illustrate # lm function # Creating two vectors x and y x <- c(rep(1:20)) y <- x * 2 # Calling lm() function to # fit a linear model f <- lm(x ~ y)
1 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, denoted E(y|x). Basically it adds the quadratic or
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, multiple trees are generated by bootstrap samples from t
3 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 businesses and organizations to learn about the beh
5 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: Supervised machine learningUnsupervised machine le
5 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. Regression trees are used when the dependent variable is
4 min read
Quantile Regression in R Programming
Quantile Regression is an algorithm that studies the impact of independent variables on different quantiles of the dependent variable distribution. Quantile Regression provides a complete picture of the relationship between Z and Y. It is robust and effective to outliers in Z observations. In Quantile Regression, the estimation and inferences are d
3 min read
How to Include Factors in Regression using R Programming?
Categorical variables (also known as a factor or qualitative variables) are variables that classify observational values into groups. They are either string or numeric are called factor variables in statistical modeling. Saving normal string variables as factors save a lot of memory. Factors can also be stored as level or label variables. They have
4 min read
How to Include Interaction in Regression using R Programming?
In this article, we will look into what is Interaction, and should we use interaction in our model to get better results or not. Include Interaction in Regression using R Let's say X1 and X2 are features of a dataset and Y is the class label or output that we are trying to predict. Then, If X1 and X2 interact, this means that the effect of X1 on Y
5 min read
Lasso Regression in R Programming
Lasso regression is a classification algorithm that uses shrinkage in simple and sparse models(i.e models with fewer parameters). In Shrinkage, data values are shrunk towards a central point like the mean. Lasso regression is a regularized regression algorithm that performs L1 regularization which adds a penalty equal to the absolute value of the m
11 min read
Ridge Regression in R Programming
Ridge regression is a classification algorithm that works in part as it doesn’t require unbiased estimators. Ridge regression minimizes the residual sum of squares of predictors in a given model. Ridge regression includes a shrinks the estimate of the coefficients towards zero. Ridge Regression in R Ridge regression is a regularized regression algo
5 min read
Regression with Categorical Variables in R Programming
Regression is a multi-step process for estimating the relationships between a dependent variable and one or more independent variables also known as predictors or covariates. Regression analysis is mainly used for two conceptually distinct purposes: for prediction and forecasting, where its use has substantial overlap with the field of machine lear
7 min read
How Neural Networks are used for Regression in R Programming?
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 ap
4 min read
R-squared Regression Analysis in R Programming
For the prediction of one variable’s value(dependent variable) through other variables (independent variables) some models are used that are called regression models. For further calculating the accuracy of this prediction another mathematical tool is used, which is R-squared Regression Analysis or the coefficient of determination. The value of R-s
5 min read
UGC-NET | UGC NET CS 2018 July - II | Question 70
Consider a hash table of size seven, with starting index zero, and a hash function (7x+3) mod 4. Assuming the hash table is initially empty, which of the following is the contents of the table when the sequence 1, 3, 8, 10 is inserted into the table using closed hashing ? Here “__” denotes an empty location in the table. (A) 3, 10, 1, 8, __ , __ ,
1 min read
Competitive Programming vs General Programming
Programming enthusiasts face a crossroads - Competitive Programming or General Programming? This article sheds light on the distinctions between Competitive Programming vs General Programming, offering a quick guide for those navigating the coding landscape. Whether you're aiming for speed and precision in competitions or tackling real-world projec
3 min read
Dynamic Programming in Game Theory for Competitive Programming
In the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive edge. Whether you're a seasoned coder or a newcomer
15+ min read
What is the Relation Between R Programming and Hadoop Programming?
The relation between R programming and Hadoop revolves around integrating R with the Hadoop ecosystem to analyze large datasets that are stored in a Hadoop environment. R, primarily used for statistical analysis and data visualization, is not inherently built for handling big data. However, when combined with Hadoop, it can leverage Hadoop's distri
3 min read
Multiple Linear Regression using R
Prerequisite: Simple Linear-Regression using RLinear Regression: It is the basic and commonly used type for predictive analysis. It is a statistical approach for modeling the relationship between a dependent variable and a given set of independent variables.These are of two types: Simple linear RegressionMultiple Linear Regression Let's Discuss Mul
3 min read
three90RightbarBannerImg