有约束的NLS优化:曲线下面积相等 [英] NLS optimization with constraints : equal area under the curve

查看:106
本文介绍了有约束的NLS优化:曲线下面积相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条曲线,中间有干扰(在t = 9时),这会导致我的数据出现下降(t <9)和上升(t> 9).我想拟合一个指数函数并添加一个约束,使两者的面积(下坡度和上坡度)相等.

I have a curve with a disturbance in the middle (at t=9) which causes a downturn (t<9) and an upturn (t>9) in my data. I would like to fit an exponential function and add a constraint that the area of the two (downturn and upturn) are equal.

参见图:

我可以使用优化来拟合曲线,但是我无法找出约束.这应该是这样的:

I can fit the curve using optim, but I can't figure out the constraint. This should be something like:

其中f(x)是指数函数.

where f(x) is the exponential function.

我已经尝试过使用constrOptim,但是我也愿意使用其他求解器.

I've tried constrOptim, but I am open to using other solvers as well.


y <-c(170, 160, 145, 127, 117, 74, 76, 78, 101, 115, 120, 70, 64, 65)
t <- seq(1,14,1)

# starting values:
lm <-lm(log(y) ~ log(t))

# Exp. Least-Squares minimization:
func <-function(pars) {
  a <- pars["a"]
  b <- pars["b"]
  fitted <- a*exp(b*t)
  sum((y-fitted)^2)  
} 

a <-lm$coefficients[[1]]
b <-lm$coefficients[[2]]
c <- 

result <- optim(c(a=a, b=b), func)

# final parameters:
a <- result$par["a"]
b <- result$par["b"]


# predict values:
pred <- a*exp(b*t)
dat = data.frame(y=y, t=t, pred=pred)

library(ggplot2)
ggplot(dat, aes(x=t, y=y)) +
  geom_line() +
  geom_line(data=dat, aes(x=t, y=pred), color='blue')

我知道我需要将约束添加到上面的优化中.像这样:

I know I need to add the constraint to the optimization above. Like so:

i = 6:12

result <- optim(c(a=a, b=b), func, sum(y[i]-a*exp(b*t[i])=0)

但这似乎不起作用.优化函数不允许这种约束.

But this doesn't seem to be working. optim function does not allow constraints of this kind.

推荐答案

我可以建议将干扰建模为正弦波吗?

May I suggest modelling the disturbance as a sine wave?

fit <- nls(y ~ a * exp(b * t) + ifelse(d*(t - m) < 0 | d*(t - m) > 2 * pi, 0 , c * sin(d*(t - m))), 
           start = list(a = 170, b = -0.1, c = -20, d = 1, m = 5))
summary(fit)

dat <- data.frame(y=y, t=t)
preddat <- data.frame(t = seq(min(t), max(t), length.out = 100))
preddat$y <- predict(fit, preddat)
preddat$y1 <- coef(fit)[["a"]] * exp(coef(fit)[["b"]] * preddat$t)


library(ggplot2)
ggplot(dat, aes(x=t, y=y)) +
  geom_line() +
  geom_line(data=preddat, color='blue') +
  geom_line(data=preddat, aes(y = y1), color='red', linetype = 2)

我确定具有信号处理背景的人会提出比丑陋的ifelse骇客更好的东西.

I'm sure someone with a background in signal processing could come up with something better than the ugly ifelse hack.

这篇关于有约束的NLS优化:曲线下面积相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆