R에서 loess 회귀를 수행하는 방법(예제 포함)


LOESS 회귀 (때때로 로컬 회귀라고도 함)는 로컬 조정을 사용하여 회귀 모델을 데이터 세트에 맞추는 방법입니다.

다음 단계별 예제에서는 R에서 LOESS 회귀를 수행하는 방법을 보여줍니다.

1단계: 데이터 생성

먼저 R에서 다음 데이터 프레임을 생성해 보겠습니다.

 #view DataFrame
df <- data. frame (x=c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14),
                 y=c(1, 4, 7, 13, 19, 24, 20, 15, 13, 11, 15, 18, 22, 27))

#view first six rows of data frame
head(df)

  xy
1 1 1
2 2 4
3 3 7
4 4 13
5 5 19
6 6 24

2단계: 여러 LOESS 회귀 모델 적합

loess() 함수를 사용하면 다양한 LOESS 회귀 모델을 이 데이터세트에 적용할 수 있으며, 범위 매개 변수에 대해 서로 다른 값을 사용할 수 있습니다.

 #fit several LOESS regression models to dataset
loess50 <- loess(y ~ x, data=df, span= .5 )
smooth50 <- predict(loess50) 

loess75 <- loess(y ~ x, data=df, span= .75 )
smooth75 <- predict(loess75) 

loess90 <- loess(y ~ x, data=df, span= .9 )
smooth90 <- predict(loess90) 

#create scatterplot with each regression line overlaid
plot(df$x, df$y, pch= 19 , main=' Loess Regression Models ')
lines(smooth50, x=df$x, col=' red ')
lines(smooth75, x=df$x, col=' purple ')
lines(smooth90, x=df$x, col=' blue ')
legend(' bottomright ', legend=c(' .5 ', ' .75 ', ' .9 '),
        col=c(' red ', ' purple ', ' blue '), pch= 19 , title=' Smoothing Span ')

R의 황토 회귀

span 에 사용하는 값이 낮을수록 회귀 모델이 덜 “부드럽게” 되고 모델이 데이터 포인트에 더 많이 맞추려고 시도합니다.

3단계: K-폴드 교차 검증을 사용하여 최상의 모델 찾기

사용할 최적의 범위 값을 찾으려면 캐럿 패키지의 함수를 사용하여 k-겹 교차 검증을 수행할 수 있습니다.

 library (caret)

#define k-fold cross validation method
ctrl <- trainControl(method = " cv ", number = 5 )
grid <- expand. grid (span = seq( 0.5 , 0.9 , len = 5 ), degree = 1 )

#perform cross-validation using smoothing spans ranging from 0.5 to 0.9
model <- train(y ~ x, data = df, method = " gamLoess ", tuneGrid=grid, trControl = ctrl)

#print results of k-fold cross-validation
print (model)

14 samples
 1 predictor

No pre-processing
Resampling: Cross-Validated (5 fold) 
Summary of sample sizes: 12, 11, 11, 11, 11 
Resampling results across tuning parameters:

  span RMSE Rsquared MAE      
  0.5 10.148315 0.9570137 6.467066
  0.6 7.854113 0.9350278 5.343473
  0.7 6.113610 0.8150066 4.769545
  0.8 17.814105 0.8202561 11.875943
  0.9 26.705626 0.7384931 17.304833

Tuning parameter 'degree' was held constant at a value of 1
RMSE was used to select the optimal model using the smallest value.
The final values used for the model were span = 0.7 and degree = 1.

RMSE( 제곱평균제곱근 오차 )의 가장 낮은 값을 생성한 범위 값이 0.7 임을 알 수 있습니다.

따라서 최종 LOESS 회귀 모델의 경우 loess() 함수의 범위 인수에 0.7 값을 사용하도록 선택합니다.

추가 리소스

다음 튜토리얼은 R의 회귀 모델에 대한 추가 정보를 제공합니다.

R에서 단순 선형 회귀를 수행하는 방법
R에서 다중 선형 회귀를 수행하는 방법
R에서 로지스틱 회귀를 수행하는 방법
R에서 분위수 회귀를 수행하는 방법
R에서 가중 회귀를 수행하는 방법

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다