拟合和绘制R中的非线性回归

时间:2016-11-03 22:19:16

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

我试图将非线性函数拟合到给定的数据集(代码片段中的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")

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

Initial graph

但是当我尝试使用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))

这就是我所看到的:

Plotted curve

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

1 个答案:

答案 0 :(得分:0)

R翻译完全按照你的要求去做。

x是未排序的数组。

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

lines(x, predict(fitmodel))按给定顺序连接点。它连接(x [1],预测(fitmodel)[1])到(x [2],预测(fitmodel)[2])到(x [3],预测(fitmodel)[3])等等。点不按x排序,您可以在图中看到图片。

根据Zheyuan Li的建议,你可能会ind <- order(x); x <- x[ind]; y <- 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.您无法合理地估算您的点数有这样的功能。

相关问题