Question: In this exercise we will generate simulated data and use it to fit a lasso model. Use the code from class, ISLR text, or a

In this exercise we will generate simulated data and use it to fit a lasso model. Use
the code from class, ISLR text, or a LLM to help with completing each task. [10
marks]
(a) Use the rnorm() function to generate a predictor X of length n =100, as well
as a noise vector of length n =100(Hint: make the standard deviation
much smaller for generating the noise vector ). Just paste your code, not all
the data values in your answer.
(b) Generate a response vector Y of length n =100 according to the model
Y =\beta 0+\beta 1X +\beta 2X2+\beta 3X3+,
where \beta 0,\beta 1,\beta 2 and \beta 3 are constants of your choice. Just paste your code in
your response, not all the generated data.
(c) Create a data frame with the response variable Y and the predictors
X, X2, X3,..., X10. Run the following code, replacing Y and data with your
response variable and data frame name and paste the output as your answer
to this part.
library(glmnet)
x <- model.matrix(Y ~ ., data = data)[,-1]
lasso.model <- cv.glmnet(x, Y, alpha =1)
plot(lasso.model)
best_lambda <- lasso.model$lambda.min
lasso.coef <- predict(lasso.model, s = best_lambda, type = "coefficients")
# Print the best lambda and coefficients
print(paste("Best lambda:", best_lambda))
print("Lasso Coefficients:")
print(lasso.coef).
(d) Explain what the code in part (c) is doing. You will need to lookup what
the cv.glmnet() function does and research cross-validation. This can be
completed with a few sentences. How close are the coefficients to the actual
coefficients you chose in (b)?

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!