R 在glm中包含线性相关特征
我有一个训练集,其中x列代表正在进行比赛的特定体育场。很明显,这些列在训练集中是线性相关的,因为比赛必须在至少一个体育场进行 然而,我的问题是,如果我通过测试数据,它可能包括一个在训练数据中看不到的体育场。因此,我希望将所有x列都包含在训练GRLM中,这样每个体育场的平均系数为零。然后,如果看到一个新体育场,它基本上会得到所有体育场系数的平均值 我遇到的问题是,R glm函数似乎检测到我的训练集中有线性相关列,并将其中一个系数设置为NA,以使其余系数线性独立。我如何: 停止在glm函数中为我的一列插入NA系数,并确保所有体育场系数总和为0 一些示例代码R 在glm中包含线性相关特征,r,glm,R,Glm,我有一个训练集,其中x列代表正在进行比赛的特定体育场。很明显,这些列在训练集中是线性相关的,因为比赛必须在至少一个体育场进行 然而,我的问题是,如果我通过测试数据,它可能包括一个在训练数据中看不到的体育场。因此,我希望将所有x列都包含在训练GRLM中,这样每个体育场的平均系数为零。然后,如果看到一个新体育场,它基本上会得到所有体育场系数的平均值 我遇到的问题是,R glm函数似乎检测到我的训练集中有线性相关列,并将其中一个系数设置为NA,以使其余系数线性独立。我如何: 停止在glm函数中为我的一
# Past observations
outcome = c(1 ,0 ,0 ,1 ,0 ,1 ,0 ,0 ,1 ,0 ,1 )
skill = c(0.1,0.5,0.6,0.3,0.1,0.3,0.9,0.6,0.5,0.1,0.4)
stadium_1 = c(1 ,1 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 )
stadium_2 = c(0 ,0 ,1 ,1 ,1 ,1 ,1 ,0 ,0 ,0 ,0 )
stadium_3 = c(0 ,0 ,0 ,0 ,0 ,0 ,0 ,1 ,1 ,1 ,1 )
train_glm_data = data.frame(outcome, skill, stadium_1, stadium_2, stadium_3)
LR = glm(outcome ~ . - outcome, data = train_glm_data, family=binomial(link='logit'))
print(predict(LR, type = 'response'))
# New observations (for a new stadium we have not seen before)
skill = c(0.1)
stadium_1 = c(0 )
stadium_2 = c(0 )
stadium_3 = c(0 )
test_glm_data = data.frame(outcome, skill, stadium_1, stadium_2, stadium_3)
print(predict(LR, test_glm_data, type = 'response'))
# Note that in this case, the observation is simply the same as if we had observed stadium_3
# Instead I would like it to be an average of all the known stadiums coefficients
# If they all sum to 0 this is essentially already done for me
# However if not then the stadium_3 coefficient is buried somewhere in the intercept term
train_glm_data$stadium要估计所有虚拟变量的系数,可以在公式中添加“-1”,这将删除截距:
LR = glm(outcome ~ . - outcome - 1, data = train_glm_data, family=binomial(link='logit'))
系数:
coef(LR)
# skill stadium_1 stadium_2 stadium_3
# -2.8080177 0.8424053 0.7541226 1.1313135
对于看不见的训练级别问题,@hack-r提出了一些好主意。另一个想法是为新观测的所有虚拟变量插补1/n
(其中n
是观测体育场的数量)。您拟合的glm
模型是什么?如果你能提供一个最小的可复制的例子,这会很有帮助
coef(LR)
# skill stadium_1 stadium_2 stadium_3
# -2.8080177 0.8424053 0.7541226 1.1313135