R预测填充值(需要从模型生成平滑曲线)

问题描述 投票:0回答:1

我正在尝试使用predict()填充值(行包含x值和y值作为NaN)来填充包含数据的绘图中的预测曲线。这个想法是要获得比仅使用数据x值更平滑的预测曲线。但是,predict()返回的时髦值似乎并不是基于y值的x计算。问题是:

  • 预测计算出了什么问题。
  • 如何设置数据框或更改代码以获取平滑线。

这是输出的样子(请注意错误预测的y值的下降):erroneously predicted values for least squares non-linear regression

这里是产生可怕结果的代码:

library(ggplot2)
library(nlme)

# generate test data frame
x = c(0, 5, 100, 1000, 50, 200, 300, 500)
y = c(0, 3, 5, 6, NaN, NaN, NaN, NaN)
df=data.frame(x,y)


# a log model to fit the data
lF <- formula(y ~ Ymax-(Ymax-Y0)*exp(-k*x))

# nonlinear regression
model <- nls(lF, data=df,
             start=list(Ymax=3.0, k=0.01, Y0=0.3),
             na.action = na.omit)

# print out the model resutls
summary(model)

# Derive predicted lines
df$pred <- predict(model)

# plot the data and three models
ggplot(df, aes(x=x, y=y))+
     geom_point() +
     geom_line(aes(y=pred))
r ggplot2 model predict nls
1个回答
0
投票

如果您在newdata=df命令中指定参数prediction,则会得到:

# print out the model resutls
summary(model)
df$pred <- predict(model, newdata=df)

# plot the data and three models
ggplot(df, aes(x=x, y=y))+
     geom_point(color="red", size=3) +
     geom_line(aes(y=pred), size=1) +
     theme_bw()

enter image description here

如果要从模型中绘制一条平滑线,则需要定义合适的x值序列:

df2 <- data.frame(x=c(seq(0,1,0.001),1:1000))
df2$pred <- predict(model, newdata=df2)

ggplot(df, aes(x=x, y=y))+
     geom_point(color="red", size=3) +
     geom_line(data=df2, aes(x=x, y=pred), color="blue", size=1) +
     theme_bw()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.