将函数参数传递给mle()以获得对数似然
问题描述:
我使用mle()方法在R中手动估计具有多个预测变量的logit回归。我无法在下面的函数calcLogLikelihood
中传递计算对数似然所需的额外参数。将函数参数传递给mle()以获得对数似然
这是我计算负对数似然的函数。
calcLogLikelihood <- function(betas, x, y) {
# Computes the negative log-likelihood
#
# Args:
# x: a matrix of the predictor variables in the logit model
# y: a vector of the outcome variable (e.g. living in SF, etc)
# betas: a vector of beta coefficients used in the logit model
#
# Return:
# llf: the negative log-likelihood value (to be minimized via MLE)
#
# Error handling:
# Check if any values are null, and whether there are same number of coefficients as there are predictors
if (TRUE %in% is.na(x) || TRUE %in% is.na(y)) {
stop(" There is one or more NA value in x and y!")
}
nbetas <- sapply(betas, length)
if (nbetas-1 != ncol(x)) {
print(c(length(betas)-1, length(x)))
stop(" Categorical vector and coef vector of different lengths!")
}
linsum <- betas$betas[1] + sum(betas$betas[2:nbetas] * x)
p <- CalcInvlogit(linsum)
llf <- -1 * sum(data$indweight * (y * log(p) + (1-y) * log(1-p)))
return(llf)
}
这里是我的X和Y数据矩阵的样子:
> head(x)
agebucket_(0,15] agebucket_(15,30] agebucket_(30,45] agebucket_(45,60] agebucket_(60,75]
1 0 0 1 0 0
2 0 0 1 0 0
3 0 0 1 0 0
4 0 0 1 0 0
5 0 0 1 0 0
6 0 0 0 1 0
> head(y)
[,1]
[1,] 1
[2,] 1
[3,] 0
[4,] 0
[5,] 1
[6,] 0
这里的调用我的函数:
# Read in data
data <- read.csv("data.csv")
# cont.x.vars and dummy.x.vars are arrays of predictor variable column names
x.vars <- c(cont.x.vars, dummy.x.vars)
# Select y column. This is the dependent variable name.
y.var <- "Housing"
# Select beta starting values
betas <- list("betas"=c(100, rep(.1, length(x.vars))))
# Select columns from the original dataframe
x <- data.matrix(data[, x.vars])
y <- data.matrix(data[, y.var])
# Minimize LLF
fit <- mle(calcLogLikelihood, betas, x=x, y=y)
这里是我的错误信息:
Error in is.na(x) : 'x' is missing
这个错误似乎来了,因为我没有正确传递calcLogLikelihood
所需的x和y参数,但我不确定发生了什么问题。我如何解决这个错误?
答
出现此错误是因为stats4 :: mle函数不会将任何使用省略号参数的参数传递给您的似然函数。相反,省略号用于将更多参数传递给optimizer(请参阅?stats4 :: mle)。您必须注意您的似然函数只是要优化的参数的函数。数据,即x和y,不能通过调用传递给mle。
您有两种选择。 1.重新定义你的可能性函数。您可以依赖R的词法范围规则,因为您将数据(x,y)视为*变量(只需从函数定义中除去参数x和y,并在工作区中定义x和y),或者定义闭包明确哪个是更强大的解决方案并解释(例如)here。 2.你也可以使用optim而不是mle,它允许你保留你的可能性的定义,并在后台被mle用作优化器。
看起来像'x.vars'变量可能与'data'对象的列名称不匹配。随意通过发布来证明我错了:'colnames(data)'和'dput(x.vars)' – 2014-11-06 00:28:28