基于glm拟合的estimated function含义及作业要求咨询
问题解答
关于estimated function的定义
你提到的estimated function既不是单独的随机截距,也不是原始拟合值,是每个被试对应的、以target.contrast为自变量的正确概率预测曲线:对0-1区间内任意取值的target.contrast,代入对应模型计算得到的正确响应概率,将这些点连起来的函数曲线就是要求的estimated function。
当前代码的问题
你当前拟合的是带随机截距的混合效应logistic模型,且直接绘制所有被试的原始自变量和拟合值的散点图,不符合「每个subject分别绘制」的要求,所有被试的结果会混在同一张图里无法区分。
实现方案
方案1:基于已拟合的混合效应模型生成
你已拟合的glmer模型中,每个被试有独立的随机截距,共享全局的target.contrast斜率,可以直接用这个模型生成每个被试的预测曲线,代码如下:
library(lme4) library(ggplot2) # 生成0-1区间的平滑自变量序列 new_x <- seq(0, 1, length.out = 100) # 为每个被试匹配所有自变量取值 new_data <- expand.grid(target.contrast = new_x, subject = unique(exp2_staircase$subject)) # 预测每个被试对应的正确概率 new_data$pred_prob <- predict(model1, newdata = new_data, type = "response") # 所有被试曲线放在同一张图 ggplot(new_data, aes(x = target.contrast, y = pred_prob, color = factor(subject))) + geom_line(linewidth = 1) + labs(x = "Target contrast", y = "Predicted probability of correct response", title = "Estimated logistic function per subject") + theme_minimal() # 若需要每个被试单独的子图,加上分面即可 # ggplot(new_data, aes(x = target.contrast, y = pred_prob)) + # geom_line(linewidth = 1, color = "steelblue") + # facet_wrap(~subject) + # labs(x = "Target contrast", y = "Predicted probability of correct response") + # theme_minimal()
方案2:每个被试单独拟合GLM(符合作业原文表述)
作业要求明确提到「基于将correct作为因变量、target.contrast作为自变量拟合的glm模型」,如果要求每个被试单独拟合独立的GLM,可使用如下代码实现:
library(dplyr) library(tidyr) library(ggplot2) library(purrr) # 按被试分组,每个组单独拟合GLM并生成预测值 plot_data <- exp2_staircase %>% nest(data = -subject) %>% # 每个被试拟合glm mutate(model = map(data, ~ glm(correct ~ target.contrast, data = .x, family = binomial)), # 生成预测值 pred = map(model, ~ data.frame(target.contrast = seq(0, 1, length.out = 100), pred_prob = predict(.x, newdata = data.frame(target.contrast = seq(0,1, length.out = 100)), type = "response")))) %>% unnest(pred) # 绘图 ggplot(plot_data, aes(x = target.contrast, y = pred_prob, color = factor(subject))) + geom_line(linewidth = 1) + labs(x = "Target contrast", y = "Predicted probability of correct response", title = "Estimated logistic function per subject (independently fitted GLM)") + theme_minimal()
内容的提问来源于stack exchange,提问作者Quantizer
相关产品推荐
相关产品推荐

