lasso2 패키지의 전립선 암 데이터에 대해 다른 회귀 모델을 실행하려고합니다. 올가미를 사용하면 평균 제곱 오차를 계산하는 두 가지 방법을 발견했습니다. 하지만 그들은 나에게 아주 다른 결과를주었습니다. 그래서 나는 잘못된 것을하고 있는지 또는 단지 한 방법이 다른 것보다 낫다는 것을 알고 싶습니다.올가미 회귀 분석에서 왜 MSE를 계산하는 것이 다른 산출물을 제공합니까?
# Needs the following R packages.
library(lasso2)
library(glmnet)
# Gets the prostate cancer dataset
data(Prostate)
# Defines the Mean Square Error function
mse = function(x,y) { mean((x-y)^2)}
# 75% of the sample size.
smp_size = floor(0.75 * nrow(Prostate))
# Sets the seed to make the partition reproductible.
set.seed(907)
train_ind = sample(seq_len(nrow(Prostate)), size = smp_size)
# Training set
train = Prostate[train_ind, ]
# Test set
test = Prostate[-train_ind, ]
# Creates matrices for independent and dependent variables.
xtrain = model.matrix(lpsa~. -1, data = train)
ytrain = train$lpsa
xtest = model.matrix(lpsa~. -1, data = test)
ytest = test$lpsa
# Fitting a linear model by Lasso regression on the "train" data set
pr.lasso = cv.glmnet(xtrain,ytrain,type.measure='mse',alpha=1)
lambda.lasso = pr.lasso$lambda.min
# Getting predictions on the "test" data set and calculating the mean square error
lasso.pred = predict(pr.lasso, s = lambda.lasso, newx = xtest)
# Calculating MSE via the mse function defined above
mse.1 = mse(lasso.pred,ytest)
cat("MSE (method 1): ", mse.1, "\n")
# Calculating MSE via the cvm attribute inside the pr.lasso object
mse.2 = pr.lasso$cvm[pr.lasso$lambda == lambda.lasso]
cat("MSE (method 2): ", mse.2, "\n")
그래서이 내가 모두 MSE에 대한 얻은 출력은 다음과 같습니다
MSE (method 1): 0.4609978
MSE (method 2): 0.5654089
그리고 그들은 매우 다르다. 아무도 이유를 아나요? 도움을 위해 미리 감사드립니다.
사무엘
,'mse.1' 테스트 MSE입니다 'mse.2'는 선택된 모델의 교차 검증 오류입니다 - 그러나 훈련 데이터에만 근거합니다. – alistaire
이 점을 지적 해 주셔서 감사합니다. 올바른 순서는 훈련 데이터를 통해 cv.glmnet을 실행하여 최상의 람다를 얻은 다음 MSE에 대해 방법 1을 사용하는 것입니다. cvm (평균 유효성 검사 오류)을 취하기 위해 테스트 데이터를 통해 cv.glmnet을 두 번 다시 실행하는 것이 좋지 않다고 생각합니까? 죄송합니다. 조금 혼란 스럽습니다. – chogall
교차 검증을 사용하면 테스트 데이터에 사용할 람다 값을 계산하기 위해 테스트 오류를 추정 할 수 있습니다. 테스트 데이터는 한 번만 터치해야합니다. – alistaire