优化通用产品

时间:2018-03-01 04:28:19

标签: r

所以我写了这个可爱的功能来概括MLE问题解决MLE问题。

# Π f(x | θs) for x ∈ xs
# 
# Useful for things like multiplying iid likelihoods/pdfs
# 
# fn - the PDF/likelihood/whatever function
# xs - known values
# thetas - the space to explore
`Πf(x|θs)` = function(fn, xs, thetas) {
  # Matrix with columns as fn(x, θ) for each x in xs
  xs_given_θs = sapply(xs, function(x) fn(x, thetas))
  # Take sum of each row to find joint function
  apply(xs_given_θs, 1, prod)
}

理论上,我期待能够做这样的事情:

require(purrr)
likelihood = partial(`Πf(x|θs)`,
  fn = function(k, θ) θ^k * exp(-θ) / factorial(k),
  xs = c(1, 2, 3, 4, 5)
)

# This above is a partial application of arguments.
#
# likelihood(thetas) will now compute the likelihood for thetas
# given the above xs and supplied function.

optimize(likelihood, c(0, 10), maximum = T)

但是在apply步骤中的优化例程期间会出现这种情况:

 Error in apply(sapply(xs, function(x) fn(x, thetas)), 1, prod) : 
  dim(X) must have a positive length 

有人可以解释导致失败的优化例程正在做什么,以及我如何重写Πf(x|θs)以防止这种情况发生?

请注意,即使我正在处理对数似然性,也会出现同样的问题:

# Σ loglikelihood(x | θs) for x ∈ xs
# 
# Useful for things like summing iid log likelihoods/pdfs
# 
# fn - the log(PDF/likelihood/whatever) function
# xs - known values
# thetas - the space to explore
`Σloglik(x|θs)` = function(fn, xs, thetas) {
  # Matrix with columns as fn(x, θ) for each x in xs
  xs_given_θs = sapply(xs, function(x) fn(x, thetas))
  # Take product of each row to find joint function
  apply(xs_given_θs, 1, sum)
}

0 个答案:

没有答案