【问题标题】:Using modelr::add_predictions for glm为 glm 使用 modelr::add_predictions
【发布时间】:2017-07-02 04:08:57
【问题描述】:

我正在尝试使用 tidyverse 和 modelr 包计算一组数据的逻辑回归预测。显然,我在add_predictions 中做错了什么,因为我没有像在统计数据中使用“预测”函数那样收到逻辑函数的“响应”。这应该很简单,但我想不通,多次搜索收效甚微。

library(tidyverse)
library(modelr)
options(na.action = na.warn)
library(ISLR)

d <- as_tibble(ISLR::Default)
model <- glm(default ~ balance, data = d, family = binomial)
grid <- d %>% data_grid(balance) %>% add_predictions(model)

ggplot(d, aes(x=balance)) + 
    geom_point(aes(y = default)) + 
    geom_line(data = grid, aes(y = pred))

【问题讨论】:

    标签: r glm tidyverse modelr


    【解决方案1】:

    predict.glm 的type 参数默认为"link",默认情况下add_predictions 不会更改,也不会为您提供任何更改为几乎肯定需要的"response" 的方法。 (A GitHub issue exists;如果你愿意,可以在上面添加你漂亮的代表。)也就是说,通过dplyr::mutate 在tidyverse 中直接使用predict 并不难。

    还请注意,ggplot 将 default(一个因子)强制为数字以绘制线条,这很好,除了“否”和“是”被 1 和 2 替换,而返回的概率为predict 将介于 0 和 1 之间。显式强制转换为数字并减去 1 可修复绘图,但需要额外调用 scale_y_continuous 来修复标签。

    library(tidyverse)
    library(modelr)
    
    d <- as_tibble(ISLR::Default)
    model <- glm(default ~ balance, data = d, family = binomial)
    
    grid <- d %>% data_grid(balance) %>% 
        mutate(pred = predict(model, newdata = ., type = 'response'))
    
    ggplot(d, aes(x = balance)) + 
        geom_point(aes(y = as.numeric(default) - 1)) + 
        geom_line(data = grid, aes(y = pred)) + 
        scale_y_continuous('default', breaks = 0:1, labels = levels(d$default))
    

    另外请注意,如果你想要的只是一个情节,geom_smooth 可以直接为你计算预测:

    ggplot(d, aes(balance, as.numeric(default) - 1)) + 
        geom_point() + 
        geom_smooth(method = 'glm', method.args = list(family = 'binomial')) + 
        scale_y_continuous('default', breaks = 0:1, labels = levels(d$default))
    

    【讨论】:

    • 使用刚刚发布的modelr 中的version 0.1.4,您可以添加type,例如:add_predictions(data, model, var = "pred", type = NULL)
    猜你喜欢
    • 1970-01-01
    • 2018-11-15
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多