【问题标题】:Fitting and plotting non linear regression in R [duplicate]在R中拟合和绘制非线性回归[重复]
【发布时间】:2017-03-17 16:02:26
【问题描述】:

我正在尝试将非线性函数拟合到给定的数据集(代码 sn-p 中的 x 和 y),该函数定义为

f(x) = a/((sin((x-b)/2))^4)
x <- c(0, 5, -5, 10, -10, 15, -15, 20, -20, 25, -25, 30, -30)
y <- c(4.21, 3.73, 2.08, 1.1, 0.61, 0.42, 0.13, 0.1, 0.04, 0.036667, 0.016667, 0.007778, 0.007778)
plot(x,y, log="y")

这就是我在提到函数之前应该拟合的初始图的样子。

但是当我尝试使用 nls 拟合并绘制曲线时,图形看起来不太正确

f <- function(x,a,b) { a/((sin((x-b)/2))^4) }
fitmodel <- nls (y ~ f(x,a,b), start=list(a=1,b=1))
lines(x, predict(fitmodel))

这是我看到的:

我很确定我在这里做错了什么,并感谢您的帮助。

【问题讨论】:

  • @ZheyuanLi 是对的——例如看看plot(x,y, log="y", type="l") 看看为什么会这样。然后比较plot(x[order(x)],y[order(x)], log="y", type="l")
  • 我认为先订购 y,然后订购 x,即y &lt;- y[order(x)]; x[order(x)]
  • 内联修复:lines(sort(x), predict(fitmodel)[order(x)])
  • 感谢您的帮助,图表看起来肯定更好,至少。不幸的是,这个功能是给我的,所以我对此无能为力。

标签: r plot non-linear-regression model-fitting


【解决方案1】:

R 解释器完全按照您的指示去做。

x 是未排序的数组。

因此,predict(fitmodel) 对这些未排序的点进行预测。

lines(x, predict(fitmodel)) 按给定顺序连接点。它将 (x[1], predict(fitmodel)[1]) 连接到 (x[2], predict(fitmodel)[2]) 到 (x[3], predict(fitmodel)[3]) 等。点不是按x排序的,你看图中的图片。

你可以按照李哲元的建议做ind &lt;- order(x); x &lt;- x[ind]; y &lt;- y[ind]

此外,您的模型毫无意义。

f <- function(x,a,b) { a/((sin((x-b)/2))^4) }
fitmodel <- nls (y ~ f(x,a,b), start=list(a=1,b=1))

对于任何abf 将是一个周期为 2π 的周期函数,而您的 x 在第 5 步中从 -30 变为 30。您无法使用这样的函数合理地近似您的点。

【讨论】:

    猜你喜欢
    • 2019-12-06
    • 2016-07-09
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 2021-05-31
    • 2019-01-14
    相关资源
    最近更新 更多