2016-09-14 3 views
4

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 

그리고 그들은 매우 다르다. 아무도 이유를 아나요? 도움을 위해 미리 감사드립니다.

사무엘

+0

,'mse.1' 테스트 MSE입니다 'mse.2'는 선택된 모델의 교차 검증 오류입니다 - 그러나 훈련 데이터에만 근거합니다. – alistaire

+0

이 점을 지적 해 주셔서 감사합니다. 올바른 순서는 훈련 데이터를 통해 cv.glmnet을 실행하여 최상의 람다를 얻은 다음 MSE에 대해 방법 1을 사용하는 것입니다. cvm (평균 유효성 검사 오류)을 취하기 위해 테스트 데이터를 통해 cv.glmnet을 두 번 다시 실행하는 것이 좋지 않다고 생각합니까? 죄송합니다. 조금 혼란 스럽습니다. – chogall

+0

교차 검증을 사용하면 테스트 데이터에 사용할 람다 값을 계산하기 위해 테스트 오류를 ​​추정 할 수 있습니다. 테스트 데이터는 한 번만 터치해야합니다. – alistaire

답변

1

으로 그래서, 당신은 교차 검증에서 MSE는 (훈련) 주름이보고 된 두 번째 경우, MSE를 계산하기 위해 테스트 데이터를 사용하는 첫 번째 경우에, @alistaire 지적 사과와 사과 비교가 아닙니다.

우리는 사과와 사과를 비교 (훈련 폴드에 맞는 값을 유지함)하기 위해 다음과 같이 할 수 있으며 같은 훈련 폴드에서 계산하면 mse.1과 mse.2가 정확히 동일하다는 것을 알 수 있습니다 (값이 내 바탕 화면의 R 버전 3.1.2, x86_64에-W64-mingw32, 윈도우 10, 당신에서 약간의 차이가 있지만) : 내가 제대로 읽고 있어요 경우

# 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 
# keep the fitted values on the training folds 
pr.lasso = cv.glmnet(xtrain,ytrain,type.measure='mse', keep=TRUE, alpha=1) 
lambda.lasso = pr.lasso$lambda.min 
lambda.id <- which(pr.lasso$lambda == pr.lasso$lambda.min) 

# get the predicted values on the training folds with lambda.min (not from test data) 
mse.1 = mse(pr.lasso$fit[,lambda.id], ytrain) 
cat("MSE (method 1): ", mse.1, "\n") 

MSE (method 1): 0.6044496 

# 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 (method 2): 0.6044496 

mse.1 == mse.2 
[1] TRUE 
+0

답장을 보내 주셔서 감사합니다. @sandipan. 그래서 cv.glmnet은 기본적으로 10 배를 사용합니다. 훨씬 더 많은 수의 접기를 지정하면 교차 유효성 검사의 결과가 더 나아질 것입니까? – chogall

+0

폴드 수가 많으면 overfitting으로 이어질 수 있습니다. 훈련을 위해 더 많은 데이터를 얻고 있기 때문입니다. –

+0

자, 기본값은 K = 10으로 두는 것이 가장 좋습니다. 아니면 최적의 폴드 수를 찾는 방법이 있습니까? – chogall

관련 문제