R 中的多项式回归 - 对曲线有额外的约束

Polynomial regression in R - with extra constraints on the curve

我知道如何在 R 中进行基本的多项式回归。但是,我只能使用 nlslm 来拟合一条线,使点的误差最小化。

这在大多数情况下都有效,但有时当数据中存在测量差距时,模型会变得非常反直觉。有没有办法添加额外的约束?

可重现示例:

我想将模型拟合到以下编造的数据(类似于我的真实数据):

x <- c(0, 6, 21, 41, 49, 63, 166)
y <- c(3.3, 4.2, 4.4, 3.6, 4.1, 6.7, 9.8)
df <- data.frame(x, y)

首先,让我们绘制它。

library(ggplot2)
points <- ggplot(df, aes(x,y)) + geom_point(size=4, col='red')
points

看起来如果我们用一条线连接这些点,它会改变方向 3 次,所以让我们尝试用四次拟合它。

lm <- lm(formula = y ~ x + I(x^2) + I(x^3) + I(x^4))
quartic <- function(x)  lm$coefficients[5]*x^4 + lm$coefficients[4]*x^3 + lm$coefficients[3]*x^2 + lm$coefficients[2]*x + lm$coefficients[1]

points + stat_function(fun=quartic)

看起来模型非常适合这些点...除了,因为我们的数据在 63 和 166 之间有很大的差距,所以那里有一个巨大的尖峰,没有理由出现在模型中。 (根据我的实际数据,我知道那里没有巨大的峰值)

所以本例中的问题是:

如果那不可能,那么另一种方法是:

或者也许可以使用更好的模型? (除了分段进行之外)。我的目的是比较图表之间模型的特征。

spline 类型的函数将完美匹配您的数据(但不用于预测目的)。样条曲线广泛应用于CAD领域,有时它只是拟合数学中的数据点,与回归相比可能缺乏物理意义。 here and a great background introduction in here.

中的更多信息

example(spline) 会向您展示很多奇特的示例,实际上我使用了其中一个。

进一步,采样更多的数据点,然后通过lmnls回归拟合进行预测会更合理。

示例代码:

library(splines)

x <- c(0, 6, 21, 41, 49, 63, 166)
y <- c(3.3, 4.2, 4.4, 3.6, 4.1, 6.7, 9.8)

s1 <- splinefun(x, y, method = "monoH.FC")

plot(x, y)
curve(s1(x), add = TRUE, col = "red", n = 1001)

我能想到的另一种方法是限制回归中参数的范围,这样您就可以获得预期范围内的预测数据。

很简单的代码,下面有optim,只是一个选择。

dat <- as.data.frame(cbind(x,y))
names(dat) <- c("x", "y")

# your lm 
# lm<-lm(formula = y ~ x + I(x^2) + I(x^3) + I(x^4))

# define loss function, you can change to others 
 min.OLS <- function(data, par) {
      with(data, sum((   par[1]     +
                         par[2] *  x + 
                         par[3] * (x^2) +
                         par[4] * (x^3) +
                         par[5] * (x^4) +   
                         - y )^2)
           )
 }

 # set upper & lower bound for your regression
 result.opt <- optim(par = c(0,0,0,0,0),
                min.OLS, 
                data = dat, 
                lower=c(3.6,-2,-2,-2,-2),
                upper=c(6,1,1,1,1),
                method="L-BFGS-B"
  )

 predict.yy <- function(data, par) {
               print(with(data, ((
                    par[1]     + 
                    par[2] *  x +
                    par[3] * (x^2) +
                    par[4] * (x^3) + 
                    par[5] * (x^4))))
                )
  }

  plot(x, y, main="LM with constrains")
  lines(x, predict.yy(dat, result.opt$par), col="red" )

我会按照 eipi10 的建议进行局部回归。但是,如果您想要进行多项式回归,您可以尝试最小化惩罚平方和。

这是一个函数因偏离直线 "too much" 而受到惩罚的示例:

library(ggplot2)
library(maxLik)
x <- c(0, 6, 21, 41, 49, 63, 166)/100
y <- c(3.3, 4.2, 4.4, 3.6, 4.1, 6.7, 9.8)
df <- data.frame(x, y)
points <- ggplot(df, aes(x,y)) + geom_point(size=4, col='red')

polyf <- function(par, x=df$x) {
   ## the polynomial function
   par[1]*x + par[2]*x^2 + par[3]*x^3 + par[4]*x^4 + par[5]
}
quarticP <- function(x) {
   polyf(par, x)
}
## a evenly distributed set of points, penalize deviations on these
grid <- seq(range(df$x)[1], range(df$x)[2], length=10)

objectiveF <- function(par, kappa=0) {
   ## Calculate penalized sum of squares: penalty for deviating from linear
   ## prediction
   PSS <- sum((df$y - polyf(par))^2) + kappa*(pred1 - polyf(par))^2 
   -PSS
}

## first compute linear model prediction
res1 <- lm(y~x, data=df)
pred1 <- predict(res1, newdata=data.frame(x=grid))
points <- points + geom_smooth(method='lm',formula=y~x)
print(points)

## non-penalized function
res <- maxBFGS(objectiveF, start=c(0,0,0,0,0))
par <- coef(res)
points <- points + stat_function(fun=quarticP, col="green")
print(points)

## penalty
res <- maxBFGS(objectiveF, start=c(0,0,0,0,0), kappa=0.5)
par <- coef(res)
points <- points + stat_function(fun=quarticP, col="yellow")
print(points)

惩罚为 0.5 的结果如下所示: 您可以调整惩罚,以及grid,偏差被惩罚的位置。

Ott Toomets 源代码对我不起作用,存在一些错误。这是更正后的版本(不使用 ggplot2):

library(maxLik)
x <- c(0, 6, 21, 41, 49, 63, 166)/100
y <- c(3.3, 4.2, 4.4, 3.6, 4.1, 6.7, 9.8)
df <- data.frame(x, y)

polyf <- function(par, x=df$x) {
  ## the polynomial function
  par[1]*x + par[2]*x^2 + par[3]*x^3 + par[4]*x^4 + par[5]
}
quarticP <- function(x) {
  polyf(par, x)
}
## a evenly distributed set of points, penalize deviations on these
grid <- seq(range(df$x)[1], range(df$x)[2], length=10)

objectiveF <- function(par, kappa=0) {
  ## Calculate penalized sum of squares: penalty for deviating from linear
  ## prediction
  PSS <- sum((df$y - polyf(par))^2) + kappa*(pred1 - polyf(par, x=grid))^2 
  -PSS
}

plot(x,y, ylim=c(0,10))

## first compute linear model prediction
res1 <- lm(y~x, data=df)
pred1 <- predict(res1, newdata=data.frame(x=grid))
coefs = coef(res1)
names(coefs) = NULL
constant = coefs[1]
xCoefficient = coefs[2]
par = c(xCoefficient,0,0,0,constant)

curve(quarticP, from=0, to=2, col="black", add=T)


## non-penalized function
res <- maxBFGS(objectiveF, start=c(0,0,0,0,0))
par <- coef(res)
curve(quarticP, from=0, to=2, col="red", add=T)

## penalty
res2 <- maxBFGS(objectiveF, start=c(0,0,0,0,0), kappa=0.5)
par <- coef(res2)
curve(quarticP, from=0, to=2, col="green", add=T)