【问题标题】:plot logistic regression line over heat plot在热图上绘制逻辑回归线
【发布时间】:2017-11-05 16:36:31
【问题描述】:

我的数据是具有两个线性自变量的二进制数据。对于这两个预测变量,随着它们变大,会有更多的积极响应。我在热图中绘制了数据,显示了沿两个变量的积极响应的密度。右上角有最积极的反应,左下角有最消极的反应,两个轴上都有明显的梯度变化。

我想在热图上画一条线,显示逻辑回归模型预测正面和负面反应的可能性相同。 (我的模型格式为response~predictor1*predictor2+(1|participant)。)

我的问题:如何根据这个模型找出阳性响应率为 0.5 的线?

我尝试使用 predict(),但效果相反;我必须给它一个因子的值,而不是给出我想要的响应率。我还尝试使用我之前只有一个预测器 (function(x) (log(x/(1-x))-fixef(fit)[1])/fixef(fit)[2]) 时使用的函数,但我只能从中获取单个值,而不是一行,并且一次只能获取一个预测器的值。

【问题讨论】:

  • 有趣的问题!如果您提供示例数据,人们会更容易提供帮助,例如一个类似的逻辑回归模型,适合 R 中的一个示例数据集和您的绘图代码。我认为您可以通过找到拟合线性预测变量(在对数赔率标度上)为 0 的点来找到边界线,因此您可以使用一些非常基本的代数来找到满足 predictor2 值的方程给定一些predictor1 的值。
  • 其实我刚刚发现有人在这里写过代数:stats.stackexchange.com/a/159977/5443

标签: r plot regression prediction


【解决方案1】:

使用适合mtcars 数据集的简单示例逻辑回归模型和here 描述的代数,我可以使用以下方法生成具有决策边界的热图:

library(ggplot2)
library(tidyverse)
data("mtcars")

m1 = glm(am ~ hp + wt, data = mtcars, family = binomial)

# Generate combinations of hp and wt across their observed range. Only
#   generating 50 values of each here, which is not a lot but since each
#   combination is included, you get 50 x 50 rows 
pred_df = expand.grid(
    hp = seq(min(mtcars$hp), max(mtcars$hp), length.out = 50),
    wt = seq(min(mtcars$wt), max(mtcars$wt), length.out = 50)
)
pred_df$pred_p = predict(m1, pred_df, type = "response")


# For a given value of hp (predictor1), find the value of
#   wt (predictor2) that will give predicted p = 0.5
find_boundary = function(hp_val, coefs) {
    beta_0 = coefs['(Intercept)']
    beta_1 = coefs['hp']
    beta_2 = coefs['wt']
    boundary_wt =  (-beta_0 - beta_1 * hp_val) / beta_2
}


# Find the boundary value of wt for each of the 50 values of hp
# Using the algebra in the linked question you can instead find
# the slope and intercept of the boundary, so you could potentially
# skip this step
boundary_df = pred_df %>%
    select(hp) %>%
    distinct %>%
    mutate(wt = find_boundary(hp, coef(m1)))


ggplot(pred_df, aes(x = hp, y = wt)) +
    geom_tile(aes(fill = pred_p)) +
    geom_line(data = boundary_df)

制作:

请注意,这仅考虑模型的固定效应,因此如果您想以某种方式考虑随机效应,这可能会更复杂。

【讨论】:

    猜你喜欢
    • 2021-11-23
    • 2016-01-07
    • 2016-08-09
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 2014-03-16
    相关资源
    最近更新 更多