jnn*_*nns 9 r curve-fitting nls lm
我有几个似乎有对数关系的数据点(x和y).
> mydata
x y
1 0 123
2 2 116
3 4 113
4 15 100
5 48 87
6 75 84
7 122 77
> qplot(x, y, data=mydata, geom="line")
Run Code Online (Sandbox Code Playgroud)

现在我想找到一个适合图形的基础函数,并允许我推断其他数据点(即3或82).我读到了lm,nls但我真的没有到达任何地方.
起初,我创建了一个函数,我认为它最像是情节:
f <- function(x, a, b) {
a * exp(b *-x)
}
x <- seq(0:100)
y <- f(seq(0:100), 1,1)
qplot(x,y, geom="line")
Run Code Online (Sandbox Code Playgroud)

之后,我尝试使用nls以下方法生成拟合模型:
> fit <- nls(y ~ f(x, a, b), data=mydata, start=list(a=1, b=1))
Error in numericDeriv(form[[3]], names(ind), env) :
Missing value or an Infinity produced when evaluating the model
Run Code Online (Sandbox Code Playgroud)
有人能指出我在这方面做什么的正确方向吗?
跟进
阅读您的意见和周围远一点谷歌搜索后,我调整了首发的参数a,b并且c然后突然模型收敛.
fit <- nls(y~f(x,a,b,c), data=data.frame(mydata), start=list(a=1, b=30, c=-0.3))
x <- seq(0,120)
fitted.data <- data.frame(x=x, y=predict(fit, list(x=x))
ggplot(mydata, aes(x, y)) + geom_point(color="red", alpha=.5) + geom_line(alpha=.5) + geom_line(data=fitted.data)
Run Code Online (Sandbox Code Playgroud)

也许为您的模型使用立方规格并估算通过lm会给您一个很好的拟合.
# Importing your data
dataset <- read.table(text='
x y
1 0 123
2 2 116
3 4 113
4 15 100
5 48 87
6 75 84
7 122 77', header=T)
# I think one possible specification would be a cubic linear model
y.hat <- predict(lm(y~x+I(x^2)+I(x^3), data=dataset)) # estimating the model and obtaining the fitted values from the model
qplot(x, y, data=dataset, geom="line") # your plot black lines
last_plot() + geom_line(aes(x=x, y=y.hat), col=2) # the fitted values red lines
# It fits good.
Run Code Online (Sandbox Code Playgroud)
