開始使用免費開始

從條件分配抽樣

直接對模型呼叫 predict(),在相同的自變數(預測因子)取值下,會回傳相同的結果。這會讓插補後的資料變異太小。為了增加變異,讓插補更能重現原始資料的變異,我們可以從條件分配中抽樣。也就是說,當模型輸出的機率大於 0.5 時,不是每次都預測 1,而是依據模型回傳的機率,從二項分配中抽樣產生預測值。

你會延續上一題寫的程式碼。以下這一行已被移除:

  preds <- ifelse(preds >= 0.5, 1, 0)

你的任務是用從二項分配抽樣來取代它。只要一行程式碼就能完成!

本練習屬於課程

在 R 中以插補處理遺漏值

檢視課程

練習說明

  • 透過從二項分配取樣,覆寫 preds
  • preds 的長度作為第一個引數傳入。
  • 將 size 設為 1。
  • prob 設為模型回傳的機率。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

 impute_logreg <- function(df, formula) {
  # Extract name of response variable
  imp_var <- as.character(formula[2])
  # Save locations where the response is missing
  missing_imp_var <- is.na(df[imp_var])
  # Fit logistic regression mode
  logreg_model <- glm(formula, data = df, family = binomial)
  # Predict the response
  preds <- predict(logreg_model, type = "response")
  # Sample the predictions from binomial distribution
  preds <- ___(___, size = ___, prob = ___)
  # Impute missing values with predictions
  df[missing_imp_var, imp_var] <- preds[missing_imp_var]
  return(df)
}
編輯並執行程式碼