3

我有 5 个 (x,y) 数据点,我正在尝试找到一个最佳拟合解决方案,该解决方案由两条相交于一点 (x0,y0) 的线组成,并且遵循以下等式:

y1 = (m1)(x1 - x0) + y0
y2 = (m2)(x2 - x0) + y0

具体来说,我要求交集必须出现在 x=2 和 x=3 之间。看一下代码:

#Initialize x1, y1, x2, y2
x1 <- c(1,2)
y1 <- c(10,10)

x2 <- c(3,4,5)
y2 <- c(20,30,40)

g <- c(TRUE, TRUE, FALSE, FALSE, FALSE)

q <- nls(c(y1, y2) ~ ifelse(g == TRUE, m1 * (x1 - x0) + y0, m2 * (x2 - x0) + y0), start = c(m1 = -1, m2 = 1, y0 = 0, x0 = 2), algorithm = "port", lower = c(m1 = -Inf, m2 = -Inf, y0 = -Inf, x0 = 2), upper = c(m1 = Inf, m2 = Inf, y0 = Inf, x0 = 3))
coef <- coef(q)
m1 <- coef[1]
m2 <- coef[2]
y0 <- coef[3]
x0 <- coef[4]

#Plot the original x1, y1, and x2, y2
plot(x1,y1,xlim=c(1,5),ylim=c(0,50))
points(x2,y2)

#Plot the fits
x1 <- c(1,2,3,4,5)
fit1 <- m1 * (x1 - x0) + y0
lines(x1, fit1, col="red")

x2   <- c(1,2,3,4,5)
fit2 <- m2 * (x2 - x0) + y0
lines(x2, fit2, col="blue")

因此,您可以看到那里列出的数据点。然后,我通过我的 nls 运行它,获取我的参数m1, m2, x0, y0(斜率和交点)。

但是,看看解决方案: 在此处输入图像描述

显然,红线(应该仅基于前 2 点)不是前 2 点的最佳拟合线。这与蓝线(第二次拟合)相同,它应该取决于最后 3 点)。这里有什么问题?

4

2 回答 2

3

这是分段回归:

# input data

x1 <- c(1,2); y1 <- c(10,10); x2 <- c(3,4,5);  y2 <- c(20,30,40) 
x  <- c(x1, x2); y <- c(y1, y2)

# segmented regression

library(segmented)
fm <- segmented.lm(lm(y ~ x), ~ x, NA, seg.control(stop.if.error = FALSE, K = 2))
summary(fm)

# plot

plot(fm)
points(y ~ x)

请参阅?lm?segmented.lm了解?seg.control更多信息。

于 2011-08-19T23:46:48.803 回答
2

我不完全确定出了什么问题,但我可以通过重新安排一些事情来让它工作。请注意?nls关于“不要在人工“零残差”数据上使用'nls'。 ”中的评论。我加了一点噪音。

## Initialize x1, y1, x2, y2
x1 <- c(1,2)
y1 <- c(10,10)

x2 <- c(3,4,5)
y2 <- c(20,30,40)

## make single x, y vector
x <- c(x1,x2)
set.seed(1001)
## (add a bit of noise to avoid zero-residual artificiality)
y <- c(y1,y2)+rnorm(5,sd=0.01)

g <- c(TRUE,TRUE,FALSE,FALSE,FALSE) ## specify identities of points

## particular changes:
##   * you have lower=upper=2 for x0.  Did you want 2<x0<3?
##   * specified data argument explicitly (allows use of predict() etc.)
##   * changed name from 'q' to 'fit1' (avoid R built-in function)
fit1 <- nls(y ~ ifelse(g,m1,m1+delta_m)*(x - x0) + y0,
         start = c(m1 = -1, delta_m = 2, y0 = 0, x0 = 2),
         algorithm = "port",
         lower = c(m1 = -Inf, delta_m = 0, y0 = -Inf, x0 = 2),
         upper = c(m1 = Inf, delta_m = Inf, y0 = Inf, x0 = 3),
         data=data.frame(x,y))

#Plot the original 'data'
plot(x,y,col=rep(c("red","blue"),c(2,3)),
           xlim=c(1,5),ylim=c(0,50))

## add predicted values
xvec <- seq(1,5,length.out=101)
lines(xvec,predict(fit1,newdata=data.frame(x=xvec)))

编辑:基于ifelse点标识的子句,而不是 x 位置

编辑:更改为要求第二个斜率>第一个斜率

再看一遍,我认为上面的问题可能是由于使用了单独的向量 forx1x2above,而不是单个x向量:我怀疑这些被 R 复制以匹配g向量,这会使事情变得很糟糕很糟糕。例如,这个精简的示例:

g <- c(TRUE, TRUE, FALSE, FALSE, FALSE)
ifelse(g,x1,x2)
## [1] 1 2 5 3 4

显示在子句中使用之前被x2扩展到。最可怕的部分是通常会收到如下警告:(3 4 5 3 4)ifelse

> x2 + 1:5
[1] 4 6 8 7 9
Warning message:
In x2 + 1:5 :
  longer object length is not a multiple of shorter object length

但在这种情况下没有警告......

于 2011-08-19T22:34:54.837 回答