简体   繁体   English

通过迭代重新加权最小二乘回归获得beta的MLE

[英]Obtain the MLE of betas through iterative re-weighted least squares regression

I have the following data set: 我有以下数据集:

y <- c(5,8,6,2,3,1,2,4,5)
x <- c(-1,-1,-1,0,0,0,1,1,1)
d1 <- as.data.frame(cbind(y=y,x=x))

I when I fit a model to this data set with glm() , using a Poisson distribution with a log link: 我使用glm()将模型拟合到此数据集时,使用带日志链接的泊松分布:

model <- glm(y~x, data=d1, family = poisson(link="log"))
summary(model)

I get the following output: 我得到以下输出:

Coefficients:
            Estimate Std. Error z value Pr(>|z|)    
(Intercept)   1.3948     0.1671   8.345   <2e-16 ***
x            -0.3038     0.2250  -1.350    0.177   

I want to write a function for the iterative re-weighted least squares regression that will obtain the same estimates. 我想为迭代的加权最小二乘回归编写一个函数,该函数将获得相同的估计值。 So far I have been able to do this using an identity link, but not a log link, as I do in the glm. 到目前为止,我已经可以使用身份链接来执行此操作,但不能像glm中那样使用日志链接来执行此操作。

X <- cbind(1,x)

#write an interatively reweighted least squares function with log link
glmfunc.log <- function(d,betas,iterations=1)
{
X <- cbind(1,d[,"x"])
z <- as.matrix(betas[1]+betas[2]*d[,"x"]+((d[,"y"]-exp(betas[1]+betas[2]*d[,"x"]))/exp(betas[1]+betas[2]*d[,"x"])))


for(i in 1:iterations) {
W <- diag(exp(betas[1]+betas[2]*d[,"x"]))
betas <- solve(t(X)%*%W%*%X)%*%t(X)%*%W%*%z
}
return(list(betas=betas,Information=t(X)%*%W%*%X))
}

#run the function
model <- glmfunc.log(d=d1,betas=c(1,0),iterations=1000)

Which gives output: 给出输出:

#print betas
model$betas
           [,1]
[1,]  1.5042000
[2,] -0.6851218

Does anyone know where I am going wrong in writing the custom function and how I would correct this to replicate the output from the glm() function 有谁知道我在编写自定义函数时出了什么问题以及如何更正此问题以复制glm()函数的输出

It appears your 'z' needs to be inside of your loop, as your 'betas' get updated each iteration, thus so should your 'z' as it is based on those values. 似乎您的“ z”需要在循环中,因为您的“ beta”在每次迭代中都会更新,因此您的“ z”也应该基于这些值。

The implementation looks right otherwise. 否则,实现看起来正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM