R语言正态似然函数最大化代码中params[!fixed] <- p行含义解析
params[!fixed] <- p的疑问解答 Hey there! Let's break down that line of code and its role in maximizing the normal likelihood function step by step.
1. 先搞懂params[!fixed] <- p到底在做什么
First, let's contextualize where this line lives: it's inside the inner function returned by make.NegLogLik, which is the actual negative log-likelihood function we pass to optimizers like optim or optimize.
Let's unpack each part:
- The
fixedargument in the outermake.NegLogLikfunction lets you specify which parameters (μ and σ, corresponding to positions 1 and 2 in the vector) are fixed to a constant value and which are free to be optimized:- If an element is
FALSE, that parameter is a free variable we want the optimizer to find - If an element is a number (like
2in your second example), that parameter is locked to that value and won't change during optimization
- If an element is
params <- fixedinitializes our full parameter vector with the fixed values you specified; free parameter positions start asFALSEtemporarily!fixedconverts thefixedvector into a logical mask: anyFALSE(free parameter) becomesTRUE, and any numeric value (fixed parameter) becomesFALSE(since non-zero numbers count asTRUEin R, so!2isFALSE)- Finally,
params[!fixed] <- ptakes the candidate parameter valuesppassed in by the optimizer and plugs them into the free parameter positions inparams. Nowparamsis a complete vector with both fixed values and the current candidate values for free parameters, ready for the likelihood calculation.
2. 这行代码在最大化正态似然函数中的核心作用
记住:最小化负对数似然(这是optim这类优化器的默认行为)和最大化对数似然(进而最大化似然函数本身)是完全等价的。这行代码解决了一个关键问题:它让我们不管是优化一个参数、两个参数,甚至固定所有参数,都能复用同一套核心似然计算代码。
结合你的例子具体看:
例子1:同时优化μ和σ
nLL <- make.NegLogLik(normals) optim(c(mu = 0, sigma = 1), nLL)$par
这里fixed = c(FALSE, FALSE),所以!fixed会变成c(TRUE, TRUE)。优化器传入一个2元素的向量p(候选的μ和σ值),params[!fixed] <- p会把这两个值分别填入params的对应位置。函数随后计算该(μ, σ)组合对应的负对数似然,优化器则在二维参数空间中搜索能最小化这个值的参数组合。
例子2:固定σ,只优化μ
nLL <- make.NegLogLik(normals, c(FALSE, 2)) optimize(nLL, c(-1, 3))$minimum
这里fixed = c(FALSE, 2),所以!fixed是c(TRUE, FALSE)。此时优化器只传入单个值p(候选的μ),params[!fixed] <- p会把这个值赋值给params的第一个位置,而第二个位置保持固定的2。因为只需要在一维空间搜索,我们可以用更简单的optimize函数,且核心的似然计算代码完全不需要修改。
简单来说,这行代码就像一个灵活的"适配器":一边对接只关心自由参数的优化器,另一边对接需要完整参数集(固定+自由)的似然计算逻辑。
内容的提问来源于stack exchange,提问作者Shreyas

