R语言-正规化回归预测-ridge & lasso (ridge & lasso regression in r)

废话不多说,直接附上code
影片含有程序码详细解说,若有误再烦请告知,谢谢/images/emoticon/emoticon25.gif

library(glmnet)
library(dplyr)
library(ggplot2)
data(iris)
iris <- iris[,-c(5)]
#检查离群值
par(mfrow=c(1,3))
boxplot(iris$Sepal.Width)$out
boxplot(iris$Petal.Length)$out
boxplot(iris$Petal.Width)$out
#随机抽样
n <- nrow(iris)
set.seed(1117)
subiris <- sample(seq_len(n), size = round(0.7 * n))
traindata <- iris[subiris,]%>% as.matrix()
testdata <- iris[ - subiris,]%>% as.matrix()
trainx <- traindata[,c(2:4)]
trainy <- traindata[,c(1)]
testx <- testdata[,c(2:4)]
testy <- testdata[,c(1)]

#调参 lamda
ridge <- cv.glmnet(x = trainx,y = trainy,alpha = 0)
#交叉验证 预设k=10,alpha = 0为ridge, =1为lasso
ridge
#视觉化&选自变量
coef(ridge, s = "lambda.min") %>% 
  as.matrix() %>% 
  as.data.frame() %>% 
  add_rownames(var = "var") %>% 
  `colnames<-`(c("var","coef")) %>%
  filter(var != "(Intercept)") %>%  #剔除截距项
  top_n(3, wt = coef) %>% 
  ggplot(aes(coef, reorder(var, coef))) +
  geom_bar(stat = "identity", width=0.2,
           color="blue", fill=rgb(0.1,0.4,0.5,0.7))+
  xlab("Coefficient") +
  ylab(NULL)

#预测
future <- predict(ridge,newx = testx, s = ridge$lambda.min)
future <- as.data.frame(future)
final <- cbind(future,testy) %>% data.frame()
final <- mutate(final,mape=abs(X1-testy)/testy)
mean(final$mape)

<<:  [Day 22] 从GEIT建立政策及组织结构

>>:  厉害的教学影片,看完对电脑会有全面的了解

[Day 15] 针对网页的单元测试(一)

我们之前做的单元测试, 比较接近针对API的测试, 那我们现在要开始针对网页来做测试, 我们首先针对...

30天程序语言研究

今天是30天程序语言研究的第二十三天,由於资料库开发的部分我是负责前端所以想说顺便多练习一下其他开发...

「Wordpress 外挂开发」替你的上帝下订单,上帝模式撰写

我们最後一个主题,也是基於woocommerce,要制作出可以在bill的部分制作出可以代替别人制做...

Day11 - this&Object Prototypes Ch3 Objects - Contents - Existence

作者说明了两种确认 object 特定 property 是否存在的方式 in operator:p...

[Day13] Flutter with GetX qr_flutter & qr_code_scanner

产生QRCode qr_flutter Page的部分 用column分配元件位置  中间的QrIm...