2017-02-14 19 views
6

我想使用tidyverse和modelr軟件包計算一組數據的邏輯迴歸預測。很顯然,我在add_predictions中做錯了,因爲我沒有收到邏輯函數的「響應」,就像我在統計中使用「預測」函數一樣。這應該很簡單,但我無法弄清楚,多次搜索的結果都很少。使用modelr :: add_predictions glm

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)) 

回答

3

predict.glmtype參數默認爲"link",這add_predictions默認情況下不使用任何方式更改,也沒有提供給您切換到幾乎肯定需要的"response"。 (A GitHub issue exists;如果你願意的話,可以在它上面添加你的好代表)。也就是說,通過dplyr::mutate直接在整個範圍內使用predict並不難。

另外請注意,ggplot強制default(一個因子)爲數字爲了繪製線條,這很好,除了「否」和「是」被替換爲1和2,而由predict返回的概率將介於0和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))