(g)lmのNA省略(デフォルトの挙動)でうっかりうっかり
データにうっかり欠損(NA)が入ってると、デフォルトでその行がモデル構築&予測結果からごっそり削られるうっかりミスを防止するための備忘録うっかりうっかり。
> library(dplyr) > #デフォルト(自分で設定したオプション値だけど)のNAなし時の挙動 > getOption("na.action") [1] "na.omit"
深い意味はない変形+欠損(NA)をirisに加える
> # 適当に追加のラベル(これを予測する) > df <- iris %>% mutate(label=c(rep(1, 75), rep(0, 75))) > df <- rbind(df, tail(df, 5) %>% mutate(Species=NA)) > #適当に欠損入れる > df[1:4, 2] <- NA > #データをチェック > head(df) Sepal.Length Sepal.Width Petal.Length Petal.Width Species label 1 5.1 NA 1.4 0.2 setosa 1 2 4.9 NA 1.4 0.2 setosa 1 3 4.7 NA 1.3 0.2 setosa 1 4 4.6 NA 1.5 0.2 setosa 1 5 5.0 3.6 1.4 0.2 setosa 1 6 5.4 3.9 1.7 0.4 setosa 1 > tail(df) Sepal.Length Sepal.Width Petal.Length Petal.Width Species label 150 5.9 3.0 5.1 1.8 virginica 0 151 6.7 3.0 5.2 2.3 <NA> 0 152 6.3 2.5 5.0 1.9 <NA> 0 153 6.5 3.0 5.2 2.0 <NA> 0 154 6.2 3.4 5.4 2.3 <NA> 0 155 5.9 3.0 5.1 1.8 <NA> 0 > #総行数(155) > nrow(df) [1] 155
このまま一般化回帰(回帰でも同じ)しちゃうと・・・
> model <- glm(factor(label) ~ Sepal.Length + Sepal.Width + Species, data = df, family=binomial) > summary(model) Call: glm(formula = factor(label) ~ Sepal.Length + Sepal.Width + Species, family = binomial, data = df) Deviance Residuals: Min 1Q Median 3Q Max -1.46047 -0.00005 -0.00003 0.00005 1.43731 Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 18.5831 2608.2132 0.007 0.994 Sepal.Length 0.7637 0.6688 1.142 0.254 Sepal.Width -0.5336 1.0893 -0.490 0.624 Speciesversicolor -21.6373 2608.2112 -0.008 0.993 Speciesvirginica -42.6643 3595.1381 -0.012 0.991 (Dispersion parameter for binomial family taken to be 1) Null deviance: 202.289 on 145 degrees of freedom Residual deviance: 67.956 on 141 degrees of freedom (9 observations deleted due to missingness) AIC: 77.956 Number of Fisher Scoring iterations: 19 > #総行数が155ではなくなっている(欠損分削除されている) > length(predict(model, type = "response")) [1] 146 > length(predict(model, newdata=df, type = "response")) [1] 155
データ削られてるので注意!(一番最後の実行結果はデータ数はいいが、中にNAが詰まってる)