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

R prediction of filler values (needed to generate smoothed curve from model)

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

这是输出的样子(注意错误预测的 y 值的下降):

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

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))

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

df$pred <- predict(model, newdata=df)

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

如果你想从模型中画出一条平滑的线,你需要定义一个合适的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()