View source: R/forward_algorithms.R
| forward | R Documentation |
Calculates the log-likelihood of a sequence of observations under a homogeneous hidden Markov model using the forward algorithm.
forward(
delta,
Gamma,
allprobs,
trackID = NULL,
ad = NULL,
report = TRUE,
logspace = FALSE
)
delta |
initial or stationary distribution of length N, or matrix of dimension c(k,N) for k independent tracks, if |
Gamma |
transition probability matrix of dimension c(N,N), or array of k transition probability matrices of dimension c(N,N,k), if |
allprobs |
matrix of state-dependent probabilities/ density values of dimension c(n, N) |
trackID |
optional vector of length n containing IDs If provided, the total log-likelihood will be the sum of each track's likelihood contribution.
In this case, |
ad |
optional logical, indicating whether automatic differentiation with |
report |
logical, indicating whether Caution: When there are multiple tracks, for compatibility with downstream functions like |
logspace |
logical, indicating whether the probabilities/ densities in the |
log-likelihood for given data and parameters
Other forward algorithms:
forward_g(),
forward_hsmm(),
forward_ihsmm(),
forward_p(),
forward_phsmm()
## negative log likelihood function
nll = function(par, step) {
# parameter transformations for unconstrained optimisation
Gamma = tpm(par[1:2]) # multinomial logit link
delta = stationary(Gamma) # stationary HMM
mu = exp(par[3:4])
sigma = exp(par[5:6])
# calculate all state-dependent probabilities
allprobs = matrix(1, length(step), 2)
ind = which(!is.na(step))
for(j in 1:2) allprobs[ind,j] = dgamma2(step[ind], mu[j], sigma[j])
# simple forward algorithm to calculate log-likelihood
-forward(delta, Gamma, allprobs)
}
## fitting an HMM to the trex data
par = c(-2,-2, # initial tpm params (logit-scale)
log(c(0.3, 2.5)), # initial means for step length (log-transformed)
log(c(0.2, 1.5))) # initial sds for step length (log-transformed)
mod = nlm(nll, par, step = trex$step[1:1000])
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.