我希望能夠與h2o.glm
進行邏輯迴歸,包括因素之間的一些相互作用。然而,簡單的使用h2o.interaction
後跟h2o.glm
最終會在迴歸中包含太多虛擬變量。這是一個可重現的例子。如何在R2H2o包中包含h2o.interaction和h2o.glm因子的相互作用
# model.matrix function in R returns a matrix
# with the intercept, 1 dummy for Age, 1 dummy for Sex, and 1 dummy for Age:Sex
colnames(model.matrix(Survived ~ Age + Sex + Age:Sex, data = Titanic))
[1] "(Intercept)" "AgeAdult" "SexFemale" "AgeAdult:SexFemale"
# create an H2OFrame with the interaction of Age and Sex as a factor
library(h2o)
h2o.init()
Titanic.hex <- as.h2o(Titanic)
interact.hex <- h2o.cbind(Titanic.hex[,c("Survived","Age","Sex")]
,h2o.interaction(Titanic.hex
,factors = list(c("Age", "Sex"))
,pairwise = T
,max_factors = 99
,min_occurrence = 1))
# Age_Sex interaction column has 4 levels
h2o.levels(interact.hex$Age_Sex)
[1] "Child_Male" "Child_Female" "Adult_Male" "Adult_Female"
# Because Age_Sex interaction column has 4 levels
# we end up with 3 dummies to represent Age:Sex
interact.h2o.glm <- h2o.glm(2:ncol(interact.hex)
,"Survived"
,interact.hex
,family = 'binomial'
,lambda = 0)
h2o.varimp(interact.h2o.glm)$names
[1] "Age_Sex.Child_Female" "Age_Sex.Adult_Male" "Age_Sex.Adult_Female" "Sex.Male"
[5] "Age.Child" ""
什麼是做與H2O因素之間的相互作用的好方法使得h2o.glm
行爲就像model.matrix
?在上面的示例中,我希望看到Age
和Sex
之間的交互只有1個虛擬變量,而不是3個虛擬變量。
我也作爲單獨的答案添加了我的解決方法。 h2o.glm可以自動處理因素,但我必須做一個解決方法,以便實質上0 * 0 = 1 * 0 = 0 * 1 = 0.我的解決方法將3個級別0 * 0,1 * 0,0 * 1分解爲單一的水平。 – jmuhlenkamp
@jmuhlenkamp我想你會發現上面的代碼更有效率(並給出相同的值?),因爲我只使用H2O內置函數。如果我已經正確地理解了你的解決方案,那麼是「有H2O製造錯誤的數據,然後用R代碼修復它」? –
我的解決方案實際上只使用R代碼來製作level1字符矢量,然後應用h2o.ifelse來修復數據(我已更新我的ifelse爲h2o.ifelse以使其更清晰)。它絕不會將完整的數據從h2o傳回給R.對我來說也是可取的,因爲我的真實數據(未在此處發佈)具有許多類別的一些因素。在我的解決方法中,我只需要指定因素而不是具體的級別。 – jmuhlenkamp