作者celestialgod (天)
看板R_Language
标题Re: [问题] Logistic Regression
时间Sun Feb 12 23:45:34 2017
※ 引述《markbaseball (Mark)》之铭言:
:
:
: [问题类型]:
:
: 程式谘询(我想用R 做某件事情,但是我不知道要怎麽用R 写出来)
:
: [软体熟悉度]:
: 请把以下不需要的部份删除
: 入门(写过其他程式,只是对语法不熟悉)
: [问题叙述]:
: 各位版上的大大们,我参照网路的写法尝试跑罗吉斯回归,
: model.3<-glm(Overpayment~rs+ni+asset+fcf+ocf,family=binomial(logit), data
: =mydata)
: 但是却出现错误讯息
: Warning message:
: glm.fit: fitted probabilities numerically 0 or 1 occurred
: 依照我的理解,程式是跟我说我的Overpayment一定要是0或1才可以。
: 可是,我很确定我的overpayment变数只有0和1两种结果而已啊!!
: 请问各位大大是否可以跟我说我错在哪里吗? 感激
:
: 选择性,也许未来有用
:
举个例子
set.seed(53)
N <- 100
p <- 3
x <- matrix(rnorm(N * p), N)
beta <- rnorm(p + 1)
logit <- function(x) 1 / (1 + exp(-x))
y <- logit(cbind(1, x) %*% beta) > 0.5
# y这种生成方法保证用现在的x可完美切开0, 1
# 意思是y=1算出来的机率一定是1,y=0算出来的机率一定是0
# 不懂再往下看
glmFit <- glm(y ~ x, family = binomial(logit),
control = glm.control(maxit = 100))
# Warning message:
# glm.fit: fitted probabilities numerically 0 or 1 occurred
table(round(fitted(glmFit), 6)) # fitted这个函数会得到fitted机率
# 0 1
# 94 6
可以看到机率不是0就是1
正常情况下应该是下面这样:
y2 <- rbinom(N, 1, logit(cbind(1, x) %*% beta))
glmFit2 <- glm(y2 ~ x, family = binomial(logit),
control = glm.control(maxit = 100))
table(cut(fitted(glmFit2), seq(0, 1, by = 0.1)))
# (0,0.1] (0.1,0.2] (0.2,0.3] (0.3,0.4] (0.4,0.5] (0.5,0.6] (0.6,0.7]
# 21 30 19 15 6 4 4
# (0.7,0.8] (0.8,0.9] (0.9,1]
# 1 0 0
也就是不会直接切开0,1
不过这个只是警告,告知user说
你的资料可能有问题,才会这样直接切开
(通常是output(response)跟input(covariates)高度相关)
Note: 要增加iteration是因为 default maxit = 25,会导致不收敛
--
R资料整理套件系列文:
magrittr #1LhSWhpH (R_Language) https://goo.gl/72l1m9
data.table #1LhW7Tvj (R_Language) https://goo.gl/PZa6Ue
dplyr(上.下) #1LhpJCfB,#1Lhw8b-s (R_Language) https://goo.gl/I5xX9b
tidyr #1Liqls1R (R_Language) https://goo.gl/i7yzAz
pipeR #1NXESRm5 (R_Language) https://goo.gl/zRUISx
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 36.233.49.208
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/R_Language/M.1486914338.A.015.html
1F:→ clansoda: 所以是probability 仅有0 1两值才会出现这个warning事吧 02/13 00:08
fitted probability出现0 1才会有warning
※ 编辑: celestialgod (36.233.49.208), 02/13/2017 00:12:30
2F:→ clansoda: 就我的理解就是在regression的时候 fit的值都大於正负二 02/13 10:34
3F:→ clansoda: 才会在sigmoid後 所有的值都趋近於1或0对吗 02/13 10:35
4F:→ markbaseball: 那该如何解决完美切割的问题呢? 02/13 19:10
5F:推 maoc: 第一个例子会造成理论上的MLE是无穷大,所以程式跑出来的答 02/14 00:34
6F:→ maoc: 案并不收歛,做出来的模型并不可用,warning 就在提醒这件 02/14 00:34
7F:→ maoc: 事的发生。 02/14 00:34
8F:→ celestialgod: 感谢楼上指正,小弟没有指出要点 02/14 02:31