your programing

R로 빌드 된 모델 재사용

lovepro 2020. 10. 14. 08:13
반응형

R로 빌드 된 모델 재사용


R에서 모델을 빌드 할 때 새 데이터에서 재사용 할 수 있도록 모델 사양을 어떻게 저장합니까? 과거 데이터에 대한 로지스틱 회귀를 작성했지만 다음 달까지 새로운 관측치가 없다고 가정 해 보겠습니다. 최선의 접근 방법은 무엇입니까?

내가 고려한 사항 :

  • 모델 객체 저장 및 새 세션에서로드
  • PMML로 일부 모델을 내보낼 수 있다는 것을 알고 있지만 PMML 가져 오기에 대해서는 실제로 보지 못했습니다.

간단히 말해서 새 세션에서 모델을 사용해야 할 때 수행하는 작업을 파악하려고합니다.

미리 감사드립니다.


새로운 관측치를 예측하기 위해 모델 재사용

모델에 계산 비용이 많이 들지 않으면 필요할 때 다시 실행하는 R 스크립트에 전체 모델 구축 프로세스를 문서화하는 경향이 있습니다. 모델 피팅에 임의의 요소가 포함 된 경우 알려진 임의의 시드를 설정해야합니다.

모델을 계산하는 데 계산 비용이 많이 든다면 위와 같이 여전히 스크립트를 사용하지만 save()into 및 rda 개체를 사용하여 모델 개체를 저장 합니다. 그런 다음 저장된 객체가 있으면로드하거나 그렇지 않은 경우 if()...else코드의 관련 부분을 감싸는 간단한 절을 사용하여 모델을 다시 맞추도록 스크립트를 수정하는 경향이 있습니다.

저장된 모델 객체를로드 할 때 필요한 패키지를 모두 다시로드해야합니다.하지만 귀하의 경우에는 로짓 모델이 적합하다면 glm()R 이상으로로드 할 추가 패키지가 없습니다.

다음은 그 예입니다.

> set.seed(345)
> df <- data.frame(x = rnorm(20))
> df <- transform(df, y = 5 + (2.3 * x) + rnorm(20))
> ## model
> m1 <- lm(y ~ x, data = df)
> ## save this model
> save(m1, file = "my_model1.rda")
> 
> ## a month later, new observations are available: 
> newdf <- data.frame(x = rnorm(20))
> ## load the model
> load("my_model1.rda")
> ## predict for the new `x`s in `newdf`
> predict(m1, newdata = newdf)
        1         2         3         4         5         6 
6.1370366 6.5631503 2.9808845 5.2464261 4.6651015 3.4475255 
        7         8         9        10        11        12 
6.7961764 5.3592901 3.3691800 9.2506653 4.7562096 3.9067537 
       13        14        15        16        17        18 
2.0423691 2.4764664 3.7308918 6.9999064 2.0081902 0.3256407 
       19        20 
5.4247548 2.6906722 

이것을 자동화하려면 스크립트에서 다음을 수행 할 것입니다.

## data
df <- data.frame(x = rnorm(20))
df <- transform(df, y = 5 + (2.3 * x) + rnorm(20))

## check if model exists? If not, refit:
if(file.exists("my_model1.rda")) {
    ## load model
    load("my_model1.rda")
} else {
    ## (re)fit the model
    m1 <- lm(y ~ x, data = df)
}

## predict for new observations
## new observations
newdf <- data.frame(x = rnorm(20))
## predict
predict(m1, newdata = newdf)

물론 데이터 생성 코드는 실제 데이터를로드하는 코드로 대체됩니다.

이전에 피팅 된 모델을 새로운 관측치로 업데이트

추가 새 관측치를 사용하여 모델을 재 적합하려는 경우. 다음 update()은 유용한 기능입니다. 이것이하는 일은 하나 이상의 모델 인수를 업데이트하여 모델을 다시 맞추는 것입니다. 모델을 맞추는 데 사용되는 데이터에 새 관찰을 포함하려면 인수에 전달 된 데이터 프레임에 새 관찰을 추가 'data'한 후 다음을 수행합니다.

m2 <- update(m1, . ~ ., data = df)

where m1 is the original, saved model fit, . ~ . is the model formula changes, which in this case means include all existing variables on both the left and right hand sides of ~ (in other words, make no changes to the model formula), and df is the data frame used to fit the original model, expanded to include the newly available observations.

Here is a working example:

> set.seed(123)
> df <- data.frame(x = rnorm(20))
> df <- transform(df, y = 5 + (2.3 * x) + rnorm(20))
> ## model
> m1 <- lm(y ~ x, data = df)
> m1

Call:
lm(formula = y ~ x, data = df)

Coefficients:
(Intercept)            x  
      4.960        2.222  

> 
> ## new observations
> newdf <- data.frame(x = rnorm(20))
> newdf <- transform(newdf, y = 5 + (2.3 * x) + rnorm(20))
> ## add on to df
> df <- rbind(df, newdf)
> 
> ## update model fit
> m2 <- update(m1, . ~ ., data = df)
> m2

Call:
lm(formula = y ~ x, data = df)

Coefficients:
(Intercept)            x  
      4.928        2.187

Other have mentioned in comments formula(), which extracts the formula from a fitted model:

> formula(m1)
y ~ x
> ## which can be used to set-up a new model call
> ## so an alternative to update() above is:
> m3 <- lm(formula(m1), data = df)

However, if the model fitting involves additional arguments, like 'family', or 'subset' arguments in more complex model fitting functions. If update() methods are available for your model fitting function (which they are for many common fitting functions, like glm()), it provides a simpler way to update a model fit than extracting and reusing the model formula.

If you intend to do all the modelling and future prediction in R, there doesn't really seem much point in abstracting the model out via PMML or similar.


If you use the same name of the dataframe and variables, you can (at least for lm() and glm() ) use the function update on the saved model :

Df <- data.frame(X=1:10,Y=(1:10)+rnorm(10))

model <- lm(Y~X,data=Df)
model

Df <- rbind(Df,data.frame(X=2:11,Y=(10:1)+rnorm(10)))

update(model)

This is off course without any preparation of the data and so forth. It just reuses the model specifications set. Be aware that if you change the contrasts in the meantime, the new model gets updated with the new contrasts, not the old.

So the use of a script is in most cases the better answer. One could include all steps in a convenience function that just takes the dataframe, so you can source the script and then use the function on any new dataset. See also the answer of Gavin for that.

참고URL : https://stackoverflow.com/questions/5118074/reusing-a-model-built-in-r

반응형