Yan*_* Li 11 regression r
我知道如何在R中进行基本多项式回归.但是,我只能使用nls或lm拟合一条最小化误差的线.
这在大多数情况下都有效,但有时当数据中存在测量间隙时,模型变得非常违反直觉.有没有办法添加额外的约束?
可重复的例子:
我想将模型拟合到以下组成的数据(类似于我的真实数据):
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)
Run Code Online (Sandbox Code Playgroud)
首先,让我们绘制它.
library(ggplot2)
points <- ggplot(df, aes(x,y)) + geom_point(size=4, col='red')
points
Run Code Online (Sandbox Code Playgroud)
看起来如果我们将这些点与一条线连接起来,它会改变方向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)
Run Code Online (Sandbox Code Playgroud)
看起来这个模型非常适合这个点...除了,因为我们的数据在63到166之间有很大的差距,所以有一个巨大的峰值,没有理由在模型中.(对于我的实际数据,我知道那里没有巨大的峰值)
所以这个案子的问题是:
如果那是不可能的,那么另一种方法是:
或许还有更好的模型可供使用?(除了分段执行).我的目的是比较图形之间的模型特征.
该spline类型的功能完美匹配您的数据(但不进行预测的目的).样条曲线广泛用于CAD领域,有时它只适合数学中的数据点,与回归相比可能缺乏物理意义.在更多信息这里和在大背景的介绍在这里.
该example(spline)会告诉你很多花哨的例子,其实我用其中的一个.
此外,采样更多数据点然后拟合lm或nls回归预测更合理.
示例代码:
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)
Run Code Online (Sandbox Code Playgroud)
我能想到的另一种方法是约束回归中的参数范围,以便您可以获得预期范围内的预测数据.
一个非常简单的代码,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" )
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1555 次 |
| 最近记录: |