繁体   English   中英

R中的自动曲线拟合

[英]Automatic curve fitting in R

是否有任何包使用许多简单模型自动拟合曲线?
简单的模型我的意思是:

  • AX + B
  • 斧^ 2 + BX + C
  • a * log(x)+ b
  • 一个* X ^ N + B
  • AX /(1 + BX)
  • 斧^ N /(1 + BX ^ n)的
  • ...

最好的方法是使用一个带有两个向量参数X和Y的函数,并返回一个带有SSE的拟合简单模型列表。

尝试这个。 rhs是右侧的字符向量, xy是数据。 它为每个构造公式fo ,然后提取参数并将每个参数设置为1作为起始值。 最后它运行nls并返回已排序的SSE,以便结果是通过右侧命名的SSE的向量。 如果verbose=TRUE (默认情况下是这样),那么它还会显示每个拟合的输出。

sse <- function(rhs, x, y) sort(sapply(rhs, function(rhs, x, y, verbose = TRUE) {
    fo <- as.formula(paste("y", rhs, sep = "~"))
    nms <- setdiff(all.vars(fo), c("x", "y"))
    start <- as.list(setNames(rep(1, length(nms)), nms))
    fm <- nls(fo, data.frame(x, y), start = start)
    if (verbose) { print(fm); cat("---\n") }
    deviance(fm)
}, x = x, y = y))

## test

set.seed(123)
x <- 1:10
y <- rnorm(10, x)

# modify to suit
rhs <- c("a*x+b", "a*x*x+b*x+c")

sse(rhs, x, y)

您还可以查看提供评估分数多项式的函数的包。 到目前为止,这些似乎是mboost (使用函数FP )和mfp (使用函数mfp )。 虽然我没有尝试过这些软件包,但它们背后的理论非常符合您的要求。

mfp包在2005年的R-News中有所描述。

可能感兴趣的两个参考文献是

Royston P,Altman D(1994)使用连续协变量的分数多项式的回归。 Appl Stat。 3:429-467。

Sauerbrei W,Royston P(1999)建立多变量预测和诊断模型:通过使用分数多项式转换预测变量。 皇家统计学会期刊(系列A)162:71-94。

您可以通过手动调整几次自由度来拟合回归样条并找到合适的拟合。 尝试以下功能:

spline.fit <- function(x, y, df=5) {
  ## INPUT: x, y are two vectors (predictor and response);
  ##        df is the number of spline basis.  Increase "df" to fit more adaptively to the data.
  require(splines) # available as default R Package.
  bx <- bs(x, df)  # B-spline basis matrix as New Predictors (dimension is "length(x)" by "df")
  f <- lm(y ~ bx)  # Linear Regression on Spline Basis (that is, "df" number of new predictors)
  fy <- fitted(f)  # Fitted Response
  plot(x, y); lines(x, fy, col="blue", lwd=2) # Make a plot to show the fit.
  invisible(list(x=bx, y=fy, f=f))    # Return the Basis (new predictors), Fitted Y, Regression
}

if (F) {                                # Unit Test
  spline.fit(1:100, rnorm(100))
  spline.fit(1:100, rnorm(100), df=20)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM