【问题标题】:R prediction of filler values (needed to generate smoothed curve from model)填充值的 R 预测(需要从模型生成平滑曲线)
【发布时间】:2020-06-13 19:35:43
【问题描述】:

我正在尝试使用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))

【问题讨论】:

    标签: r ggplot2 model predict nls


    【解决方案1】:

    如果你在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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多