R:绘制时间变量的预测和实际响应
R: Plot predicted and actual response over a time variable
我有一个模型,我想在其中绘制时间变量的预测。在同一图表中添加该时间点的平均响应也会非常有帮助。
这是一些可重现的数据。
set.seed(123)
x1 = rnorm(1000) # some continuous variables
x2 = rnorm(1000)
z = 1 + 2*x1 + 3*x2 # linear combination with a bias
pr = 1/(1+exp(-z)) # pass through an inv-logit function
y = rbinom(1000,1,pr) # bernoulli response variable
#valid glm:
df = data.frame(y=y,x1=x1,x2=x2,time=rep(seq(1:10),10))
fit = glm( y~x1+x2,data=df,family="binomial")
现在我想用 time
组绘制 mean(predict(fit,df,type="response"))
以及 time
组绘制 mean(y)
。
有什么提示或想法吗?
编辑:感谢您的回复!是的,我知道在这个例子中时间不在模型中。我只是想举一个简单的例子。在我的真实模型中,时间包括在内。是的,我想绘制随时间推移的平均响应和平均预测。
您是根据 x1
和 x2
而不是时间进行预测,因此每次都会有多个预测。如果你想绘制每次 mean(y)
和每次预测的平均值 y
(红色)你可以做
require(dplyr);require(reshape2);require(ggplot2)
df %>%
mutate(pred = predict(fit, df, type="response")) %>%
group_by(time) %>%
summarize_at(vars(y, pred), mean) %>%
melt(id = 'time') %>%
ggplot(aes(time, value, color = variable)) + geom_line()
对我来说,在模型中不包括时间的情况下,这似乎是一件奇怪的事情。下面是一种方法,计算 x 的平均值和预测的平均值。
library(tidyverse)
df$pred <- predict(fit)
means <- df %>%
group_by(time) %>%
summarize(mean_y = mean(y),
mean_pred = mean(pred)) %>%
gather(mean, val, -time)
ggplot(means, aes(time, val, color = mean)) +
geom_point() +
geom_line()
我有一个模型,我想在其中绘制时间变量的预测。在同一图表中添加该时间点的平均响应也会非常有帮助。
这是一些可重现的数据。
set.seed(123)
x1 = rnorm(1000) # some continuous variables
x2 = rnorm(1000)
z = 1 + 2*x1 + 3*x2 # linear combination with a bias
pr = 1/(1+exp(-z)) # pass through an inv-logit function
y = rbinom(1000,1,pr) # bernoulli response variable
#valid glm:
df = data.frame(y=y,x1=x1,x2=x2,time=rep(seq(1:10),10))
fit = glm( y~x1+x2,data=df,family="binomial")
现在我想用 time
组绘制 mean(predict(fit,df,type="response"))
以及 time
组绘制 mean(y)
。
有什么提示或想法吗?
编辑:感谢您的回复!是的,我知道在这个例子中时间不在模型中。我只是想举一个简单的例子。在我的真实模型中,时间包括在内。是的,我想绘制随时间推移的平均响应和平均预测。
您是根据 x1
和 x2
而不是时间进行预测,因此每次都会有多个预测。如果你想绘制每次 mean(y)
和每次预测的平均值 y
(红色)你可以做
require(dplyr);require(reshape2);require(ggplot2)
df %>%
mutate(pred = predict(fit, df, type="response")) %>%
group_by(time) %>%
summarize_at(vars(y, pred), mean) %>%
melt(id = 'time') %>%
ggplot(aes(time, value, color = variable)) + geom_line()
对我来说,在模型中不包括时间的情况下,这似乎是一件奇怪的事情。下面是一种方法,计算 x 的平均值和预测的平均值。
library(tidyverse)
df$pred <- predict(fit)
means <- df %>%
group_by(time) %>%
summarize(mean_y = mean(y),
mean_pred = mean(pred)) %>%
gather(mean, val, -time)
ggplot(means, aes(time, val, color = mean)) +
geom_point() +
geom_line()