我想手工进行泊松回归并定义一个可用于估计任意数量系数的函数。我有两个问题:
首先:我如何得到一个beta矩阵,而不必写每个beta表达。我想以这种方式写lambda lambda = exp(t(x)%*%beta)。我以为我可以做一个for循环并为x a beta中的每一列创建并在矩阵中将它们加起来但我不知道如何编码它。
第二: 由于我不知道怎么写我的贝塔,我试着编写估算6个贝塔的函数。我得到了数据集warpbreaks的结果,但系数与glm不一样,为什么?我也不知道我必须将哪些值粘贴到par,并且如果我不将x和y粘贴到函数中,也不知道为什么optim不起作用。
希望你能帮忙!
daten <- warpbreaks
LogLike <- function(y,x, par) {
beta <- par
# the deterministic part of the model:
lambda <- exp(beta%*%t(x))
# and here comes the negative log-likelihood of the whole dataset, given the
# model:
LL <- -sum(dpois(y, lambda, log = TRUE))
return(LL)
}
PoisMod<-function(formula, data){
# #formula
form <- formula(formula)
#
# # dataFrame
model <- model.frame(formula, data = data)
#
# # Designmatrix
x <- model.matrix(formula,data = data)
#
# # Response Variable
y <- model.response(model)
par <- rep(0,ncol(x))
call <- match.call()
koef <- optim(par=par,fn=LogLike,x=x,y=y)$par
estimation <- return(list("coefficients" = koef,"call"= call))
class(result) <- "PoisMod"
}
print.PoisMod <- function(x, ...) {
# Call
cat("Call:", "\n")
#
print(x$call)
#
cat("\n")
# Coefficients
cat("Coefficents:", "\n")
#
Koef <- (t(x$coefficients))
#
rownames(Koef) <- ""
#
print(round(Koef, 3))
}
答案 0 :(得分:2)
这是一个工作示例,基于您的代码..但没有解释变量的平方:
LogLike <- function(y,x, par) {
beta0 <- par[1]
beta1 <- par[2]
beta2 <- par[3]
beta3 <- par[4]
# the deterministic part of the model:
lambda <- exp(beta0*x[,1] + beta1 * x[,2] +beta2*x[,3]+beta3*x[,4])
# and here comes the negative log-likelihood of the whole dataset, given the
# model:
LL <- -sum(dpois(y, lambda, log = TRUE))
return(LL)
}
PoisMod<-function(formula, data){
# # definiere Regressionsformel
form <- formula(formula)
#
# # dataFrame wird erzeugt
model <- model.frame(formula, data = data)
#
# # Designmatrix erzeugt
x <- model.matrix(formula,data = data)
#
# # Response Variable erzeugt
y <- model.response(model)
par <- c(0,0,0,0)
erg <- list(optim(par=par,fn=LogLike,x=x,y=y)$par)
return(erg)
}
PoisMod(breaks~wool+tension, as.data.frame(daten))
你可以和glm比较:
glm(breaks~wool+tension, family = "poisson", data = as.data.frame(daten))
编辑:任意数量的解释变量
LogLike <- function(y,x, par) {
beta <- par
# the deterministic part of the model:
lambda <- exp(beta%*%t(x))
# and here comes the negative log-likelihood of the whole dataset, given the
# model:
LL <- -sum(dpois(y, lambda, log = TRUE))
return(LL)
}
PoisMod<-function(formula, data){
# # definiere Regressionsformel
form <- formula(formula)
#
# # dataFrame wird erzeugt
model <- model.frame(formula, data = data)
#
# # Designmatrix erzeugt
x <- model.matrix(formula,data = data)
#
# # Response Variable erzeugt
y <- model.response(model)
par <- rep(0,ncol(x))
erg <- list(optim(par=par,fn=LogLike,x=x,y=y)$par)
return(erg)
}
PoisMod(breaks~wool+tension, as.data.frame(daten))
glm(breaks~wool+tension, family = "poisson", data = as.data.frame(daten))