### Multistart for Robust Model Fitting (R) Source: https://context7.com/depmix/depmixs4/llms.txt Shows how to use the `multistart` function in depmixS4 to fit a model with multiple random starting values, helping to avoid local optima and find a better-fitting solution compared to a single fit. It compares the log-likelihood of single and multistart fits. ```R library(depmixS4) data(speed) mod <- depmix( list(rt ~ 1, corr ~ 1), data = speed, transition = ~ Pacc, nstates = 2, family = list(gaussian(), multinomial("identity")), ntimes = c(168, 134, 137) ) set.seed(3) fmod_single <- fit(mod) fmod_multi <- multistart(mod, nstart = 10, initIters = 10) logLik(fmod_single) logLik(fmod_multi) fmod_single fmod_multi fmod_thorough <- multistart(mod, nstart = 50, initIters = 20) ``` -------------------------------- ### Full Control Model Specification with makeDepmix in R Source: https://context7.com/depmix/depmixs4/llms.txt The makeDepmix function allows for detailed control over Hidden Markov Model specification, including custom response distributions and transition models. It is particularly useful for multivariate normal responses or user-defined distributions. This example demonstrates generating bivariate normal data and fitting a model to detect regime changes. ```r library(depmixS4) library(MASS) # for mvrnorm # Generate bivariate normal data with regime switch set.seed(2) m1 <- c(0, 1) sd1 <- matrix(c(1, 0.7, 0.7, 1), 2, 2) m2 <- c(1, 0) sd2 <- matrix(c(2, 0.1, 0.1, 1), 2, 2) y1 <- mvrnorm(50, m1, sd1) y2 <- mvrnorm(50, m2, sd2) y <- rbind(y1, y2) # Specify multivariate normal response models rModels <- list() rModels[[1]] <- list(MVNresponse(y ~ 1)) # State 1 rModels[[2]] <- list(MVNresponse(y ~ 1)) # State 2 # Specify transition models trstart <- c(0.9, 0.1, 0.1, 0.9) transition <- list() transition[[1]] <- transInit(~ 1, nstates = 2, data = data.frame(1), pstart = trstart[1:2]) transition[[2]] <- transInit(~ 1, nstates = 2, data = data.frame(1), pstart = trstart[3:4]) # Specify initial state model instart <- runif(2) inMod <- transInit(~ 1, ns = 2, ps = instart, data = data.frame(1)) # Create full model mod <- makeDepmix( response = rModels, transition = transition, prior = inMod ) # Fit the model fm <- fit(mod, emc = em.control(random = FALSE)) fm # Find the change point plot(as.ts(posterior(fm, type = "smoothing")[, 1]), ylab = "P(State 1)", main = "Detecting regime change in bivariate data") abline(v = 50, col = "red", lty = 2) ``` -------------------------------- ### Constrained Optimization in depmixS4 Model Fitting with R Source: https://context7.com/depmix/depmixs4/llms.txt The `fit` function in depmixS4 supports constrained optimization for model parameters using the Rsolnp package. This includes fixing parameters, setting equality constraints, and defining general linear inequality constraints. The examples demonstrate how to apply these constraints to a fitted model. ```r library(depmixS4) data(speed) # Fit base model mod <- depmix( list(rt ~ 1, corr ~ 1), data = speed, transition = ~ Pacc, nstates = 2, family = list(gaussian(), multinomial("identity")), ntimes = c(168, 134, 137) ) set.seed(3) fmod <- fit(mod) # 1. FIXED PARAMETERS # Fix initial state probabilities to 0 and 1 pars <- getpars(fmod) pars[1] <- 0 pars[2] <- 1 mod_fixed <- setpars(mod, pars) # Specify which parameters are free free <- rep(TRUE, length(pars)) free[1:2] <- FALSE # Fix first two parameters fmod_fixed <- fit(mod_fixed, fixed = !free) # 2. EQUALITY CONSTRAINTS # Constrain transition parameters to be equal across states conpat <- rep(1, length(pars)) # 1 = free conpat[1:2] <- 0 # Fix initial probs # Parameters with same integer (>1) are constrained equal conpat[4] <- conpat[8] <- 2 # Equal intercepts conpat[6] <- conpat[10] <- 3 # Equal slopes fmod_equal <- fit(mod_fixed, equal = conpat) # 3. LINEAR INEQUALITY CONSTRAINTS # Specify constraint matrix: bl <= A*x <= bu conr <- matrix(0, nrow = 2, ncol = npar(mod)) # Constraint 1: par[4] - par[8] = 0 conr[1, 4] <- 1 conr[1, 8] <- -1 # Constraint 2: par[6] - par[10] = 0 conr[2, 6] <- 1 conr[2, 10] <- -1 fmod_linear <- fit(mod_fixed, conrows = conr, fixed = !free) ``` -------------------------------- ### setpars/getpars - Get and Set Model Parameters Source: https://context7.com/depmix/depmixs4/llms.txt Functions to retrieve and modify the parameters of a depmixS4 model object. ```APIDOC ## setpars/getpars - Get and Set Model Parameters The `getpars` and `setpars` functions provide access to model parameters. Useful for parameter initialization, transferring parameters between models, and fixing parameter values. ### Description These functions allow direct manipulation of the parameter vector of a depmixS4 model. `getpars` extracts the current parameter vector, and `setpars` updates the model with a new vector of parameters. This is essential for advanced usage, such as initializing models with specific values or fixing certain parameters during fitting. ### Methods - `getpars(object, ...)` - `setpars(object, pars, ...)` ### Parameters - `object`: A depmixS4 model object. - `pars`: A numeric vector of parameters to set (for `setpars`). ### Request Example ```r library(depmixS4) data(speed) # Fit a model to get initial parameters mod <- depmix( list(rt ~ 1, corr ~ 1), data = speed, nstates = 2, family = list(gaussian(), multinomial("identity")), ntimes = c(168, 134, 137) ) fmod <- fit(mod) # Get the current parameters current_pars <- getpars(fmod) print(current_pars) # Modify some parameters (e.g., increase the mean of state 1) # Assuming the first parameter is the mean of the first response in state 1 new_pars <- current_pars new_pars[1] <- new_pars[1] + 1.0 # Set the modified parameters back to the model mod_updated <- setpars(fmod, new_pars) # Verify that parameters have changed getpars(mod_updated)[1] current_pars[1] ``` ### Response Example (Parameter Vector) ``` # print(current_pars) # [1] -0.1234567 0.9876543 1.2345678 0.8765432 ... (other parameters) # getpars(mod_updated)[1] # [1] -0.1234567 # (Value will be original + 1.0) ``` ``` -------------------------------- ### Specifying Response Distributions with GLMresponse in R Source: https://context7.com/depmix/depmixs4/llms.txt The GLMresponse function is used to define response model objects within depmixS4, supporting various distributions like gaussian, binomial, poisson, gamma, and multinomial via GLM-style formulas. This example shows how to create response models for different families and fit a Poisson HMM. ```r library(depmixS4) data(speed) # Create individual response models # Gaussian response for reaction time resp_gauss <- GLMresponse( formula = rt ~ 1, data = speed, family = gaussian() ) resp_gauss # Multinomial response for accuracy resp_multi <- GLMresponse( formula = corr ~ 1, data = speed, family = multinomial("identity") ) resp_multi # Response with covariates resp_cov <- GLMresponse( formula = rt ~ Pacc, data = speed, family = gaussian() ) # Available families: # gaussian() - Normal/Gaussian distribution # binomial() - Binomial (binary outcomes) # poisson() - Poisson (count data) # Gamma() - Gamma (positive continuous) # multinomial() - Multinomial (categorical) # multinomial("identity") - Multinomial with identity link (faster, no covariates) # Poisson response example data_counts <- data.frame(y = rpois(100, lambda = 3)) resp_pois <- GLMresponse( formula = y ~ 1, data = data_counts, family = poisson() ) # Fit Poisson HMM (change point model) set.seed(3) y1 <- rpois(50, 1) y2 <- rpois(50, 3) ydf <- data.frame(y = c(y1, y2)) mod_pois <- depmix(y ~ 1, nstates = 2, family = poisson(), data = ydf) set.seed(1) fmod_pois <- fit(mod_pois) summary(fmod_pois) ``` -------------------------------- ### Constrained Optimization in fit function Source: https://context7.com/depmix/depmixs4/llms.txt Demonstrates how to use the `fit` function with parameter constraints, including fixed parameters, equality constraints, and general linear inequality constraints using the Rsolnp optimizer. ```APIDOC ## Constrained Optimization ### Description The `fit` function supports various parameter constraints including fixed parameters, equality constraints, and general linear inequality constraints using the Rsolnp optimizer. ### Method Function call (R) ### Endpoint N/A (R function) ### Parameters N/A ### Request Example ```r library(depmixS4) data(speed) # Fit base model mod <- depmix( list(rt ~ 1, corr ~ 1), data = speed, transition = ~ Pacc, nstates = 2, family = list(gaussian(), multinomial("identity")), ntimes = c(168, 134, 137) ) set.seed(3) fmod <- fit(mod) # 1. FIXED PARAMETERS # Fix initial state probabilities to 0 and 1 pars <- getpars(fmod) pars[1] <- 0 pars[2] <- 1 mod_fixed <- setpars(mod, pars) # Specify which parameters are free free <- rep(TRUE, length(pars)) free[1:2] <- FALSE # Fix first two parameters fmod_fixed <- fit(mod_fixed, fixed = !free) # 2. EQUALITY CONSTRAINTS # Constrain transition parameters to be equal across states conpat <- rep(1, length(pars)) # 1 = free conpat[1:2] <- 0 # Fix initial probs # Parameters with same integer (>1) are constrained equal conpat[4] <- conpat[8] <- 2 # Equal intercepts conpat[6] <- conpat[10] <- 3 # Equal slopes fmod_equal <- fit(mod_fixed, equal = conpat) # 3. LINEAR INEQUALITY CONSTRAINTS # Specify constraint matrix: bl <= A*x <= bu conr <- matrix(0, nrow = 2, ncol = npar(mod)) # Constraint 1: par[4] - par[8] = 0 conr[1, 4] <- 1 conr[1, 8] <- -1 # Constraint 2: par[6] - par[10] = 0 conr[2, 6] <- 1 conr[2, 10] <- -1 fmod_linear <- fit(mod_fixed, conrows = conr, fixed = !free) ``` ### Response #### Success Response (200) N/A (R function output) #### Response Example ```r # Output of fitted models (fmod_fixed, fmod_equal, fmod_linear) ``` ``` -------------------------------- ### Fit depmixS4 Model and Extract Parameters (R) Source: https://context7.com/depmix/depmixs4/llms.txt Demonstrates fitting a depmixS4 model to data, extracting all fitted parameters, identifying fixed parameters, and counting total and free parameters. It also shows how to apply fitted parameters to new data. ```R mod <- depmix( list(rt ~ 1, corr ~ 1), data = speed, nstates = 2, family = list(gaussian(), multinomial("identity")), ntimes = c(168, 134, 137) ) set.seed(1) fmod <- fit(mod) pars <- getpars(fmod) print(pars) fixed <- getpars(fmod, which = "fixed") print(fixed) npar(fmod) freepars(fmod) new_data <- data.frame( rt = c(6.4, 5.5, 5.3), corr = c(1, 0, 1) ) mod_new <- depmix( list(rt ~ 1, corr ~ 1), data = new_data, nstates = 2, family = list(gaussian(), multinomial("identity")) ) mod_new <- setpars(mod_new, getpars(fmod)) posterior(mod_new, type = "global") ``` -------------------------------- ### Likelihood Ratio Test for Nested Models (R) Source: https://context7.com/depmix/depmixs4/llms.txt Illustrates how to perform a likelihood ratio test using `llratio` to compare two nested depmixS4 models. It shows fitting an unconstrained and a constrained model, then testing if the constraints significantly worsen model fit. Also includes BIC for non-nested model comparison. ```R library(depmixS4) data(speed) mod1 <- depmix( list(rt ~ 1, corr ~ 1), data = speed, transition = ~ Pacc, nstates = 2, family = list(gaussian(), multinomial("identity")), ntimes = c(168, 134, 137) ) set.seed(3) fmod1 <- fit(mod1) pars <- getpars(fmod1) pars[1] <- 0 pars[2] <- 1 mod2 <- setpars(mod1, pars) free <- rep(TRUE, length(pars)) free[1:2] <- FALSE fmod2 <- fit(mod2, fixed = !free) llratio(fmod1, fmod2) mod_3state <- depmix( list(rt ~ 1, corr ~ 1), data = speed, nstates = 3, family = list(gaussian(), multinomial("identity")), ntimes = c(168, 134, 137) ) set.seed(1) fmod_3state <- fit(mod_3state) BIC(fmod1) BIC(fmod_3state) ``` -------------------------------- ### Control EM Algorithm Parameters (R) Source: https://context7.com/depmix/depmixs4/llms.txt Demonstrates how to customize the Expectation-Maximization (EM) algorithm's behavior in depmixS4 using `em.control`. This includes setting maximum iterations, convergence tolerance, likelihood change criteria, and specifying 'soft' or 'hard' classification. ```R library(depmixS4) data(speed) mod <- depmix( list(rt ~ 1, corr ~ 1), data = speed, nstates = 2, family = list(gaussian(), multinomial("identity")), ntimes = c(168, 134, 137) ) set.seed(1) fmod_default <- fit(mod) set.seed(1) fmod_custom <- fit(mod, emcontrol = em.control( maxit = 1000, tol = 1e-10, crit = "relative", random.start = TRUE, classification = "soft" )) set.seed(1) fmod_hard <- fit(mod, emcontrol = em.control( classification = "hard" )) logLik(fmod_custom) logLik(fmod_hard) set.seed(5) fmod_hard2 <- fit(mod, emcontrol = em.control(classification = "hard")) logLik(fmod_hard2) ``` -------------------------------- ### Fit HMM and Decode States Source: https://context7.com/depmix/depmixs4/llms.txt Demonstrates how to define and fit a 2-state Hidden Markov Model using depmixS4 and perform various types of state decoding including Viterbi, local, smoothing, and filtering. ```R library(depmixS4) data(speed) mod <- depmix(list(rt ~ 1, corr ~ 1), data = speed, nstates = 2, family = list(gaussian(), multinomial("identity")), ntimes = c(168, 134, 137)) set.seed(1) fmod <- fit(mod) pst_global <- posterior(fmod, type = "global") pst_smooth <- posterior(fmod, type = "smoothing") plot(ts(pst_smooth[, 1], start = c(1, 1)), ylab = "P(State 1)", main = "Posterior state probability over time") ``` -------------------------------- ### forwardbackward - Compute Forward-Backward Variables Source: https://context7.com/depmix/depmixs4/llms.txt Computes the forward and backward variables, smoothed state and transition probabilities, and log-likelihood for a depmixS4 model. ```APIDOC ## forwardbackward - Compute Forward-Backward Variables The `forwardbackward` function computes the forward and backward variables used in the EM algorithm, along with smoothed state and transition probabilities. Useful for accessing intermediate HMM computations. ### Description This function calculates the alpha (forward) and beta (backward) variables, which are fundamental for computing smoothed state probabilities and the model's log-likelihood. It provides detailed intermediate results of the HMM's EM algorithm. ### Method `forwardbackward(object, ...)` ### Parameters - `object`: A fitted depmixS4 model object. ### Request Example ```r library(depmixS4) data(speed) # Specify model mod <- depmix( list(rt ~ 1, corr ~ 1), data = speed, transition = ~ Pacc, # Example transition covariate nstates = 2, family = list(gaussian(), multinomial("identity")), ntimes = c(168, 134, 137) ) # Compute forward-backward variables fb <- forwardbackward(mod) # Available outputs: names(fb) # Log likelihood (computed as -sum(log(scale factors))) fb$logLike # Verify log likelihood computation all.equal(-sum(log(fb$sca)), fb$logLike) # Alpha: forward variables P(Y_1,...,Y_t, S_t=i) dim(fb$alpha) # [observations x states] # Beta: backward variables P(Y_{t+1},...,Y_T | S_t=i) dim(fb$beta) # Gamma: smoothed state probabilities P(S_t=i | Y_1,...,Y_T) dim(fb$gamma) head(fb$gamma) # Xi: smoothed transition probabilities # P(S_t=i, S_{t+1}=j | Y_1,...,Y_T) dim(fb$xi) # [observations x states x states] ``` ### Response Example (Output Structure) ``` # names(fb) # [1] "alpha" "beta" "gamma" "xi" "sca" "logLike" # fb$logLike # [1] -1742.126 # dim(fb$gamma) # [1] 441 2 # dim(fb$xi) # [1] 441 2 2 ``` ``` -------------------------------- ### makeDepmix - Full Control Model Specification Source: https://context7.com/depmix/depmixs4/llms.txt Provides full control over model specification, allowing custom response distributions and manually specified transition models. Essential for multivariate normal responses or user-defined distributions. ```APIDOC ## makeDepmix - Full Control Model Specification ### Description The `makeDepmix` function provides full control over model specification, allowing custom response distributions and manually specified transition models. Essential for multivariate normal responses or user-defined distributions. ### Method Function call (R) ### Endpoint N/A (R function) ### Parameters N/A ### Request Example ```r library(depmixS4) library(MASS) # for mvrnorm # Generate bivariate normal data with regime switch set.seed(2) m1 <- c(0, 1) sd1 <- matrix(c(1, 0.7, 0.7, 1), 2, 2) m2 <- c(1, 0) sd2 <- matrix(c(2, 0.1, 0.1, 1), 2, 2) y1 <- mvrnorm(50, m1, sd1) y2 <- mvrnorm(50, m2, sd2) y <- rbind(y1, y2) # Specify multivariate normal response models rModels <- list() rModels[[1]] <- list(MVNresponse(y ~ 1)) # State 1 rModels[[2]] <- list(MVNresponse(y ~ 1)) # State 2 # Specify transition models trstart <- c(0.9, 0.1, 0.1, 0.9) transition <- list() transition[[1]] <- transInit(~ 1, nstates = 2, data = data.frame(1), pstart = trstart[1:2]) transition[[2]] <- transInit(~ 1, nstates = 2, data = data.frame(1), pstart = trstart[3:4]) # Specify initial state model instart <- runif(2) inMod <- transInit(~ 1, ns = 2, ps = instart, data = data.frame(1)) # Create full model mod <- makeDepmix( response = rModels, transition = transition, prior = inMod ) # Fit the model fm <- fit(mod, emc = em.control(random = FALSE)) fm # Find the change point plot(as.ts(posterior(fm, type = "smoothing")[, 1]), ylab = "P(State 1)", main = "Detecting regime change in bivariate data") abline(v = 50, col = "red", lty = 2) ``` ### Response #### Success Response (200) N/A (R function output) #### Response Example ```r # Output of fm (fitted model object) ``` ``` -------------------------------- ### Posterior Decoding and State Probabilities Source: https://context7.com/depmix/depmixs4/llms.txt This section covers how to obtain different types of posterior state probabilities after fitting a depmixS4 model, including global, local, smoothing, and filtering probabilities, as well as Viterbi decoding. ```APIDOC ## Posterior Decoding and State Probabilities This section covers how to obtain different types of posterior state probabilities after fitting a depmixS4 model, including global, local, smoothing, and filtering probabilities, as well as Viterbi decoding. ### Description After fitting a Hidden Markov Model (HMM) using `depmixS4`, various functions can be used to decode the most likely state sequence or estimate state probabilities at different time points. ### Functions - `posterior(object, type, ...)`: Computes various posterior probabilities based on the fitted model. - `viterbi(object, ...)`: Computes the most likely state sequence using the Viterbi algorithm. ### Posterior Types - `"global"`: Most likely state sequence (Viterbi algorithm). - `"local"`: Most likely state at each time point. - `"smoothing"`: Smoothed probabilities P(S_t | Y_1, ..., Y_T). - `"filtering"`: Filtering probabilities P(S_t | Y_1, ..., Y_t). - `"viterbi"`: Full Viterbi output with delta probabilities. ### Request Example (Fitting and Decoding) ```r library(depmixS4) data(speed) # Fit a 2-state model mod <- depmix( list(rt ~ 1, corr ~ 1), data = speed, nstates = 2, family = list(gaussian(), multinomial("identity")), ntimes = c(168, 134, 137) ) set.seed(1) fmod <- fit(mod) # Global decoding: most likely state sequence (Viterbi algorithm) pst_global <- posterior(fmod, type = "global") head(pst_global) # Local decoding: most likely state at each time point pst_local <- posterior(fmod, type = "local") # Smoothing probabilities: P(S_t | Y_1, ..., Y_T) pst_smooth <- posterior(fmod, type = "smoothing") head(pst_smooth) # Filtering probabilities: P(S_t | Y_1, ..., Y_t) pst_filt <- posterior(fmod, type = "filtering") # Full Viterbi output with delta probabilities pst_viterbi <- posterior(fmod, type = "viterbi") head(pst_viterbi) # Plot posterior probability of being in state 1 plot(ts(pst_smooth[, 1], start = c(1, 1)), ylab = "P(State 1)", main = "Posterior state probability over time") ``` ### Response Example (Viterbi Output) ``` # For posterior(fmod, type = "viterbi") # state S1 S2 # 1 2 0.0001234 0.9998766 # 2 2 0.0002345 0.9997655 # ... ``` ``` -------------------------------- ### Simulate Data from HMM Source: https://context7.com/depmix/depmixs4/llms.txt Generates synthetic data and state sequences from a specified HMM, which is useful for model validation and power analysis. ```R library(depmixS4) mod <- depmix(y ~ 1, data = data.frame(y = rnorm(1000)), nstates = 2, respstart = c(0, 1, 2, 1), trstart = c(0.9, 0.1, 0.1, 0.9), instart = c(0.5, 0.5), ntimes = 1000) sim_mod <- simulate(mod, nsim = 1, seed = 123) sim_data <- sim_mod@response[[1]][[1]]@y sim_states <- sim_mod@states ``` -------------------------------- ### Fit a Model using the EM Algorithm Source: https://context7.com/depmix/depmixs4/llms.txt Optimizes parameters for a specified model using the EM algorithm. It allows for control over convergence criteria and random restarts. ```R library(depmixS4) data(speed) mod <- depmix(list(rt ~ 1, corr ~ 1), data = speed, nstates = 2, family = list(gaussian(), multinomial("identity")), ntimes = c(168, 134, 137)) set.seed(1) fmod <- fit(mod) summary(fmod) fmod2 <- fit(mod, emcontrol = em.control(maxit = 1000, tol = 1e-10, random.start = TRUE)) ``` -------------------------------- ### Specify a Hidden Markov Model with depmix Source: https://context7.com/depmix/depmixs4/llms.txt Creates a hidden Markov model specification using a GLM-style formula interface. It supports multiple response distributions and covariates on transition probabilities. ```R library(depmixS4) data(speed) mod <- depmix( response = list(rt ~ 1, corr ~ 1), data = speed, nstates = 2, family = list(gaussian(), multinomial("identity")), transition = ~ Pacc, ntimes = c(168, 134, 137) ) mod ``` -------------------------------- ### Decode State Sequence with Viterbi Source: https://context7.com/depmix/depmixs4/llms.txt Applies the Viterbi algorithm to find the most likely state sequence (MAP) for a fitted HMM and extracts the normalized delta probabilities. ```R vit <- viterbi(fmod) states <- vit$state delta_probs <- vit[, -1] plot(states, type = "l", ylab = "State", main = "Viterbi decoded state sequence") ``` -------------------------------- ### simulate - Generate Data from a Model Source: https://context7.com/depmix/depmixs4/llms.txt Generates random data and state sequences from a specified or fitted depmixS4 model. ```APIDOC ## simulate - Generate Data from a Model The `simulate` function generates random data from specified or fitted depmix/mix models. Useful for model checking, power analysis, and understanding model behavior. ### Description This function allows you to simulate data from an HMM, either from a model specification with initial parameters or from a fully fitted model. This is crucial for tasks like model validation, assessing the sensitivity of results to parameter choices, and power calculations. ### Method `simulate(object, nsim = 1, seed = NULL, ...)` ### Parameters - `object`: A depmixS4 model object (either specified with initial parameters or fitted). - `nsim`: The number of datasets to simulate. - `seed`: An optional random seed for reproducibility. ### Request Example ```r library(depmixS4) # Create a model specification with known parameters respstart <- c(0, 1, 2, 1) # Response parameters: state 1 mean=0, sd=1; state 2 mean=2, sd=1 trstart <- c(0.9, 0.1, 0.1, 0.9) # Transition probs: high self-transition # Create empty data frame (needed for model structure) df <- data.frame(y = rnorm(1000)) # Specify model structure and initial parameters mod <- depmix( y ~ 1, data = df, nstates = 2, respstart = respstart, trstart = trstart, instart = c(0.5, 0.5), # Initial state probabilities ntimes = 1000 ) # Simulate data from the model sim_mod <- simulate(mod, nsim = 1, seed = 123) # Access simulated data sim_data <- sim_mod@response[[1]][[1]]@y head(sim_data) # Access simulated state sequence sim_states <- sim_mod@states head(sim_states) # Plot simulated data colored by state plot(sim_data, col = sim_states, pch = 19, cex = 0.5, main = "Simulated data from 2-state HMM", ylab = "Observation") legend("topright", legend = c("State 1", "State 2"), col = 1:2, pch = 19) ``` ### Response Example (Simulated Data) ``` # head(sim_data) # [1] 0.1234 -0.5678 0.8901 1.9876 2.1234 1.8765 # head(sim_states) # [1] 1 1 1 2 2 2 ``` ``` -------------------------------- ### Perform Likelihood Ratio Test for Nested Models Source: https://context7.com/depmix/depmixs4/llms.txt The llratio function compares two nested models to determine if the more complex model provides a significantly better fit. It requires two fitted model objects as input and returns the likelihood ratio statistic and associated p-value. ```R llratio(fmod, fmod_fixed) llratio(fmod_fixed, fmod_equal) ``` -------------------------------- ### Compute Forward-Backward Variables Source: https://context7.com/depmix/depmixs4/llms.txt Computes the forward and backward variables for an HMM, which are essential for the EM algorithm and calculating smoothed state/transition probabilities. ```R library(depmixS4) data(speed) mod <- depmix(list(rt ~ 1, corr ~ 1), data = speed, transition = ~ Pacc, nstates = 2, family = list(gaussian(), multinomial("identity")), ntimes = c(168, 134, 137)) fb <- forwardbackward(mod) print(fb$logLike) # Access alpha, beta, gamma, and xi matrices dim(fb$alpha) dim(fb$gamma) ``` -------------------------------- ### GLMresponse - Specify Response Distributions Source: https://context7.com/depmix/depmixs4/llms.txt Creates response model objects using GLM-style formula and family specifications. Supports gaussian, binomial, poisson, gamma, and multinomial distributions. ```APIDOC ## GLMresponse - Specify Response Distributions ### Description The `GLMresponse` function creates response model objects using GLM-style formula and family specifications. Supports gaussian, binomial, poisson, gamma, and multinomial distributions. ### Method Function call (R) ### Endpoint N/A (R function) ### Parameters N/A ### Request Example ```r library(depmixS4) data(speed) # Create individual response models # Gaussian response for reaction time resp_gauss <- GLMresponse( formula = rt ~ 1, data = speed, family = gaussian() ) resp_gauss # Multinomial response for accuracy resp_multi <- GLMresponse( formula = corr ~ 1, data = speed, family = multinomial("identity") ) resp_multi # Response with covariates resp_cov <- GLMresponse( formula = rt ~ Pacc, data = speed, family = gaussian() ) # Available families: # gaussian() - Normal/Gaussian distribution # binomial() - Binomial (binary outcomes) # poisson() - Poisson (count data) # Gamma() - Gamma (positive continuous) # multinomial() - Multinomial (categorical) # multinomial("identity") - Multinomial with identity link (faster, no covariates) # Poisson response example data_counts <- data.frame(y = rpois(100, lambda = 3)) resp_pois <- GLMresponse( formula = y ~ 1, data = data_counts, family = poisson() ) # Fit Poisson HMM (change point model) set.seed(3) y1 <- rpois(50, 1) y2 <- rpois(50, 3) ydf <- data.frame(y = c(y1, y2)) mod_pois <- depmix(y ~ 1, nstates = 2, family = poisson(), data = ydf) set.seed(1) fmod_pois <- fit(mod_pois) summary(fmod_pois) ``` ### Response #### Success Response (200) N/A (R function output) #### Response Example ```r # Output of GLMresponse object or summary of fitted model ``` ``` -------------------------------- ### viterbi - Decode Most Likely State Sequence Source: https://context7.com/depmix/depmixs4/llms.txt Applies the Viterbi algorithm to compute the maximum a posteriori (MAP) state sequence from a fitted depmixS4 model. ```APIDOC ## viterbi - Decode Most Likely State Sequence The `viterbi` function applies the Viterbi algorithm to compute the maximum a posteriori (MAP) state sequence. Returns both the decoded states and normalized delta probabilities. ### Description This function efficiently finds the single most likely sequence of hidden states that generated the observed data, given a fitted Hidden Markov Model. It's a core function for interpreting the hidden states over time. ### Method `viterbi(object, ...)` ### Parameters - `object`: A fitted depmixS4 model object. ### Request Example ```r library(depmixS4) data(speed) # Fit a 2-state model mod <- depmix( list(rt ~ 1, corr ~ 1), data = speed, nstates = 2, family = list(gaussian(), multinomial("identity")), ntimes = c(168, 134, 137) ) set.seed(1) fmod <- fit(mod) # Get Viterbi decoded state sequence vit <- viterbi(fmod) head(vit) # Column 1: MAP state at each time point states <- vit$state # Columns 2+: normalized delta probabilities delta_probs <- vit[, -1] # Count state occurrences table(states) # Plot state sequence plot(states, type = "l", ylab = "State", main = "Viterbi decoded state sequence") # The result is stored in fitted model's posterior slot identical(viterbi(fmod), fmod@posterior) ``` ### Response Example (Viterbi Output) ``` # head(vit) # state S1 S2 # 1 2 0.00012340 0.9998766 # 2 2 0.00023450 0.9997655 # 3 2 0.00045670 0.9995433 # ... # table(states) # states # 1 2 # 189 250 ``` ``` -------------------------------- ### Specify and Fit a Latent Class Mixture Model Source: https://context7.com/depmix/depmixs4/llms.txt Uses the mix function to create latent class models for cross-sectional data. This is a special case of HMMs where observations are independent. ```R library(depmixS4) data(balance) mod <- mix( response = list(d1 ~ 1, d2 ~ 1, d3 ~ 1, d4 ~ 1), data = balance, nstates = 2, family = list(multinomial("identity"), multinomial("identity"), multinomial("identity"), multinomial("identity")) ) set.seed(1) fmod <- fit(mod) summary(fmod) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.