#========================================================# # Quantitative ALM, Financial Econometrics & Derivatives # ML/DL using R, Python, Tensorflow by Sang-Heon Lee # # https://kiandlee.blogspot.com #——————————————————–# # Cross Validation of Lasso : Gaussian Regression #========================================================# library(glmnet) graphics.off() # clear all graphs rm(list = ls()) # remove all files from your workspace set.seed(1234) #============================================ # data : x and y #============================================ data(QuickStartExample) # built-in data nfolds = 5 # number of folds #============================================ # cross validation by using cv.glmnet #============================================ cvfit – cv.glmnet( x, y, family = “gaussian”, type.measure = “mse” , nfolds = nfolds, keep = TRUE # returns foldid ) # two lambda from cv.glmnet cvfit$lambda.min; cvfit$lambda.1se x11(); plot(cvfit) #============================================ # cross validation by hand #============================================ # get a vector of fold id used in cv.glmnet # to replicate the same result. # Therefore, this is subject to the change foldid – cvfit$foldid # from glmnet # candidate lambda range fit – glmnet(x, y, family = “gaussian”) v.lambda – fit$lambda nla – length(v.lambda) m.mse – matrix(0, nrow = nfolds, ncol=nla) #——————————- # iteration over all folds #——————————- for (i in 1:nfolds) { # training fold : tr # validation fold : va ifd – which(foldid==i) # i-th fold tr.x – x[–ifd,]; tr.y – y[–ifd] va.x – x[ifd,]; va.y – y[ifd] # estimation using training fold fit – glmnet(tr.x, tr.y, family = “gaussian”, … Read more