簡體   English   中英

將函數參數傳遞給mle()以獲取對數似然

[英]Passing function parameters to mle() for log likelihood

我正在使用mle()方法在R中手動估計具有多個預測變量的logit回歸。 我無法在下面的函數calcLogLikelihood中傳遞計算對數似然性所需的其他參數。

這是我計算負對數似然的函數。

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沒有使用省略似然函數的省略號參數傳遞任何參數。 相反,省略號用於將更多參數傳遞給optim(參見?stats4 :: mle)。 您必須注意您的似然函數只是要優化的參數的函數。 數據,即x和y,不能在調用mle時傳遞。

你有兩個選擇。 1.重新定義你的可能性函數。 您可以依賴R的詞法范圍規則,因為您將數據(x,y)視為自由變量(只需從函數定義中刪除參數x和y並在工作空間中定義x和y),或者定義閉包明確地,這是一個更強大的解決方案,並在這里解釋(例如)。 2.你也可以使用optim而不是mle,它允許你保持你的可能性定義,並被mle用作后台的優化器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM