保存 R 的 loess() 模型?

Saving the model of R's loess()?

我有一个使用 R 的 loess() 函数拟合的模型。

有没有办法以某种形式保存或提取模型,这样我就可以在另一个脚本中使用它(通过 predict()),而不需要用于拟合的原始数据?

假设您有以下模型:

set.seed(69)

df <- data.frame(x = 1:10, y = rnorm(10))

my_model <- loess(y ~ x, df)

模型是完整的,并且包含再现性所需的所有数据,您可以使用 dput:

查看这些数据
dput(my_model)
#> structure(list(n = 10L, fitted = c(0.326732521143027, -0.110249341375308, 
#> -0.5129070962872, -1.0245028344818, -0.515520311385236, 0.936834208165912, 
#> 1.02529173682113, -0.0325363615379678, -0.925858641095554, -1.79331515361539
#> ), residuals = c(`1` = -0.249567149174745, `2` = 0.484564908411681, 
#> `3` = 0.178093195928771, `4` = 0.0746138620473938, `5` = -0.424689773472765, 
#> `6` = 0.252788906835992, `7` = 0.418801764499952, `8` = -0.871410368375438, 
#> `9` = -0.240996764699026, `10` = 0.222241837709625), enp = 4.9507127595997, 
#>     s = 0.635987915064919, one.delta = 4.00725442163284, two.delta = 3.74265436940279, 
#>     trace.hat = 5.47172916898343, divisor = 1, robust = c(1, 
#>     1, 1, 1, 1, 1, 1, 1, 1, 1), pars = list(span = 0.75, degree = 2L, 
#>         normalize = TRUE, parametric = FALSE, drop.square = FALSE, 
#>         surface = "interpolate", cell = 0.2, family = "gaussian", 
#>         trace.hat = "exact", iterations = 1L), kd = list(parameter = c(d = 1L, 
#>     n = 10L, vc = 2L, nc = 19L, nv = 11L, liv = 1049L, lv = 849L
#>     ), a = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 1L, 
#>     0L, 0L, 0L, 0L, 0L, 0L, 0L), xi = c(5, 3, 8, 2, 4, 7, 9, 
#>     1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0), vert = c(0.955, 10.045
#>     ), vval = c(0.345367102568788, -0.45469139983717, -1.83201089325508, 
#>     -0.858718571224215, -0.515520311385236, 0.688784281802855, 
#>     -0.5129070962872, -0.258927828125719, -0.0325363615379678, 
#>     -0.715456285854514, -0.110249341375308, -0.401210278764226, 
#>     -1.0245028344818, 0.00604222878595367, 1.02529173682113, 
#>     -0.443278504696964, -0.925858641095554, -0.85553623203908, 
#>     0.326732521143027, -0.454333729158981, 0.936834208165912, 
#>     0.472504615586807)), call = loess(formula = y ~ x, data = df), 
#>     terms = y ~ x, xnames = c(x = "x"), x = structure(1:10, .Dim = c(10L, 
#>     1L), .Dimnames = list(c("1", "2", "3", "4", "5", "6", "7", 
#>     "8", "9", "10"), "x")), y = c(`1` = 0.0771653719682824, `2` = 0.374315567036373, 
#>     `3` = -0.33481390035843, `4` = -0.949888972434407, `5` = -0.940210084858001, 
#>     `6` = 1.1896231150019, `7` = 1.44409350132108, `8` = -0.903946729913406, 
#>     `9` = -1.16685540579458, `10` = -1.57107331590576), weights = c(1, 
#>     1, 1, 1, 1, 1, 1, 1, 1, 1)), class = "loess")

所以你可以安全地做:

saveRDS(my_model, "my_loess.rds")

并使用

将模型加载到另一个脚本中
loaded_model <- readRDS("my_loess.rds")

loaded_model
#> Call:
#> loess(formula = y ~ x, data = df)
#> 
#> Number of Observations: 10 
#> Equivalent Number of Parameters: 4.95 
#> Residual Standard Error: 0.636 

reprex package (v0.3.0)

于 2020-07-25 创建