LASSO(Least Absolute Shinkage and Selection Operator)
library(glmnet)
autoparts <- read.csv("C:/Users/user/Desktop/JBTP/autoparts.csv", header=T)
dim(autoparts)
## [1] 34139 17
autoparts1 <- autoparts[autoparts$prod_no=="90784-76001", -c(1:7)]
dim(autoparts1)
## [1] 21779 10
autoparts2 <- autoparts1[autoparts1$c_thickness < 1000, ]
dim(autoparts2)
## [1] 21767 10
# model.matix() 함수는 기본적으로 1로 채워진 y절편을 만듦
xmat <- model.matrix(c_thickness ~ fix_time + a_speed + b_speed + separation + s_separation + rate_terms + mpa + load_time + highpressure_time, data=autoparts2)
# 이것이 필요없다는 마지막에 [,-1]을 써서 제외시킴
xmat <- model.matrix(c_thickness ~ fix_time + a_speed + b_speed + separation + s_separation + rate_terms + mpa + load_time + highpressure_time, data=autoparts2)[,-1]
#반응변수 부분을 이해하기 쉽게 yvec 이름으로 저장
yvec <- autoparts2$c_thickness
#최대 100개의 람다를 만든다
#DF=계수의 수, %Dcv=설명력, Lambda=람다
#람다가 가능한 최소가 될 때까지 진행
fit.lasso <- glmnet(x=xmat, y=yvec, alpha=1, nlambda=100)
#k-fold 10회 수행
fit.lasso.cv <- cv.glmnet(x=xmat, y=yvec, nfold=10, alpha=1, lambda=fit.lasso$lambda)
plot(fit.lasso.cv)
***
#위에서 찾은 최적 람다(MSE를 가장 작게 만드는 람다)를 다른 이름으로 저장
fit.lasso.param <- fit.lasso.cv$lambda.min
#위에서 찾은 최적 람다를 이용하여 최종 lasso 모형을 만듦
fit.lasso.tune <- glmnet(x=xmat, y=yvec, alpha=1, lambda=fit.lasso.param)
#생성한 모델로 설명변수의 계수를 출력
#9개 변수가 모두 선택됨
coef(fit.lasso.tune)
## 10 x 1 sparse Matrix of class "dgCMatrix"
## s0
## (Intercept) 7.065200e+02
## fix_time 5.915140e-02
## a_speed -1.711912e+01
## b_speed 1.945994e+00
## separation -7.502414e-01
## s_separation -7.378120e-01
## rate_terms 1.051817e-02
## mpa -1.526025e-01
## load_time -1.507899e-01
## highpressure_time -1.877501e-05