import numpy
J = 10
K = 3
nests = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3]Discrete Choice Modeling, Part III: Mixed Models
More modeling technique chapters are available on my website.
Probabilistic utility models that incorporate sophisticated couplings – while also admitting clean, analytic results – are few and far between. We explored many of the exceptional models in Part II. Often, a more productive route to constructing discrete choice models with more elaborate substitution patterns is to modify an existing discrete choice model.
In this chapter, we’ll explore a general technique for building sophisticated discrete choice models out of simpler base models, with a particular emphasis on efficient practical implementation. At the end, we’ll review a demonstrative application.
1 Mixed Discrete Choice Models
Consider a parameterized base utility model, p( u_{n1}, \ldots, u_{nJ} \mid \phi ). Given a mixture kernel p( \phi \mid \psi ), we can derive a new utility model as a continuous mixture, p( u_{n1}, \ldots, u_{nJ} \mid \psi ) = \int \mathrm{d} \phi \, p( \phi \mid \psi ) \, p( u_{n1}, \ldots, u_{nJ} \mid \phi). I will refer to \psi as the global parameter and \phi as an auxiliary parameter.
If the base utility model and mixture kernel are sufficiently well-behaved, then we can exchange the mixture integral with other integrals and derivatives. This allow us to, for example, define new discrete choice models by directly mixing the joint cumulative distribution function, \begin{align*} \Pi( u_{n1}, \ldots, u_{nJ} \mid \psi ) &= \left[ \prod_{j = 1}^{J} \int_{-\infty}^{ u_{nj} } \mathrm{d} u'_{nj} \, \right] \, p( u'_{n1}, \ldots, u'_{nJ} \mid \psi ) \\ &= \left[ \prod_{j = 1}^{J} \int_{-\infty}^{ u_{nj} } \mathrm{d} u'_{nj} \, \right] \, \int \mathrm{d} \phi \, p( \phi \mid \psi ) \, p( u'_{n1}, \ldots, u'_{nJ} \mid \phi) \\ &= \int \mathrm{d} \phi \, p( \phi \mid \psi ) \, \left[ \prod_{j = 1}^{J} \int_{-\infty}^{ u_{nj} } \mathrm{d} u_{nj'} \, \right] \, p( u'_{n1}, \ldots, u'_{nJ} \mid \phi) \\ &= \int \mathrm{d} \phi \, p( \phi \mid \psi ) \, \Pi( u'_{n1}, \ldots, u'_{nJ} \mid \phi ). \end{align*}
Each mixture kernel p( \phi \mid \psi ) defines a new mixed utility model, or equivalently a new mixed cumulative distribution function. In turn, the mixed utility model defines new choice probabilities that will, in general, exhibit different substitution patterns than those derived from the base utility model. Engineering mixture kernels that result in specific substitution patterns, however, is by no means trivial.
2 Mixed Choice Probabilities
Because choice probabilities are defined through a sequence of derivatives and integrals of the joint cumulative distribution function, deriving choice probabilities is much easier when we can freely exchanging these operations with the mixture integral. In practice, we are almost always working with base utility models and mixture kernels that are sufficiently well-behaved to allow this, and I will assume as much moving forwards.
In this case, we can write not only \Pi( u_{n1}, \ldots, u_{nJ} \mid \psi ) = \int \mathrm{d} \phi \, p( \phi \mid \psi ) \, \Pi( u_{n1}, \ldots, u_{nJ} \mid \phi ) but also \frac{ \partial \Pi }{ \partial x_{j} } ( u_{n1}, \ldots, u_{nJ} \mid \psi) = \int \mathrm{d} \phi \, p( \phi \mid \psi ) \, \frac{ \partial \Pi }{ \partial x_{j} } ( u_{n1}, \ldots, u_{nJ} \mid \phi ). This then allows us to write the new choice probabilities as continuous mixtures of the base choice probabilities, \begin{align*} q_{nj} ( \psi ) &= \pi( \mathsf{u}_{nj} ) \\ &= \int_{-\infty}^{+\infty} \mathrm{d} u \, \frac{ \partial \Pi }{ \partial x_{j} } ( u, \ldots, u \mid \psi ) \\ &= \int_{-\infty}^{+\infty} \mathrm{d} u \, \int \mathrm{d} \phi \, p( \phi \mid \psi ) \, \frac{ \partial \Pi }{ \partial x_{j} } ( u, \ldots, u \mid \phi ) \\ &= \int \mathrm{d} \phi \, p( \phi \mid \psi ) \, \int_{-\infty}^{+\infty} \mathrm{d} u \, \frac{ \partial \Pi }{ \partial x_{j} } ( u, \ldots, u \mid \phi ) \\ &= \int \mathrm{d} \phi \, p( \phi \mid \psi ) \, q_{nj} ( \phi ). \end{align*} To avoid any confusion, I will refer to the q_{nj} ( \psi ) as mixed choice probabilities and the q_{nj} ( \phi ) as base choice probabilities.
For example, given an initial independent Gumbel model with the base choice probabilities, q_{nj} ( \mu_{n1}, \ldots, \mu_{nJ}, \sigma_{n} ) = \frac{ e^{ \frac{ \mu_{nj} }{ \sigma_{n} } } }{ \sum_{j' = 1}^{J} e^{ \frac{ \mu_{nj'} }{ \sigma_{n} } } }, we can define a new discrete choice model with the mixed choice probabilities \begin{align*} q_{nj} ( \psi ) &= \int \mathrm{d} \mu_{n1} \ldots \mathrm{d} \mu_{nJ} \, p( \mu_{n1}, \ldots, \mu_{nJ} \mid \psi ) \, q_{nj} ( \mu_{n1}, \ldots, \mu_{nJ}, \sigma_{n} ) \\ &= \int \mathrm{d} \mu_{n1} \ldots \mathrm{d} \mu_{nJ} \, p( \mu_{n1}, \ldots, \mu_{nJ} \mid \psi ) \, \frac{ e^{ \frac{ \mu_{nj} }{ \sigma_{n} } } }{ \sum_{j' = 1}^{J} e^{ \frac{ \mu_{nj'} }{ \sigma_{n} } } }. \end{align*}
That said, we can also define mixed models with respect to any of the parameters. For instance, the mixture kernel could integrate over the agent scales \sigma_{n}, the scaled baseline utilities \nu_{nj} = \mu_{nj} / \sigma_{n}, the relative baseline utilities \delta_{nj} = \mu_{nj} - \mu_{nj'}, and so on.
3 Mixed Substitution Patterns
One of the main benefits of mixing a base discrete choice model is that the procedure tends to obstruct simpler substitution patterns exhibited by that model. In this section, we’ll investigate how the substitution patterns of the independent Gumbel model are mechanically obstructed by the introduction of a continuous mixture.
Mixing the baseline utilities in the independent Gumbel model results in the mixed choice probabilities q_{nj} = \int \mathrm{d} \mu_{n1} \ldots \mathrm{d} \mu_{nJ} \, p( \mu_{n1}, \ldots, \mu_{nJ} \mid \psi ) \, e^{ \frac{ \mu_{nj} }{ \sigma_{n} } } \left[ \sum_{j' = 1}^{J} e^{ \frac{ \mu_{nj'} }{ \sigma_{n} } } \right]^{-1}. While mathematically straightforward, this in a bit ungainly in terms of notation. To allow for more compact equations, let’s introduce the notation \boldsymbol{\mu}_{n} = ( \mu_{n1}, \ldots, \mu_{nJ} ) and \mathrm{d} \boldsymbol{\mu}_{n} = \mathrm{d} \mu_{n1} \ldots \mathrm{d} \mu_{nJ} so that we can instead write q_{nj} = \int \mathrm{d} \boldsymbol{\mu}_{n} \, p( \boldsymbol{\mu}_{n} \mid \psi ) \, e^{ \frac{ \mu_{nj} }{ \sigma_{n} } } \left[ \sum_{j' = 1}^{J} e^{ \frac{ \mu_{nj'} }{ \sigma_{n} } } \right]^{-1}.
3.1 Ratios of Choice Probabilities
Let’s first consider the substitution patterns quantified by ratios of choice probabilities. Because the ratio of integrals is not equal to the integral the ratio, continuous mixtures obstruct cancellations in these ratios.
The independent Gumbel model, for instance, exhibits independence from irrelevant alternatives because every ratio of choice probabilities is independent of the other alternatives, \frac{ q_{nj_{1}} }{ q_{nj_{2}} } = \frac{ e^{ \frac{ \mu_{nj_{1}} }{ \sigma_{n} } } }{ e^{ \frac{ \mu_{nj_{2}} }{ \sigma_{n} } } } = \exp \left( \frac{ \mu_{nj_{1}} - \mu_{nj_{2}} }{ \sigma_{n} } \right). When we mix the baseline utilities, however, the ratios of choice probabilities become \frac{ q_{nj_{1}} }{ q_{nj_{2}} } = \frac{ \int \mathrm{d} \boldsymbol{\mu}_{n} \, p( \boldsymbol{\mu}_{n} \mid \psi ) \, e^{ \frac{ \mu_{nj_{1}} }{ \sigma_{n} } } \left[ \sum_{j' = 1}^{J} e^{ \frac{ \mu_{nj'} }{ \sigma_{n} } } \right]^{-1} }{ \int \boldsymbol{\mu}_{n} \, p( \boldsymbol{\mu}_{n} \mid \psi ) \, e^{ \frac{ \mu_{nj_{2}} }{ \sigma_{n} } } \left[ \sum_{j' = 1}^{J} e^{ \frac{ \mu_{nj'} }{ \sigma_{n} } } \right]^{-1} }.
The common denominators, \left[ \sum_{j' = 1}^{J} e^{ \frac{ \mu_{nj'} }{ \sigma_{n} } } \right]^{-1}, no longer cancel because they cannot be factored out of the integrals, \begin{align*} \int \mathrm{d} \boldsymbol{\mu}_{n} \, & p( \boldsymbol{\mu}_{n} \mid \psi ) \, e^{ \frac{ \mu_{nj_{1}} }{ \sigma_{n} } } \left[ \sum_{j' = 1}^{J} e^{ \frac{ \mu_{nj'} }{ \sigma_{n} } } \right]^{-1} \\ &\ne \left[ \sum_{j' = 1}^{J} e^{ \frac{ \mu_{nj'} }{ \sigma_{n} } } \right]^{-1} \int \mathrm{d} \boldsymbol{\mu}_{n} \, p( \boldsymbol{\mu}_{n} \mid \psi ) \, e^{ \frac{ \mu_{nj_{1}} }{ \sigma_{n} } }. \end{align*}
Specifically, the ratio of mixed choice probabilities is not equal to the mixed ratio of independent Gumbel choice probabilities, \frac{ q_{nj_{1}} }{ q_{nj_{2}} } \ne \int \boldsymbol{\mu}_{n} \, p(\boldsymbol{\mu}_{n} \mid \psi ) \, \frac{ e^{ \frac{ \mu_{nj_{1}} }{ \sigma_{n} } } }{ e^{ \frac{ \mu_{nj_{2}} }{ \sigma_{n} } } }.
3.2 Elasticities
A similar obstruction arises when computing elasticities.
Assuming all of the niceties needed to freely exchange integrals and derivatives, the sensitivities of a mixed discrete choice model can be written as \frac{ \partial q_{nj} }{ \partial z } ( \psi ) = \int \mathrm{d} \phi \, p( \phi \mid \psi ) \, \frac{ \partial q_{nj} }{ \partial z } ( \phi ). The corresponding elasticities then become \begin{align*} \frac{ z }{ q_{nj}( \psi ) } \frac{ \partial q_{nj} }{ \partial z } ( \psi ) &= \frac{ z }{ q_{nj}( \psi ) } \int \mathrm{d} \phi \, p( \phi \mid \psi ) \, \frac{ \partial q_{nj} }{ \partial z } ( \phi ) \\ &= z \int \mathrm{d} \phi \, p( \phi \mid \psi ) \, \frac{ z }{ q_{nj}( \psi ) } \frac{ \partial q_{nj} }{ \partial z } ( \phi ) \\ &= z \, \frac{ \int \mathrm{d} \phi \, p( \phi \mid \psi ) \, \frac{ \partial q_{nj} }{ \partial z } ( \phi ) }{ q_{nj}( \psi ) } \\ &= z \, \frac{ \int \mathrm{d} \phi \, p( \phi \mid \psi ) \, \frac{ \partial q_{nj} }{ \partial z } ( \phi ) }{ \int \mathrm{d} \phi \, p( \phi \mid \psi ) \, q_{nj}(\phi) }. \end{align*}
In the second equation, the mixed choice probability q_{nj}( \psi ) does not cancel with the base choice probability q_{nj}( \phi ). The last equation is written entirely in terms of base choice probabilities, but the terms in the numerator and denominator are blocked from canceling with each other because they cannot be factored outside of the integrals.
These obstructions can be a bit easier to understand in an explicit example. Consider an independent Gumbel model where we have \begin{align*} \frac{ \partial q_{nj} }{ \partial z } ( \boldsymbol{\mu}_{n} ) &= - \frac{ q_{nj} ( \boldsymbol{\mu}_{n} ) }{ \sigma_{n} } \sum_{j' = 1}^{J} q_{nj'} ( \boldsymbol{\mu}_{n} ) \frac{ \partial \mu_{nj'} }{ \partial z }. \end{align*} The choice probability q_{nj} ( \boldsymbol{\mu}_{n} ) cancels when evaluating the corresponding elasticity, \frac{ z }{ q_{nj}( \boldsymbol{\mu}_{n} ) } \frac{ \partial q_{nj} }{ \partial z } ( \boldsymbol{\mu}_{n} ) = -\frac{1}{\sigma_{n}} \, \sum_{j' = 1}^{J} q_{nj'} ( \boldsymbol{\mu}_{n} ) \frac{ \partial \mu_{nj'} }{ \partial z }. Because of this cancellation, the elasticities are the same for all alternatives j.
If we mix the baseline utilities, however, then the elasticities become \begin{align*} \frac{ z }{ q_{nj}( \psi ) } &\frac{ \partial q_{nj} }{ \partial z } ( \psi ) \\ &= \frac{ z }{ q_{nj}( \psi ) } \int \mathrm{d} \boldsymbol{\mu}_{n} \, p( \boldsymbol{\mu}_{n} \mid \psi ) \, \frac{ \partial q_{nj} }{ \partial z } ( \boldsymbol{\mu}_{n} ) \\ &= -\frac{z}{\sigma_{n}} \, \int \mathrm{d} \boldsymbol{\mu}_{n} \, p( \boldsymbol{\mu}_{n} \mid \psi ) \, \left[ \frac{ q_{nj} ( \boldsymbol{\mu}_{n} ) }{ q_{nj}( \psi ) } \right] \sum_{j' = 1}^{J} q_{nj'} ( \boldsymbol{\mu}_{n} ) \frac{ \partial \mu_{nj'} }{ \partial z }. \end{align*}
The ratio of a base choice probability to the corresponding mixed choice probability, \frac{ q_{nj} ( \boldsymbol{\mu}_{n} ) }{ q_{nj}( \psi ) } \ne 1, will, in general, vary across alternatives. Consequently, the sensitivities will no longer be homogeneous, and independence from irrelevant alternatives will be violated.
4 The Multivariate Normal Baseline Mixing Kernel
Continuous mixture modeling is a very general technique. One particular family of continuous mixture models, however, dominates applications of mixed discrete choice modeling in practice.
4.1 General Construction
This ubiquitous approach starts with a base independent Gumbel model and then mixes the baseline utilities with a multivariate normal kernel, p ( \boldsymbol{\mu}_{n} \mid \boldsymbol{\kappa}_{n}, \boldsymbol{\Sigma} ) = \text{multinormal} ( \boldsymbol{\mu}_{n} \mid \boldsymbol{\kappa}_{n}, \boldsymbol{\Sigma} ). In this chapter I will refer to the resulting family of discrete choice models as multivariate normal mixed baseline discrete choice models, although this is not standard terminology. A more common description that one might encounter in the economics and marketing literature is the normal error component logit-mixture model.
The components of \boldsymbol{\kappa}_{n} define a sort of baseline, baseline utility for each alternative. In practice, they’re usually interpreted in the same way as the baseline utilities in the base independent Gumbel model: the larger \kappa_{nj_{1}} is relative to \kappa_{nj_{2}}, the more agent n prefers alternative j_{1} to alternative j_{2} in a fixed choice subset.
Unfortunately, many discussions of mixed discrete choice modeling take these similarities a bit too far and treat probabilistic utilities, u_{nj}, baseline utilities, \mu_{nj}, and baseline-baseline utilities, \kappa_{nj}, as equivalent objects. Many go as far to use the same variables to denote all three, leaving it up to the reader to distinguish when each quantity is being considered. To avoid any ambiguity, I will be diligent in using different notation for each distinct object.
What really defines the substitution patterns of this mixed discrete choice model is the structure of the covariance matrix \boldsymbol{\Sigma}. The larger \Sigma_{j_{1} j_{2}} is, the better substitutes the j_{1}th and j_{2}th alternatives will be for each other.
To facilitate a wide range of covariance structures, including even singular structures, we can write the covariance as \boldsymbol{\Sigma} = \boldsymbol{Z} \cdot \boldsymbol{\Gamma} \cdot \boldsymbol{Z}^{T}. Here \boldsymbol{\Gamma} is any positive-definite, symmetric (L \times L)-matrix and \boldsymbol{Z} is any rectangular (J \times L)-matrix.
If L < J then \boldsymbol{\Sigma} will not be positive-definite, but the mixed discrete choice model will still be well-defined. To avoid having to deal with any singular behavior in \boldsymbol{\Sigma} when implementing these models, we can always model latent deviations, p ( \boldsymbol{\theta}_{n} \mid \boldsymbol{\Gamma} ) = \text{multinormal} ( \boldsymbol{\theta}_{n} \mid \boldsymbol{0}, \boldsymbol{\Gamma} ), that are then pushed forward through a deterministic linear transformation, \boldsymbol{\mu}_{n} = \boldsymbol{\kappa}_{n} + \boldsymbol{Z} \cdot \boldsymbol{\theta}_{n}, to give the multivariate normal mixing kernel, p ( \boldsymbol{\mu}_{n} \mid \boldsymbol{\kappa}_{n}, \boldsymbol{Z}, \boldsymbol{\Gamma} ) = \text{multinormal} ( \boldsymbol{\mu}_{n} \mid \boldsymbol{\kappa}_{n}, \boldsymbol{Z} \cdot \boldsymbol{\Gamma} \cdot \boldsymbol{Z}^{T} ).
One nice benefit of this particular implementation is that it clarifies how \boldsymbol{Z} mediates the coupling between each alternative. The larger Z_{j_{1}l} and Z_{j_{2}l} are, the more \theta_{nl} contributes to both \mu_{nj_{1}} and \mu_{nj_{2}}, coupling the behavior of the two baseline utilities together. If there is only one l for with both Z_{j_{1}l} and Z_{j_{2}l} are non-zero, then \mu_{nj_{1}} and \mu_{nj_{2}} will be exactly coupled to each other in the mixed model. At the same time, if there is no l for which Z_{j_{1}l} and Z_{j_{2}l} are both non-zero, then \mu_{nj_{1}} and \mu_{nj_{2}} will be independent of each other in the mixed model.
This model can also be implemented with non-centered deviations \boldsymbol{\eta}_{n}, p ( \boldsymbol{\eta}_{n} ) = \text{multinormal} ( \boldsymbol{\eta}_{n} \mid \boldsymbol{0}, \boldsymbol{I} ) with \boldsymbol{\mu}_{n} = \boldsymbol{\kappa}_{n} + \boldsymbol{Z} \cdot \boldsymbol{L}_{\boldsymbol{\Gamma}} \cdot \boldsymbol{\eta}_{n}. Here, \boldsymbol{L} is the Choleksy decomposition of \boldsymbol{\Gamma}, \boldsymbol{L}_{\boldsymbol{\Gamma}} \cdot \boldsymbol{L}_{\boldsymbol{\Gamma}}^{T} = \boldsymbol{\Gamma}.
I will refer to the implementation of this mixed model with \boldsymbol{\theta}_{n} as a centered parameterization and the implementation with \boldsymbol{\eta}_{n} as a non-centered parameterization. In general, the deviations for each agent can be implemented differently from each other. This flexibility is very useful when trying to optimize the performance of these models in practice, as we’ll see in Section 8.4.
4.2 Special Cases
Many common discrete choice models are defined by a multivariate normal mixed baseline model with specific choices for the structure of \boldsymbol{Z} and \boldsymbol{\Gamma}. Even more discrete choice models can be well-approximated by an appropriate mixed independent Gumbel model (McFadden and Train 2000). In this section, I’ll discuss a few of these models; for a much more extensive presentation see Walker, Ben-Akiva, and Bolduc (2007) and the references therein.
For example, the heteroskedastic logit model is defined by taking L = J, \boldsymbol{Z} to be the J-dimensional identify matrix, and \boldsymbol{\Gamma} to be a diagonal matrix quantifying variances for each alternative. This model simply introduces independent variation into each baseline utility, complicating the resulting substitution patterns.
The analytic factor model is given by fixing L < J but allowing \boldsymbol{Z} to be an otherwise arbitrary matrix and \boldsymbol{\Gamma} to be an arbitrary positive-definite, symmetric matrix. This lack of restrictions makes the analytic factor model extremely flexible. That flexibility, however, is quite difficult to constrain with observed data, manifesting in frustrating inferential degeneracies.
The mixed multivariate normal mixed baseline model cannot exactly reproduce the behavior of the nested Gumbel model, but it can approximate it well. To do so, we take L = K and then fix the elements of the coupling matrix to be Z_{jk} = \left\{ \begin{array}{ll} 1, & j \in B_{k} \\ 0, & j \notin B_{k} \end{array} \right. . Because each alternative falls into one, and only one, nest, each row of \boldsymbol{Z} contains only a single non-zero value.
Finally, we restrict \boldsymbol{\Gamma} to a diagonal matrix with K non-zero elements \Gamma_{kk} = \gamma_{k}^{2}. As \gamma_{k} increases, the alternatives in the kth nest become better substitutes for each other relative to the alternatives in other nests. Qualitatively, each \gamma_{k} behaves similarly to 1 - \lambda_{k} in the nested Gumbel model, with smaller values corresponding to weaker couplings within the kth nest and larger values corresponding to larger couplings.
Generalizing this model to approximate the generalized nested Gumbel model is straightforward: allowing each row of \boldsymbol{Z} to be a (K - 1)-simplex allows the jth alternative to have partial membership in an arbitrary number of nests.
5 Relative Implementations of Multivariate Normal Mixed Baseline Models
Although mixed discrete choice models exhibit substitution patterns that are distinct from those of their base models, they often exhibit the similar redundancies as their base models. In particular, all discrete choice models derived by mixing the baseline utilities in an independent Gumbel model inherit the translation and scale redundancies of that base model. Fortunately, we can eliminate these redundancies using techniques to those we discussed in Part I, Section 3.2.
5.1 Deriving The Relative Baseline Utility Model
To account for the translation redundancy in a mixed independent Gumbel model, we need to transform the baseline utilities to relative baseline utilities, \delta_{nj} = \mu_{nj} - \mu_{nj'}. When working with a mixed model, however, this transformation is no longer deterministic but rather probabilistic. In particular, we have to push forward the initial probabilistic model for the baseline utilities, p ( \boldsymbol{\mu}_{n} \mid \boldsymbol{\kappa}_{n}, \boldsymbol{Z}, \boldsymbol{\Gamma} ), into a probabilistic model for the relative baseline utilities, p ( \boldsymbol{\delta}_{n} \mid \boldsymbol{\kappa}_{n}, \boldsymbol{Z}, \boldsymbol{\Gamma} ).
The implementation of this probabilistic operation is a bit more straightforward if we use linear algebra for the anchoring transformation. Collecting the baseline utilities \mu_{nj} into the vector \boldsymbol{\mu}_{n} and the relative baseline utilities \delta_{nj} into the vector \boldsymbol{\delta}_{n} allows us to anchor the j'th baseline utility to zero with the linear transformation \boldsymbol{\delta}_{n} = \mathbf{A} \cdot \boldsymbol{\mu}_{n}. The elements of \boldsymbol{A} are given by A_{ i i' } = \delta_{ i i' } - \delta_{ i' j'}, where \delta_{ij} denotes the Kronecker delta function, \delta_{ij} = \left\{ \begin{array}{ll} 0, & i \ne j \\ 1, & i = j \end{array} \right. Mechanically, \boldsymbol{A} is formed by taking the J \times J identify matrix and then subtracting one from all of the elements in the j'th column.
Under this transformation, the multivariate normal model for the baseline utilities, p ( \boldsymbol{\mu}_{n} \mid \boldsymbol{\kappa}_{n}, \boldsymbol{Z}, \boldsymbol{\Gamma} ) = \text{multinormal} ( \boldsymbol{\mu}_{n} \mid \boldsymbol{\kappa}_{n}, \boldsymbol{Z} \cdot \boldsymbol{\Gamma} \cdot \boldsymbol{Z}^{T} ), conveniently pushes forward to another multivariate normal model for the relative baseline utilities, p ( \boldsymbol{\delta}_{n} \mid \boldsymbol{\kappa}_{n}, \boldsymbol{Z}, \boldsymbol{\Gamma} ) = \text{multinormal} ( \boldsymbol{\nu}_{n} \mid \boldsymbol{\chi}_{n}, \boldsymbol{\Omega} ). The transformed location vector is given by \boldsymbol{\chi}_{n} = \boldsymbol{A} \cdot \boldsymbol{\kappa}_{n}, while the transformed covariance matrix is given by \begin{align*} \boldsymbol{\Omega} &= \boldsymbol{A} \cdot \boldsymbol{Z} \cdot \boldsymbol{\Gamma} \cdot \boldsymbol{Z}^{T} \cdot \boldsymbol{A}^{T} \\ &= (\boldsymbol{A} \cdot \boldsymbol{Z}) \cdot \boldsymbol{\Gamma} \cdot (\boldsymbol{A} \cdot \boldsymbol{Z} )^{T}. \end{align*}
We can avoid any singular behavior in \boldsymbol{\Sigma} = \boldsymbol{Z} \cdot \boldsymbol{\Gamma} \cdot \boldsymbol{Z}^{T} by deriving relative baseline utilities from centered deviations, \boldsymbol{\delta}_{n} = \boldsymbol{A} \cdot \boldsymbol{\kappa}_{n} + (\boldsymbol{A} \cdot \boldsymbol{Z}) \cdot \boldsymbol{\theta}_{n} with p ( \boldsymbol{\theta}_{n} \mid \boldsymbol{\Gamma} ) = \text{multinormal} ( \boldsymbol{\theta}_{n} \mid \boldsymbol{0}, \boldsymbol{\Gamma} ).
The corresponding non-centered implementation is given by \boldsymbol{\delta}_{n} = \boldsymbol{A} \cdot \boldsymbol{\kappa}_{n} + \boldsymbol{A} \cdot \boldsymbol{Z} \cdot \boldsymbol{L} \cdot \boldsymbol{\eta}_{n}. with p ( \boldsymbol{\eta}_{n} ) = \text{multinormal} ( \boldsymbol{\eta}_{n} \mid \boldsymbol{0}, \boldsymbol{I} ). and \boldsymbol{L} \cdot \boldsymbol{L}^{T} = \boldsymbol{\Gamma}.
5.2 Eliminating Redundancies In The Relative Baseline Utilities
At this point, we have to reconcile the anchoring with the covariance structure of the baseline utilities. Specifically, if the transformed covariance matrix, \boldsymbol{\Omega} = (\boldsymbol{A} \cdot \boldsymbol{Z}) \cdot \boldsymbol{\Gamma} \cdot (\boldsymbol{A} \cdot \boldsymbol{Z} )^{T}, is singular, then some of the elements of \boldsymbol{\nu}_{n} will be redundant.
Conveniently, we can analytically quantify this singularity using the rank of the combined transformation matrix \boldsymbol{W} = \boldsymbol{A} \cdot \boldsymbol{Z}. If \boldsymbol{W} is rank-deficient, R < L \ne J, then many different configurations of \theta_{n}, or \eta_{n} in the non-centered implementation, will yield exactly the same configuration of the relative baseline utilities \boldsymbol{\nu}_{n}. No amount of data will ever be able to distinguish between these equivalent possibilities.
Fortunately, we can use the same linear algebra tools both to identify when \boldsymbol{W} is singular and to rectify the corresponding redundancies. The systematic procedure starts with the combined transformation matrix \boldsymbol{W} = \boldsymbol{A} \cdot \boldsymbol{Z}, and then performs a singular value decomposition (Trefethen and Bau 1997), \boldsymbol{W} = \boldsymbol{U} \cdot \boldsymbol{S} \cdot \boldsymbol{V}^{T}. In theory, we could also use a rank-revealing QR decomposition here. Because QR decomposition implementations are not always clear about whether or not they are rank-revealing, the singular value decomposition tends to be safer.
The singular value decomposition isolates the singular behavior of \boldsymbol{W} into the central matrix \boldsymbol{S}. If the rank of \boldsymbol{W} is less than L, then all of the elements of \boldsymbol{S} will be zero except for the diagonals in the upper-left R \times R block, \boldsymbol{S} = \begin{pmatrix} \overbrace{\boldsymbol{S}_{11}}^{ R \times R } & \overbrace{\boldsymbol{0} }^{ R \times (L - R) } \\ \underbrace{\boldsymbol{0} }_{ (J - R) \times R } & \underbrace{\boldsymbol{0} }_{ (J - R) \times (L - R) }. \end{pmatrix}
At this point, we decompose the \boldsymbol{U} and \boldsymbol{V} matrices to match the block structure of \boldsymbol{S}, \begin{align*} \boldsymbol{U} &= \begin{pmatrix} \overbrace{\boldsymbol{U}_{11} }^{ R \times R } & \overbrace{\boldsymbol{U}_{12} }^{ R \times (J - R) } \\ \underbrace{\boldsymbol{U}_{21} }_{ (J - R) \times R } & \underbrace{\boldsymbol{U}_{22} }_{ (J - R) \times (J - R) } \end{pmatrix} \\ \boldsymbol{V} &= \begin{pmatrix} \overbrace{\boldsymbol{V}_{11} }^{ R \times R } & \overbrace{\boldsymbol{V}_{12} }^{ R \times (L - R) } \\ \underbrace{\boldsymbol{V}_{21} }_{ (L - R) \times R } & \underbrace{\boldsymbol{V}_{22} }_{ (L - R) \times (L - R) } \end{pmatrix} \end{align*}
This allows us to reduce \boldsymbol{W} to only it’s non-singular behavior, \begin{align*} \boldsymbol{W} &= \boldsymbol{U} \cdot \boldsymbol{S} \cdot \boldsymbol{V}^{T} \\ &= \begin{pmatrix} \boldsymbol{U}_{11} & \boldsymbol{U}_{12} \\ \boldsymbol{U}_{21} & \boldsymbol{U}_{22} \end{pmatrix} \cdot \begin{pmatrix} \boldsymbol{S}_{11} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0} \end{pmatrix} \cdot \begin{pmatrix} \boldsymbol{V}_{11}^{T} & \boldsymbol{V}_{21}^{T} \\ \boldsymbol{V}_{12}^{T} & \boldsymbol{V}_{22}^{T} \end{pmatrix} \\ &= \begin{pmatrix} \boldsymbol{U}_{11} & \boldsymbol{U}_{12} \\ \boldsymbol{U}_{21} & \boldsymbol{U}_{22} \end{pmatrix} \cdot \begin{pmatrix} \boldsymbol{S}_{11} \cdot \boldsymbol{V}_{11}^{T} & \boldsymbol{S}_{11} \cdot \boldsymbol{V}_{21}^{T} \\ \boldsymbol{0} & \boldsymbol{0} \end{pmatrix} \\ &= \begin{pmatrix} \boldsymbol{U}_{11} \\ \boldsymbol{U}_{21} \end{pmatrix} \cdot \begin{pmatrix} \boldsymbol{S}_{11} \cdot \boldsymbol{V}_{11}^{T} & \boldsymbol{S}_{11} \cdot \boldsymbol{V}_{21}^{T} \\ \end{pmatrix} \\ &= \boldsymbol{B} \cdot \boldsymbol{C}, \end{align*} where \boldsymbol{B} = \underbrace{ \begin{pmatrix} \boldsymbol{U}_{11} \\ \boldsymbol{U}_{21} \end{pmatrix} }_{J \times R} and \boldsymbol{C} = \underbrace{ \begin{pmatrix} \boldsymbol{S}_{11} \cdot \boldsymbol{V}_{11}^{T} & \boldsymbol{S}_{11} \cdot \boldsymbol{V}_{21}^{T} \\ \end{pmatrix} }_{ R \times L }.
Finally, we can completely isolate the non-singular covariations of the relative baseline utilities into the covariance matrix \boldsymbol{\Xi} = \underbrace{ \boldsymbol{C} \cdot \boldsymbol{\Gamma} \cdot \boldsymbol{C}^{T} }_{ R \times R }. By construction, \boldsymbol{\Xi} will always be non-singular.
The centered implementation of this non-redundant relative baseline utilities model is given by \boldsymbol{\delta}_{n} = \boldsymbol{A} \cdot \boldsymbol{\kappa}_{n} + \boldsymbol{B} \cdot \boldsymbol{\zeta}_{n}, where p ( \boldsymbol{\zeta}_{n} ) = \text{multinormal} ( \boldsymbol{\zeta}_{n} \mid \boldsymbol{0}, \boldsymbol{\Xi} ). Note the vector \boldsymbol{\zeta}_{n} consists of not L elements, but rather only R < L elements.
At the same time, we also have a corresponding non-centered implementation, \boldsymbol{\delta}_{n} = \boldsymbol{A} \cdot \boldsymbol{\kappa}_{n} + \boldsymbol{B} \cdot \boldsymbol{L}_{\boldsymbol{\Xi}} \cdot \boldsymbol{\xi}_{n}. where p ( \boldsymbol{\xi}_{n} ) = \text{multinormal} ( \boldsymbol{\xi}_{n} \mid \boldsymbol{0}, \boldsymbol{I} ). and \boldsymbol{L}_{\boldsymbol{\Xi}} \cdot \boldsymbol{L}_{\boldsymbol{\Xi}}^{T} = \boldsymbol{\Xi} = \boldsymbol{C} \cdot \boldsymbol{\Gamma} \cdot \boldsymbol{C}^{T}. Once again, the vector \boldsymbol{\xi}_{n} consists of only R < L elements.
5.3 Eliminating Redundancies In The Mixture Kernel
Even after we eliminate the redundancies in the relative baseline utilities, these mixed discrete choice models can still exhibit redundancies in the location and covariance parameters of the mixture kernel.
For example, the J components of the original baseline-baseline utilities \boldsymbol{\kappa} are no longer distinguishable once we move to relative baseline utilities. Fortunately, we can immediately avoid this redundancy by directly modeling the J - 1 components of relative baseline-baseline utilities, \boldsymbol{\chi} = \boldsymbol{A} \cdot \boldsymbol{\kappa}, instead of the J components of \boldsymbol{\kappa}.
The potential redundancies in the covariance matrix configurations are a bit more subtle. By construction, the initial covariance matrix \boldsymbol{\Gamma} contains up to L (L + 1) / 2 individual elements, each of which could be modeled with a separate parameter. In some implementations, however, we might constrain the structure of \boldsymbol{\Gamma}, for example by fixing the off-diagonal elements to zero to leave only L free parameters. In general, let’s say that we’re modeling \boldsymbol{\Gamma} with H \le \frac{ L \, (L + 1) }{ 2 } total degrees of freedom.
On the other hand, the non-singular covariance matrix \boldsymbol{\Xi} = \boldsymbol{C} \cdot \boldsymbol{\Gamma} \cdot \boldsymbol{C}^{T}, which can be fully constrained by observed data, contains only R (R + 1) / 2 individual elements.
If we ever have H > \frac{ R \, (R + 1) }{ 2 }, then we will not able to able to distinguish all H of the parameters comprising \boldsymbol{\Gamma}. The only way to avoid this redundancy is to reduce the parameterization of \boldsymbol{\Gamma} to a set of R (R + 1) / 2 parameters that completely determine \boldsymbol{\Xi}. Typically, this is best done by hand to ensure that the reduced parameterization is as interpretable as possible.
5.4 Cleaning Up
One limitation of this systematic procedure is that the resulting \boldsymbol{B} and \boldsymbol{C} matrices are not always the most interpretable objects. Often, it can be useful to massage these matrices into more interpretable forms with the introduction of some auxiliary matrices.
Consider two R \times R matrices \boldsymbol{M}_{1} and \boldsymbol{M}_{2} that are inverses of each other, \mathbf{M}_{1} \cdot \mathbf{M}_{2} = \mathbf{M}_{2}^{T} \cdot \mathbf{M}_{1}^{T} = \mathbf{I}. Inserting the identify matrix into the relative covariance matrix, \begin{align*} \boldsymbol{\Omega} &= \boldsymbol{B} \cdot \left( \boldsymbol{C} \cdot \boldsymbol{\Gamma} \cdot \boldsymbol{C}^{T} \right) \cdot \boldsymbol{B}^{T} \\ &= \boldsymbol{B} \cdot \mathbf{I} \cdot \left( \boldsymbol{C} \cdot \boldsymbol{\Gamma} \cdot \boldsymbol{C}^{T} \right) \cdot \mathbf{I} \cdot \boldsymbol{B}^{T} \end{align*} allows us to insert these matrices, \begin{align*} \boldsymbol{\Omega} &= \boldsymbol{B} \cdot \mathbf{I} \cdot \left( \boldsymbol{C} \cdot \boldsymbol{\Gamma} \cdot \boldsymbol{C}^{T} \right) \cdot \mathbf{I} \cdot \boldsymbol{B}^{T} \\ &= \boldsymbol{B} \cdot \left( \mathbf{M}_{1} \cdot \mathbf{M}_{2} \right) \cdot \left( \boldsymbol{C} \cdot \boldsymbol{\Gamma} \cdot \boldsymbol{C}^{T} \right) \cdot \left( \mathbf{M}_{2}^{T} \cdot \mathbf{M}_{1}^{T} \right) \cdot \boldsymbol{B}^{T} \\ &= \left( \boldsymbol{B} \cdot \mathbf{M}_{1} \right) \left( \mathbf{M}_{2} \cdot \boldsymbol{C} \right) \cdot \boldsymbol{\Gamma} \cdot \left( \boldsymbol{C}^{T} \cdot \mathbf{M}^{T}_{2} \right) \cdot \left( \mathbf{M}_{1}^{T} \cdot \boldsymbol{B}^{T} \right) \\ &= \left( \boldsymbol{B} \cdot \mathbf{M}_{1} \right) \left( \mathbf{M}_{2} \cdot \boldsymbol{C} \right) \cdot \boldsymbol{\Gamma} \cdot \left( \boldsymbol{M}_{2} \cdot \mathbf{C} \right)^{T} \cdot \left( \boldsymbol{B} \cdot \mathbf{M}_{1} \right)^{T}. \end{align*}
We are then free to engineer \boldsymbol{M}_{1} and \boldsymbol{M}_{2} so that \boldsymbol{B} \cdot \mathbf{M}_{1} and \mathbf{M}_{2} \cdot \boldsymbol{C} take on more interpretable forms.
To be clear, this step is entirely optional. Moreover, finding useful \boldsymbol{M}_{1} and \boldsymbol{M}_{2} is much more of an art than any systematic process. That said, this procedure can be extremely convenient when trying to compare different multivariate normal mixed baseline models.
In particular, this kind of manipulation is often helpful for reconciling the structure of equivalent discrete choice models written in different forms. For example, if we know what values \boldsymbol{B} \cdot \mathbf{M}_{1} has to take for two models to agree, then we can solve for \mathbf{M}_{1} and then \mathbf{M}_{2} = \mathbf{M}_{1}^{-1}.
5.5 Demonstration
To demonstrate the robust implementation of multivariate normal mixed baseline discrete choice models, let’s consider a mixed independent Gumbel model that approximates the nested Gumbel model.
We start with the nesting configuration that we used for the exercises in Part II.
Next, we construct a matrix that encodes this nesting structure. Multiplying this matrix by the deviation vector will add the deviation associated with each nest to the baseline utilities of the alternatives in those nests.
Z = numpy.zeros([J, K])
for k in range(K):
Z[[ j for j in range(J) if nests[j] == k + 1 ],k] = 1
Zarray([[1., 0., 0.],
[1., 0., 0.],
[1., 0., 0.],
[0., 1., 0.],
[0., 1., 0.],
[0., 1., 0.],
[0., 1., 0.],
[0., 0., 1.],
[0., 0., 1.],
[0., 0., 1.]])
At this point, we construct a matrix encoding the anchoring transformation that maps baseline utilities to relative baseline utilities.
anchor = 10A = numpy.identity(J)
A[:,anchor - 1] -= numpy.ones([J])
Aarray([[ 1., 0., 0., 0., 0., 0., 0., 0., 0., -1.],
[ 0., 1., 0., 0., 0., 0., 0., 0., 0., -1.],
[ 0., 0., 1., 0., 0., 0., 0., 0., 0., -1.],
[ 0., 0., 0., 1., 0., 0., 0., 0., 0., -1.],
[ 0., 0., 0., 0., 1., 0., 0., 0., 0., -1.],
[ 0., 0., 0., 0., 0., 1., 0., 0., 0., -1.],
[ 0., 0., 0., 0., 0., 0., 1., 0., 0., -1.],
[ 0., 0., 0., 0., 0., 0., 0., 1., 0., -1.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 1., -1.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
To eliminate the redundancies inherent to this model, we first combine A and Z into a single transformation.
W = numpy.matmul(A, Z)We then isolate the non-singular part of this combined transformation by applying a singular value decomposition.
U, S, Vt = numpy.linalg.svd(W)The non-zero diagonal elements of \mathbf{S} immediately indicate that the rank of \mathbf{W} is not L = K = 3 but rather only 2.
print(f'Singular Values: {S}')Singular Values: [3.25661654e+00 1.84240298e+00 6.69005615e-17]
R = sum(S > 1e-15)
print(f'Rank: {R}')Rank: 2
Finally, we construct the \mathbf{B} and \mathbf{C} matrices by reducing the components of the singular value decomposition.
B = U[:,0:R]
numpy.round(B, 3)array([[-0.347, -0.461],
[-0.347, -0.461],
[-0.347, -0.461],
[-0.4 , 0.301],
[-0.4 , 0.301],
[-0.4 , 0.301],
[-0.4 , 0.301],
[ 0. , 0. ],
[ 0. , 0. ],
[ 0. , 0. ]])
C = numpy.concatenate((numpy.matmul(numpy.diag(S[0:R]),
Vt[0:R, 0:R]),
numpy.matmul(numpy.diag(S[0:R]),
Vt[0:R, R:K])),
axis=1)
numpy.round(C, 3)array([[-1.041, -1.598, 2.639],
[-1.384, 1.202, 0.182]])
As expected, the product \mathbf{B} \cdot \mathbf{C} recovers \mathbf{W} without having to deal with any singular behavior.
numpy.round(numpy.matmul(B, C) - W, 3)array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., -0., 0.],
[ 0., -0., 0.],
[ 0., -0., 0.],
[ 0., -0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
The only downside to this procedure is that \mathbf{B} and \mathbf{C} are not the most interpretable objects. To clean them up a bit, let’s introduce the matrices \mathbf{M}_{1} and \mathbf{M}_{2}.
M1 = numpy.array([[-1.041141, -1.384206],
[-1.598343, 1.202206]])
M2 = numpy.array([[-0.3470470, -0.3995857],
[-0.4614019, 0.3005516]])As required, these matrices are inverses of each other.
numpy.round(numpy.matmul(M1, M2))array([[ 1., -0.],
[ 0., 1.]])
Consequently, we can use \mathbf{B} \cdot \mathbf{M}_{1} instead of \mathbf{B} and \mathbf{M}_{2} \cdot \mathbf{C} instead of \mathbf{C} when constructing the relative baseline utilities.
numpy.round(numpy.matmul(B, M1))array([[ 1., -0.],
[ 1., -0.],
[ 1., -0.],
[-0., 1.],
[-0., 1.],
[-0., 1.],
[-0., 1.],
[ 0., 0.],
[ 0., 0.],
[ 0., 0.]])
numpy.round(numpy.matmul(M2, C))array([[ 1., 0., -1.],
[ 0., 1., -1.]])
What’s so special about these matrices? Well \mathbf{M}_{2} \cdot \mathbf{C} defines a transformation taking the K nest-wise deviations to K - 1 relative nest-wise deviations, \theta_{n, k} - \theta_{n, k'}. Here, the anchor nest k' is the nest containing the anchored alternative. At the same time, \mathbf{B} \cdot \mathbf{M}_{1} defines a transformation that adds these relative nest-wise deviations to the corresponding alternatives.
All of this is to say that we can derive the non-redundant nested mixed discrete choice model in two ways. On one hand, we can map the nest-wise deviations into relative nest-wise deviations to eliminate the baseline utility redundancy from the beginning, and then add the relative nest-wise deviations to the appropriate relative baseline utilities. At the same time, we can construct the relative baseline utilities first, and then systematically eliminate the underlying redundancy using the singular value decomposition. Because both approaches implement the same model, we are free to use the one that is most convenient in any given application.
After eliminating the redundancy in the relative baseline utilities, we have to consider the potential redundancy in the covariance parameters.
In the nested mixed discrete choice model, we take the covariance matrix \boldsymbol{\Gamma} to be diagonal, resulting in H = K free parameters. The non-redundant implementation of this model, however, informs only \begin{align*} G &= \frac{ R \, (R + 1) }{ 2 } \\ &= \frac{ (K - 1) \, (K - 1 + 1) }{ 2 } \\ &= \frac{ (K - 1) \, K }{ 2 } \end{align*} covariance parameters. If K > 2 then H < G, and all of the non-zero elements of \boldsymbol{\Gamma} will be informed by the observed data.
What happens, however, if K = 2? Well, let’s consider an explicit example.
J = 10
K = 2
nests = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2]Z = numpy.zeros([J, K])
for k in range(K):
Z[[ j for j in range(J) if nests[j] == k + 1 ], k] = 1
A = numpy.identity(J)
A[:,anchor - 1] -= numpy.ones([J])
W = numpy.matmul(A, Z)U, S, Vt = numpy.linalg.svd(W)
R = sum(S > 1e-15)
C = numpy.concatenate((numpy.matmul(numpy.diag(S[0:R]),
Vt[0:R, 0:R]),
numpy.matmul(numpy.diag(S[0:R]),
Vt[0:R, R:K])),
axis=1)
numpy.round(C, 3)array([[-2.236, 2.236]])
In this case, the matrix \mathbf{C} has the form \mathbf{C} = \begin{pmatrix} a & -a \\ \end{pmatrix}, and the non-singular covariance has the form \begin{align*} \mathbf{\Xi} &= \mathbf{C} \cdot \boldsymbol{\Gamma} \cdot \mathbf{C}^{T} \\ &= \begin{pmatrix} a & -a \\ \end{pmatrix} \cdot \begin{pmatrix} \gamma_{1}^{2} & 0 \\ 0 & \gamma_{2}^{2} \end{pmatrix} \cdot \begin{pmatrix} a \\ -a \end{pmatrix} \\ &= (\gamma_{1}^{2} + \gamma_{2}^{2}) \, a^{2}. \end{align*}
Because \gamma_{1} and \gamma_{2} appear only as a squared sum, observed data will only ever inform that sum and not the individual values. One way to avoid this redundancy is to model the squared sum and then derive the consistent values for \gamma_{1} and \gamma_{2} after the fact.
5.6 Introducing Relative Agent Scales
Once we’ve derived a non-redundant probabilistic model for the relative baseline utilities, we can deal with the redundancy of the agent scales.
Our first step is exactly the same as in the unmixed independent Gumbel model: we distinguish an anchor agent n' and then define relative scales \tau_{n} = \frac{ \sigma_{n} }{ \sigma_{n'} }.
Now, we need to absorb \sigma_{n'} into the relative baseline utilities. In the unmixed independent Gumbel model, this was a deterministic operation where we defined \boldsymbol{\omega}_{n} = \frac{ \boldsymbol{\delta}_{n} }{ \sigma_{n'} }. In the mixed model, however, we need to specify an appropriate probabilistic model for \boldsymbol{\omega}_{n}.
Fortunately this is a relatively – how could this not be an intentional pun – straightforward operation, \boldsymbol{\omega}_{n} = \boldsymbol{\rho}_{n} + \boldsymbol{B} \cdot \boldsymbol{\iota}_{n}, with p ( \boldsymbol{\iota}_{n} ) = \text{multinormal} ( \boldsymbol{\iota}_{n} \mid \boldsymbol{0}, \boldsymbol{\Upsilon} ). Here, \boldsymbol{\rho}_{n} = \frac{1}{\sigma_{n'}} \, \boldsymbol{\chi}_{n} = \frac{1}{\sigma_{n'}} \, \boldsymbol{A} \cdot \boldsymbol{\kappa}_{n} and \begin{align*} \boldsymbol{\Upsilon} &= \frac{1}{\sigma_{n'}} \boldsymbol{\Xi} \\ &= \boldsymbol{C} \cdot \bigg( \frac{1}{\sigma_{n'}} \boldsymbol{\Gamma} \bigg) \cdot \boldsymbol{C}^{T} \\ &\equiv \boldsymbol{C} \cdot \bigg( \Psi \bigg) \cdot \boldsymbol{C}^{T} \end{align*}
In other words, instead of modeling \boldsymbol{\chi}_{n} and \boldsymbol{\Gamma}, we model \boldsymbol{\rho}_{n} and \Psi. The resulting implementation looks the same superficially, but the interpretation of these objects, and consequently any principled prior model, will change.
6 Joint Implementation Of Mixed Models
While mixed discrete choice models are straightforward to construct in theory, they can be a challenge to implement in practice. The immediate difficulty is that evaluating a mixed discrete choice model on an observation requires computing an integral, \begin{align*} p( y_{m} \mid \psi ) &= \mathrm{categorical} ( y_{m} \mid q_{n(m)1} ( \psi ), \ldots, q_{n(m)J} ( \psi ) ) \\ &= q_{n(m) y_{m} } ( \psi ) \\ &= \int \mathrm{d} \phi \, p( \phi \mid \psi ) \, q_{n(m) y_{m}} ( \phi ). \end{align*}
Unfortunately, analytic integration is rarely, if ever, possible, even for relatively simple base choice probabilities q_{nj} ( \phi ) and mixture kernels p( \phi \mid \psi ). While numerical integration is an option, it requires care to implement effectively. Moreover, the cost of accurate numerical integration is often impractical.
Conveniently, the mixing integral is straightforward to accommodate in a Bayesian analysis. Recall that all well-defined Bayesian inferences take the form of posterior expectation values. Moreover, the relevant expectands for mixed discrete choice models are functions of only the global variables \psi, \begin{align*} \mathbb{E}[ f ] &= \int \mathrm{d} \psi \, p(\psi \mid y_{m} ) f( \psi ) \\ &= \int \mathrm{d} \psi \, \frac{ p( y_{m} \mid \psi ) \, p(\psi) }{ \int \mathrm{d} \psi' \, p( y_{m} \mid \psi' ) \, p(\psi') } f( \psi ) \\ &= \frac{ \int \mathrm{d} \psi\hphantom{'} \, p( y_{m} \mid \psi\hphantom{'} ) \, p(\psi\hphantom{'}) \, f( \psi ) }{ \int \mathrm{d} \psi' \, p( y_{m} \mid \psi' ) \, p(\psi') \hphantom{\, f( \psi )} }. \end{align*}
Expanding the mixed model as a continuous mixture allows us to write these expectation values as \begin{align*} \mathbb{E}[ f ] &= \frac{ \int \mathrm{d} \psi\hphantom{'} \, p( y_{m} \mid \psi\hphantom{'} ) \, p(\psi\hphantom{'}) \, f( \psi ) }{ \int \mathrm{d} \psi' \, p( y_{m} \mid \psi' ) \, p(\psi') \hphantom{\, f( \psi )} } \\ &= \frac{ \int \mathrm{d} \psi\hphantom{'} \, \bigg[ \int \mathrm{d} \phi\hphantom{'} \, p( y_{m} \mid \phi\hphantom{'} ) \, p(\phi\hphantom{'} \mid \psi\hphantom{'} ) \bigg] \, p(\psi\hphantom{'}) \, f( \psi ) }{ \int \mathrm{d} \psi' \, \bigg[ \int \mathrm{d} \phi' \, p( y_{m} \mid \phi' ) \, p(\phi' \mid \psi') \bigg] \, p(\psi') \hphantom{\, f( \psi )} } \\ &= \frac{ \int \mathrm{d} \psi\hphantom{'} \, \mathrm{d} \phi\hphantom{'} \, p( y_{m} \mid \phi\hphantom{'} ) \, p(\phi\hphantom{'} \mid \psi\hphantom{'}) \, p(\psi\hphantom{'}) \, f( \psi ) }{ \int \mathrm{d} \psi' \, \mathrm{d} \phi' \, p( y_{m} \mid \phi' ) \, p(\phi' \mid \psi') \, p(\psi') \hphantom{\, f( \psi )} } \\ &= \int \mathrm{d} \psi \, \mathrm{d} \phi \, \frac{ p( y_{m} \mid \phi ) \, p(\phi \mid \psi) \, p(\psi) }{ \int \mathrm{d} \psi' \, \mathrm{d} \phi' \, p( y_{m} \mid \phi' ) \, p(\phi' \mid \psi') \, p(\psi') } f( \psi ) \\ &= \int \mathrm{d} \psi \, \mathrm{d} \phi \, p ( \phi, \psi \mid y_{m} ) \, f( \psi ). \end{align*}
In other words, we will always arrive at the exact same Bayesian inferences regardless of whether we work with the mixed discrete choice model p( y_{m}, \psi) = p( y_{m} \mid \psi ) \, p(\psi), or the joint model p( y_{m}, \phi, \psi) = p( y_{m} \mid \phi ) \, p(\phi \mid \psi) \, p(\psi). The integration over \phi is performed implicitly by our probabilistic computational tooling when we evaluate posterior expectation values.
This derivation, however, concerns only a single observation and its corresponding choice probability. When modeling multiple observations, we generally have to consider multiple choice probabilities. In this case, the corresponding joint model includes a distinct auxiliary parameter for each distinct choice probability. Mechanically, we need a separate \phi for each integral in the mixed model.
Given a single choice set, for example, each agent-alternative pairing results in a distinct choice probability q_{nj} ( \psi ). Consequently, the appropriate joint model introduces one auxiliary parameter for every observed configuration of n and j, \begin{align*} p( y_{1}, \ldots, y_{M}, &\phi_{11}, \ldots, \phi_{NJ}, \psi) \\ &= \prod_{m = 1}^{M} p( y_{m} \mid \phi_{n(m)y_{m}} ) \cdot \prod_{n = 1}^{N} \prod_{j = 1}^{J} p(\phi_{nj} \mid \psi) \cdot p(\psi) \\ &= \prod_{m = 1}^{M} q_{n(m)y_{m}} ( \phi_{n(m)y_{m}} ) \cdot \prod_{n = 1}^{N} \prod_{j = 1}^{J} p(\phi_{nj} \mid \psi) \cdot p(\psi). \end{align*} When the base choice probabilities depend on external variables, q_{nj} ( x_{m}, \phi ), then we would need one auxiliary parameter for every distinct value of x_{m}, \begin{align*} p( y_{1}, \ldots, y_{M}, &\, \phi_{11}, \ldots, \phi_{NJ}, \psi \mid x_{1}, \ldots, x_{M}) \\ &= \prod_{m = 1}^{M} p( y_{m} \mid \phi_{m} ) \, p(\phi_{m} \mid \psi) \cdot p(\psi). \end{align*}
When we are working with multiple choice subsets, the number of auxiliary parameters is even larger. If we have S choice subsets, each containing J_{s} alternatives, then we will have N \, \sum_{s = 1}^{S} J_{s} distinct choice probabilities, each of which requires its own auxiliary parameters.
Even in relatively simple discrete choice settings, the number of these auxiliary parameters in the joint implementation can be imposing. Especially given that the higher the dimension of the model configuration space, the more expensive posterior expectation values are to estimate. Tools like Hamiltonian Monte Carlo that scale exceptionally well with dimension, however, substantially moderate this burden.
A more subtle, but often more important, concern with joint implementations is that the joint posterior distribution can exhibit complex geometries that frustrate efficient computation. In particular, the mixture kernel p( \phi_{nj} \mid \psi ) directly couples the global and auxiliary parameters. When working with smaller data sets this coupling can propagates to the joint posterior distribution where it tends to make the estimation of posterior expectation values less accurate or more expensive.
Interestingly, the posterior geometries induced by the centered and non-centered parameters in the in the multivariate normal mixed baseline model, exhibit complementary geometries. When one frustrates posterior computation, the other will typically be well-behaved. Which implementation achieves optimal performance, however, depends on the details of each application, specifically how often each agent and alternative are observed in each choice subset, as well as how informative the prior model is.
Conveniently, these trade-offs are similar to those seen in normal hierarchical models. Consequently, we can carry over any experience implementing hierarchical models directly to the implementation of these mixed discrete choice models.
7 All Mixed Up
As we have seen, the practical application of mixed discrete choice models is complicated by the engineering of an appropriate mixture kernel, the resolution of any structural redundancies, and the implementation of the mixture integrals. Some applications, however, introduces even more potential pitfalls.
7.1 Mixed Models Verses Hierarchical Models
Like mixed discrete choice models, hierarchical models are defined by continuous mixtures, p( \theta_{1}, \ldots, \theta_{K} \mid \psi ) = \int \mathrm{d} \phi \, p( \phi \mid \psi ) \, \prod_{k = 1}^{K} p( \theta_{k} \mid \phi ). In particular, hierarchical models can also be implemented with a corresponding joint model, p( \theta_{1}, \ldots, \theta_{K}, \phi, \psi ) = p( \phi \mid \psi) \, \prod_{k = 1}^{K} p( \theta_{k} \mid \phi ).
The critical difference between these two approaches, however, is that mixed discrete choice models mix the component observational model, \begin{align*} p( y_{1}, \ldots, y_{M}, \psi ) &= \prod_{m = 1}^{M} \bigg[ \hspace{10.5mm} p( y_{m} \mid \psi ) \hspace{10.5mm} \bigg] p( \psi ) \\ &= \prod_{m = 1}^{M} \bigg[ \int \mathrm{d} \phi \, p( \phi \mid \psi ) p( y_{m} \mid \phi ) \bigg] p( \psi ), \end{align*} while hierarchical models mix the prior model, \begin{align*} p( y_{1}&, \ldots, y_{M}, \theta_{1}, \ldots, \theta_{K}, \psi ) \\ &= \prod_{m = 1}^{M} p( y_{m} \mid \theta_{1}, \ldots, \theta_{K} ) \bigg[ \hspace{10.5mm} p( \theta_{1}, \ldots, \theta_{K} \mid \psi ) \hspace{10.5mm} \bigg] p( \psi ) \\ &= \prod_{m = 1}^{M} p( y_{m} \mid \theta_{1}, \ldots, \theta_{K} ) \bigg[ \int \mathrm{d} \phi \, p( \phi \mid \psi ) \, \prod_{k = 1}^{K} p( \theta_{k} \mid \phi ) \bigg] p( \psi ) \end{align*}
Consequently, the joint implementation of a mixed discrete choice model introduces an auxiliary parameter for each unique configuration of the component observational model, p( y_{1}, \ldots, y_{M}, \phi_{1}, \ldots, \phi_{M}, \psi ) = \prod_{m = 1}^{M} \bigg[ p( \phi \mid \psi_{m} ) p( y_{m} \mid \phi_{m} ) \bigg] p( \psi ), while the joint implementation of a hierarchical model introduces only one auxiliary parameter regardless of the number of observations, \begin{align*} p( y_{1}&, \ldots, y_{M}, \theta_{1}, \ldots, \theta_{K}, \phi, \psi ) \\ &= \prod_{m = 1}^{M} p( y_{m} \mid \theta_{1}, \ldots, \theta_{K} ) \bigg[ p( \phi \mid \psi ) \, \prod_{k = 1}^{K} p( \theta_{k} \mid \phi ) \bigg] p( \psi ). \end{align*}
These slightly different joint implementations can be easy to mistake with each other, especially in models where the global parameter of a discrete choice model might itself be modeled hierarchically, \begin{align*} p( y_{1}&, \ldots, y_{M}, \psi_{1}, \ldots, \psi_{K} ) \\ &= \prod_{m = 1}^{M} \bigg[ \int \mathrm{d} \phi \, p( \phi \mid \psi_{k(m)} ) p( y_{m} \mid \phi ) \bigg] p( \psi_{1}, \ldots, \psi_{K} ) \\&= \prod_{m = 1}^{M} \bigg[ \int \mathrm{d} \phi \, p( \phi \mid \psi_{k(m)} ) p( y_{m} \mid \phi ) \bigg] \int \mathrm{d} \omega \, p( \omega ) \, \prod_{k = 1}^{K} p( \psi_{k} \mid \omega )! \end{align*}
To minimize confusion, we have to carefully distinguish the discrete choice auxiliary parameters and the hierarchical auxiliary parameters. In practice, it can help to write out the mixed model in its entirely, and make sure that each auxiliary parameters in the joint model matches up to one of the integrals.
7.2 Mixed Models Verses Marketing Mix Models
Discrete choice models are particularly common in marketing analyses. In marketing, however, the term “mix” is already overloaded.
Here, the term “marketing mix” refers to the quantities that influence the demand of a product, such as supply, promotion, and price. At the same time, “marketing mix model” refers to statistical analyses that infer how changing these quantities will impact demand (Tellis 2006). Typically, this is done by analyzing observations over time to tease out persistent relationships that are expected to generalize.
Because discrete choice models are quite useful for studying marketing mix, it’s not uncommon to see mixed discrete choice models being employed within marketing mixed models. With all of this overlap, however, the vocabulary often becomes imprecise, making it easy to confuse exactly to what each “mix” refers.
Perhaps the most productive way to avoid confusion in these applications is to refer to models with not jargon but rather their complete mathematical specification. Because this is particularly straightforward with the use of probabilistic programming, these tools are particularly useful for sophisticated marketing analyses.
8 Demonstration
Let’s take some time to anchor – the pun train continues – everything that we have discussed so far by analyzing the data that we analyzed in Part II, only this time with a mixed independent Gumbel model as well.
8.1 Setup
As always, we begin by setting up our local computation environment.
import matplotlib
import matplotlib.pyplot as plot
plot.rcParams['figure.figsize'] = [6, 4]
plot.rcParams['figure.dpi'] = 100
plot.rcParams['font.family'] = "Serif"
plot.rcParams['axes.spines.top'] = False
plot.rcParams['axes.spines.right'] = False
import json
import stan
# Needed to run pystan through a jupyter kernel
import nest_asyncio
nest_asyncio.apply()import sys
sys.path.append('support')
import mcmc_analysis_tools_pystan3 as util
import mcmc_visualization_tools as putil8.2 Read In And Process Data
Next, we read in some discrete choice data where each alternative is associated with one of K nests.
with open("data/obs_choices.json","r") as infile:
data = json.load(infile)
data['choice_counts'] = numpy.array(data['choice_counts'])
for name in data.keys():
if type(data[name]) is numpy.ndarray:
print(f'{name}: {data[name].dtype} Array, '
f'Dimensions: {data[name].shape}')
elif type(data[name]) is list:
print(f'{name}: List, '
f'Length: {len(data[name])}')
else:
print(f'{name}: {type(data[name]).__name__} Scalar')N: int Scalar
J: int Scalar
S: int Scalar
SJ: int Scalar
subset_start: List, Length: 9
subset_end: List, Length: 9
alts: List, Length: 68
choice_counts: int64 Array, Dimensions: (6, 68)
K: int Scalar
nests: List, Length: 10
n_pred: int Scalar
J_pred: int Scalar
pred_alts: List, Length: 10
Comparing behavior across the different choice subsets will be easier with a mapping from global indices to local indices.
subset_alts = []
for s in range(data['S']):
s_idx = data['subset_start'][s] - 1
e_idx = data['subset_end'][s]
subset_alts.append(data['alts'][s_idx:e_idx])
for s in range(data['S']):
print(f'Choice Subset {s + 1}: {subset_alts[s]}')Choice Subset 1: [1, 10, 8, 6, 9, 3, 7]
Choice Subset 2: [7, 4, 2, 5, 6, 9, 10]
Choice Subset 3: [10, 2, 7, 1, 8, 6]
Choice Subset 4: [5, 8, 6, 9, 10, 2, 4, 3]
Choice Subset 5: [9, 2, 4, 10, 5, 1, 3, 7]
Choice Subset 6: [1, 3, 8, 7, 2, 10, 4, 5, 6]
Choice Subset 7: [2, 4, 5, 10, 3, 6]
Choice Subset 8: [1, 2, 3, 4, 6, 7, 8, 10]
Choice Subset 9: [1, 2, 3, 4, 5, 6, 7, 8, 10]
to_subset_idx = [ [ subset_alt.index(j) + 1
if j in subset_alt else None
for j in range(1, data['J'] + 1) ]
for subset_alt in subset_alts ]8.3 Nested Gumbel Model
For a baseline – I don’t even know if this is a pun anymore – let’s construct inferences from a nested Gumbel model.
This will require first specifying a reference alternative. Here, we’ll anchor the one alternative that is shared by all of the choice subsets.
common_alts = set.intersection(
*map(set, [ data['alts'][
(data['subset_start'][s] - 1):
data['subset_end'][s]
]
for s in range(data['S']) ])
)
for alt in common_alts:
print(f'Alternative {alt}:')
for s in range(data['S']):
local_idx = to_subset_idx[s][alt - 1] - 1
MM = int(sum(data['choice_counts'][:, local_idx]))
print(f' {MM} observations in choice subset {s + 1}')Alternative 10:
194 observations in choice subset 1
262 observations in choice subset 2
206 observations in choice subset 3
42 observations in choice subset 4
275 observations in choice subset 5
360 observations in choice subset 6
275 observations in choice subset 7
334 observations in choice subset 8
119 observations in choice subset 9
data['anchor'] = 10This leaves us ready to quantify the posterior distribution.
ng\_joint.stan
functions {
// Insert a zero into x_free at index anchor
vector add_anchor(vector x_free, int anchor) {
int J = size(x_free) + 1;
if (anchor == 1)
return append_row(0, x_free);
else if (anchor == J)
return append_row(x_free, 0);
else
return append_row(x_free[1:(anchor - 1)],
append_row(0, x_free[anchor:(J - 1)]));
}
// Return the number of elements in vals that equal i
int num_which_int(array[] int vals, int i) {
int N = num_elements(vals);
int NN = 0;
for (n in 1:N) {
if (vals[n] == i) {
NN += 1;
}
}
return NN;
}
// Return the elements in vals that equal i
array[] int which_int(array[] int vals, int i) {
int N = num_elements(vals);
array[N] int selected_idxs;
int NN = 0;
for (n in 1:N) {
if (vals[n] == i) {
NN += 1;
selected_idxs[NN] = n;
}
}
return selected_idxs[1:NN];
}
}
data {
int<lower=1> N; // Number of agents
int<lower=1> J; // Number of alternatives in choice set
// Nesting configuration
int<lower=1, upper=J> K;
array[J] int<lower=1, upper=K> nests;
// Choice subset configurations
int<lower=1> S;
int<lower=1> SJ;
array[S] int<lower=1, upper=SJ> subset_start;
array[S] int<lower=1, upper=SJ> subset_end;
array[SJ] int<lower=1, upper=J> alts;
// Aggregated observations
array[N, SJ] int<lower=0> choice_counts;
// Anchoring configuration
int<lower=1, upper=J> anchor;
// Prediction configuration
int<lower=1, upper=N> n_pred;
int<lower=1> J_pred;
array[J_pred] int<lower=1, upper=J> pred_alts;
}
parameters {
// Relative baseline utilities for non-anchor alternatives
vector[J - 1] omega_free;
// Relative scales for non-anchor agents
array[N - 1] real<lower=0> tau_free;
// Intra-nest coupling parameters
vector<lower=0, upper=1>[K] lambda;
}
transformed parameters {
// Relative baseline utilities for all alternatives
vector[J] omega = add_anchor(omega_free, anchor);
// Relative scales for all agents
array[N] real<lower=0> tau = append_array({1}, tau_free);
// Alternative log probabilities
array[N] vector[SJ] log_probs;
for (s in 1:S) {
int JJ = subset_end[s] - subset_start[s] + 1;
array[JJ] int subset_alts
= alts[subset_start[s]:subset_end[s]];
array[JJ] int subset_nests = nests[subset_alts];
for (n in 1:N) {
vector[JJ] subset_log_probs;
vector[K] nest_lses;
vector[K] log_marg_probs;
// Compute marginal probability for each nest
for (k in 1:K) {
int JK = num_which_int(nests[subset_alts], k);
array[JK] int nest_alts
= which_int(nests[subset_alts], k);
nest_lses[k] = log_sum_exp( omega[subset_alts[nest_alts]]
/ (tau[n] * lambda[k]) );
}
log_marg_probs = log_softmax( lambda .* nest_lses );
// Compute joint probability for each alternative in each nest
for (k in 1:K) {
int JK = num_which_int(nests[subset_alts], k);
array[JK] int nest_alts
= which_int(nests[subset_alts], k);
// Joint Probability
subset_log_probs[nest_alts] =
// Marginal Probability
log_marg_probs[k]
// Conditional Probability
+ omega[subset_alts[nest_alts]]
/ (tau[n] * lambda[k])
- nest_lses[k];
}
log_probs[n][subset_start[s]:subset_end[s]]
= subset_log_probs;
}
}
}
model {
// Prior model
target += normal_lpdf(omega_free | 0, 2);
target += lognormal_lpdf(tau_free | 0, 1);
target += beta_lpdf(lambda | 1, 1);
// Observational model
for (n in 1:N) {
for (s in 1:S) {
int JJ = subset_end[s] - subset_start[s] + 1;
vector[JJ] subset_log_probs
= log_probs[n][subset_start[s]:subset_end[s]];
array[JJ] int subset_choice_counts
= choice_counts[n, subset_start[s]:subset_end[s]];
target += multinomial_logit_lpmf(subset_choice_counts |
subset_log_probs);
}
}
}
generated quantities {
array[N, SJ] int<lower=0> choice_counts_pred;
array[SJ] int<lower=0> agg_choice_counts_pred = rep_array(0, SJ);
array[K] int<lower=0> nest_choice_counts_pred = rep_array(0, K);
vector[J_pred] probs_pred;
for (s in 1:S) {
int JJ = subset_end[s] - subset_start[s] + 1;
for (n in 1:N) {
vector[JJ] subset_log_probs
= log_probs[n][subset_start[s]:subset_end[s]];
int MM
= sum(choice_counts[n, subset_start[s]:subset_end[s]]);
choice_counts_pred[n, subset_start[s]:subset_end[s]]
= multinomial_logit_rng(subset_log_probs, MM);
for (j in subset_start[s]:subset_end[s])
agg_choice_counts_pred[j] += choice_counts_pred[n, j];
}
}
for (k in 1:K) {
int JK = num_which_int(nests, k);
array[JK] int nest_alts = which_int(nests, k);
nest_choice_counts_pred[k]
= sum(agg_choice_counts_pred[nest_alts]);
}
{
vector[K] nest_lses;
vector[K] log_marg_probs;
for (k in 1:K) {
int JK = num_which_int(nests[pred_alts], k);
array[JK] int nest_alts
= which_int(nests[pred_alts], k);
nest_lses[k] = log_sum_exp( omega[pred_alts[nest_alts]]
/ (tau[n_pred] * lambda[k]) );
}
log_marg_probs = log_softmax( lambda .* nest_lses );
for (k in 1:K) {
int JK = num_which_int(nests[pred_alts], k);
array[JK] int nest_alts
= which_int(nests[pred_alts], k);
probs_pred[nest_alts]
= exp( log_marg_probs[k]
+ omega[nest_alts] / (tau[n_pred] * lambda[k])
- nest_lses[k]);
}
}
}with open('stan_programs/ng_joint.stan', 'r') as file:
stan_program = file.read()
model = stan.build(stan_program,
random_seed=8438338,
data=data)
fit = model.sample(num_samples=1024, refresh=0)Building...
Fortunately, we don’t see any diagnostic warnings that would indicate inaccurate posterior quantification.
diagnostics = util.extract_hmc_diagnostics(fit)
util.check_all_hmc_diagnostics(diagnostics)
samples_ng = util.extract_expectand_vals(fit)
base_samples = util.filter_expectands(samples_ng,
['omega_free',
'tau_free',
'lambda'],
True)
util.check_all_expectand_diagnostics(base_samples)All Hamiltonian Monte Carlo diagnostics are consistent with accurate
Markov chain Monte Carlo.
All expectands checked appear to be behaving well enough for reliable
Markov chain Monte Carlo estimation.
8.4 Multivariate Normal Mixed Baseline Model 1
Now, let’s see how well we can approximate inferences from the nested Gumbel model using a multivariate normal mixed model that is configured to couple together the baseline utilities for all alternatives in the same nest.
Once we have configured the \boldsymbol{Z} and \boldsymbol{A} matrices appropriately, we need to work through the linear algebra that we demonstrated in Section 5.5 to eliminate all of the redundancy in the nominal model.
Z = numpy.zeros([data['J'], data['K']])
for k in range(data['K']):
Z[ [ j for j in range(data['J'])
if data['nests'][j] == k + 1 ], k] = 1
A = numpy.identity(data['J'])
A[:,data['anchor'] - 1] -= numpy.ones([data['J']])
W = numpy.matmul(A, Z)
U, S, Vt = numpy.linalg.svd(W)
data['R'] = sum(S > 1e-15)
data['B'] = U[:,0:data['R']]
data['C'] = \
numpy.concatenate((numpy.matmul(
numpy.diag(S[0:data['R']]),
Vt[0:data['R'], 0:data['R']]
),
numpy.matmul(
numpy.diag(S[0:data['R']]),
Vt[0:data['R'], data['R']:data['K']])
), axis=1)In this case, we end up removing one excess degree of freedom.
print(f'Rank of combined transformation: {data['R']}')Rank of combined transformation: 2
Technically, we could implement these calculations directly in a Stan program. Personally, however, I prefer calculating the rank of the combined transformation, and all of the subsequent reduced matrices, externally so that I can review the effective zero threshold by hand. Just in case any floating point trickery is afoot.
For this analysis, each of the N \cdot S unique combinations of agents and choice subsets defines a unique set of choice probabilities. In order to implement the mixed model, we will need N \cdot S distinct vectors of auxiliary deviations, each of which can be implemented with a centered or non-centered parameterization. Instead of hard-coding a centered or non-centered implementation for each of these vectors, we’ll use a more general Stan program where the precise parameterization can be configured externally.
mig\_joint1.stan
functions {
// Insert a zero into x_free at index anchor
vector add_anchor(vector x_free, int anchor) {
int J = size(x_free) + 1;
if (anchor == 1)
return append_row(0, x_free);
else if (anchor == J)
return append_row(x_free, 0);
else
return append_row(x_free[1:(anchor - 1)],
append_row(0, x_free[anchor:(J - 1)]));
}
// Return the number of elements in vals that equal i
int num_which_int(array[] int vals, int i) {
int N = num_elements(vals);
int NN = 0;
for (n in 1:N) {
if (vals[n] == i) {
NN += 1;
}
}
return NN;
}
// Return the elements in vals that equal i
array[] int which_int(array[] int vals, int i) {
int N = num_elements(vals);
array[N] int selected_idxs;
int NN = 0;
for (n in 1:N) {
if (vals[n] == i) {
NN += 1;
selected_idxs[NN] = n;
}
}
return selected_idxs[1:NN];
}
}
data {
int<lower=1> N; // Number of agents
int<lower=1> J; // Number of alternatives in choice set
// Nesting configuration
int<lower=1, upper=J> K;
array[J] int<lower=1, upper=K> nests;
int<lower=1, upper=K> R;
matrix[J, R] B;
matrix[R, K] C;
// Choice subset configurations
int<lower=1> S;
int<lower=1> SJ;
array[S] int<lower=1, upper=SJ> subset_start;
array[S] int<lower=1, upper=SJ> subset_end;
array[SJ] int<lower=1, upper=J> alts;
// Mixed parameterization configuration
int<lower=0, upper=N * S> I_cp;
array[I_cp, 2] int cp_idxs;
int<lower=0, upper=N * S> I_ncp;
array[I_ncp, 2] int ncp_idxs;
// Aggregated observations
array[N, SJ] int<lower=0> choice_counts;
// Anchoring configuration
int<lower=1, upper=J> anchor;
// Prediction configuration
int<lower=1, upper=N> n_pred;
int<lower=1> J_pred;
array[J_pred] int<lower=1, upper=J> pred_alts;
}
parameters {
// Relative baseline utilities for non-anchor alternatives
vector[J - 1] rho_free;
// Relative scales for non-anchor agents
array[N - 1] real<lower=0> tau_free;
// Baseline utility mixture model configuration
vector<lower=0>[K] psi;
array[I_cp] vector[R] iota_cp;
array[I_ncp] vector[R] iota_ncp;
}
transformed parameters {
// Relative baseline utilities for all alternatives
vector[J] rho = add_anchor(rho_free, anchor);
// Relative scales for all agents
array[N] real<lower=0> tau = append_array({1}, tau_free);
// Nest contributions to relative baseline utilities
array[N, S] vector[R] iota;
// Alternative log probabilities
array[N] vector[SJ] log_probs;
{
// Transformation of latent covariance
matrix[R, R] Upsilon
= quad_form(diag_matrix(square(psi)), C');
matrix[R, R] L_Upsilon = cholesky_decompose(Upsilon);
for (i in 1:I_cp)
iota[ cp_idxs[i, 1], cp_idxs[i, 2]] = iota_cp[i];
for (i in 1:I_ncp)
iota[ncp_idxs[i, 1], ncp_idxs[i, 2]] = L_Upsilon * iota_ncp[i];
}
for (s in 1:S) {
int JJ = subset_end[s] - subset_start[s] + 1;
array[JJ] int subset_alts
= alts[subset_start[s]:subset_end[s]];
vector[JJ] subset_rho = rho[subset_alts];
for (n in 1:N) {
vector[JJ] subset_theta = (B * iota[n, s])[subset_alts];
log_probs[n][subset_start[s]:subset_end[s]]
= log_softmax( (subset_rho + subset_theta) / tau[n] );
}
}
}
model {
// Transformation of latent covariance
matrix[R, R] Upsilon
= quad_form(diag_matrix(square(psi)), C');
matrix[R, R] L_Upsilon = cholesky_decompose(Upsilon);
// Prior model
target += normal_lpdf(rho_free | 0, 10);
target += normal_lpdf(tau_free | 0, 10);
target += normal_lpdf(psi | 0, 10);
for (i in 1:I_cp)
target += multi_normal_cholesky_lpdf(iota_cp[i] |
zeros_vector(R),
L_Upsilon);
for (i in 1:I_ncp)
target += normal_lpdf(iota_ncp[i] | 0, 1);
// Observational model
for (s in 1:S) {
int JJ = subset_end[s] - subset_start[s] + 1;
for (n in 1:N) {
vector[JJ] subset_log_probs
= log_probs[n][subset_start[s]:subset_end[s]];
array[JJ] int subset_choice_counts
= choice_counts[n, subset_start[s]:subset_end[s]];
target += multinomial_logit_lpmf(subset_choice_counts |
subset_log_probs);
}
}
}
generated quantities {
array[N, SJ] int<lower=0> choice_counts_pred;
array[SJ] int<lower=0> agg_choice_counts_pred = rep_array(0, SJ);
array[K] int<lower=0> nest_choice_counts_pred = rep_array(0, K);
vector[J_pred] probs_pred;
for (s in 1:S) {
int JJ = subset_end[s] - subset_start[s] + 1;
for (n in 1:N) {
vector[JJ] subset_log_probs
= log_probs[n][subset_start[s]:subset_end[s]];
int MM
= sum(choice_counts[n, subset_start[s]:subset_end[s]]);
choice_counts_pred[n, subset_start[s]:subset_end[s]]
= multinomial_logit_rng(subset_log_probs, MM);
for (j in subset_start[s]:subset_end[s])
agg_choice_counts_pred[j] += choice_counts_pred[n, j];
}
}
for (k in 1:K) {
int JK = num_which_int(nests, k);
array[JK] int nest_alts = which_int(nests, k);
nest_choice_counts_pred[k]
= sum(agg_choice_counts_pred[nest_alts]);
}
{
matrix[R, R] Upsilon
= quad_form(diag_matrix(square(psi)), C');
matrix[R, R] L_Upsilon = cholesky_decompose(Upsilon);
vector[J_pred] pred_rho = rho[pred_alts];
vector[R] pred_iota
= multi_normal_cholesky_rng(zeros_vector(R), L_Upsilon);
vector[J_pred] pred_theta = (B * pred_iota)[pred_alts];
probs_pred
= softmax( (pred_rho + pred_theta) / tau[n_pred] );
}
}Let’s start by configuring the Stan program so that all of the deviations are centered.
data['I_cp'] = data['N'] * data['S']
data['cp_idxs'] = \
numpy.empty([data['I_cp'], 2]).astype(numpy.int64)
i = 0
for n in range(data['N']):
for s in range(data['S']):
data['cp_idxs'][i, 0] = n + 1
data['cp_idxs'][i, 1] = s + 1
i += 1
data['I_ncp'] = 0
data['ncp_idxs'] = \
numpy.empty([0, 2]).astype(numpy.int64)with open('stan_programs/mig_joint1.stan', 'r') as file:
stan_program = file.read()
model = stan.build(stan_program,
random_seed=8438338,
data=data)
fit = model.sample(num_samples=1024, refresh=0)Building...
Unfortunately, this can result in a stray divergence or two.
diagnostics1 = util.extract_hmc_diagnostics(fit)
util.check_all_hmc_diagnostics(diagnostics1)
samples_mig = util.extract_expectand_vals(fit)
base_samples = util.filter_expectands(samples_mig,
['rho_free',
'tau_free',
'psi',
'iota_cp'],
True)
util.check_all_expectand_diagnostics(base_samples)All Hamiltonian Monte Carlo diagnostics are consistent with accurate
Markov chain Monte Carlo.
All expectands checked appear to be behaving well enough for reliable
Markov chain Monte Carlo estimation.
We should be able to achieve a better posterior geometry, and eliminate any divergences, by non-centering the least-informed deviations. While we can’t quantify how informed each deviation is a priori, we can use the total number of observations as a reasonable proxy.
total_counts = numpy.zeros([data['N'], data['S']])
for s in range(data['S']):
idx1 = data['subset_start'][s] - 1
idx2 = data['subset_end'][s]
for n in range(data['N']):
total_counts[n, s] = \
sum(data['choice_counts'][n, idx1:idx2])Most of the deviations are observed a similar number of times, but a few are less frequent.
putil.plot_line_hist(plot.gca(), total_counts,
200, 330, 10,
xlabel='Total Observations')
plot.show()Let’s start by non-centering only the rarest deviations, which we define by a heuristic threshold on the number of observations.
cp_threshold = 230
putil.plot_line_hist(plot.gca(), total_counts,
200, 330, 10,
xlabel='Total Observations')
plot.axvline(x=cp_threshold, linewidth=4, color="white")
plot.axvline(x=cp_threshold, linewidth=2, color=util.mid_teal)
plot.show()data['I_cp'] = \
numpy.sum(total_counts >= cp_threshold)
data['cp_idxs'] = \
numpy.empty([data['I_cp'], 2]).astype(numpy.int64)
data['I_ncp'] = \
data['N'] * data['S'] - data['I_cp']
data['ncp_idxs'] = \
numpy.empty([data['I_ncp'], 2]).astype(numpy.int64)
i_cp = 0
i_ncp = 0
for n in range(data['N']):
for s in range(data['S']):
if total_counts[n, s] >= cp_threshold:
data['cp_idxs'][i_cp, 0] = n + 1
data['cp_idxs'][i_cp, 1] = s + 1
i_cp += 1
else:
data['ncp_idxs'][i_ncp, 0] = n + 1
data['ncp_idxs'][i_ncp, 1] = s + 1
i_ncp += 1/var/folders/bb/67q6n75n13xcq3tcqt9mn44h0000gn/T/ipykernel_77536/4033696558.py:9: RuntimeWarning: invalid value encountered in cast
numpy.empty([data['I_ncp'], 2]).astype(numpy.int64)
Let’s see if this more sophisticated parameterization does any better.
with open('stan_programs/mig_joint1.stan', 'r') as file:
stan_program = file.read()
model = stan.build(stan_program,
random_seed=8438338,
data=data)
fit = model.sample(num_samples=1024, refresh=0)Building...
Indeed, the computational diagnostics are now clean.
diagnostics2 = util.extract_hmc_diagnostics(fit)
util.check_all_hmc_diagnostics(diagnostics2)
samples_mig = util.extract_expectand_vals(fit)
base_samples = util.filter_expectands(samples_mig,
['rho_free',
'tau_free',
'psi',
'iota_ncp'],
True)
util.check_all_expectand_diagnostics(base_samples)All Hamiltonian Monte Carlo diagnostics are consistent with accurate
Markov chain Monte Carlo.
All expectands checked appear to be behaving well enough for reliable
Markov chain Monte Carlo estimation.
After all of that, we can finally compare the inferences derived from the mixed model to those derived from the nested Gumbel model. The inferred probabilities for the full choice set are consistent, both with each other and the true values. That said, the uncertainties in the mixed model are substantially larger.
with open("data/truth.json","r") as infile:
truth = json.load(infile)
probs_true = numpy.exp(truth['log_probs_true'])
f, axarr = plot.subplots(2, 1, layout="constrained")
names = [ f'probs_pred[{j + 1}]'
for j in range(data['J']) ]
putil.plot_disc_pushforward_quantiles(
axarr[0], samples_ng, names,
baseline_values=probs_true,
baseline_color=putil.mid_teal,
xlabel="Alternative",
xticklabels=range(1, data['J'] + 1),
ylabel="Probability",
display_ylim=[0, 0.25],
title="Nested Gumbel Model"
)
names = [ f'probs_pred[{j + 1}]'
for j in range(data['J']) ]
putil.plot_disc_pushforward_quantiles(
axarr[1], samples_mig, names,
baseline_values=probs_true,
baseline_color=putil.mid_teal,
xlabel="Alternative",
xticklabels=range(1, data['J'] + 1),
ylabel="Probability",
display_ylim=[0, 0.25],
title="Nested Mixed Model"
)
plot.show()That said, we have to be careful comparing the parameters in the two models: many of the parameters are similar, but not exactly equivalent. For example, our inferences for the relative baseline utilities in the nested Gumbel model and the relative baseline-baseline utilities in the mixed model are not at all consistent.
omega_true = \
( numpy.array(truth['mu_true']) \
- truth['mu_true'][data['anchor'] - 1]) \
/ truth['sigma_true'][0]
f, axarr = plot.subplots(2, 1, layout="constrained")
names = [ f'omega[{j + 1}]' for j in range(data['J']) ]
putil.plot_disc_pushforward_quantiles(
axarr[0], samples_ng, names,
baseline_values=omega_true,
baseline_color=putil.mid_teal,
xlabel="Alternative",
xticklabels=range(1, data['J'] + 1),
ylabel="Relative\nBaseline\nUtility",
display_ylim=[-1.25, 0.75],
title="Nested Gumbel Model"
)
names = [ f'rho[{j + 1}]' for j in range(data['J']) ]
putil.plot_disc_pushforward_quantiles(
axarr[1], samples_mig, names,
baseline_values=omega_true,
baseline_color=putil.mid_teal,
xlabel="Alternative",
xticklabels=range(1, data['J'] + 1),
ylabel="Relative\nBaseline-Baseline\nUtility",
display_ylim=[-1.25, 0.75],
title="Nested Mixed Model"
)
plot.show()On the other hand, the inferred agent scales are nearly equivalent in the two models.
tau_true = numpy.array(truth['sigma_true']) \
/ truth['sigma_true'][0]
f, axarr = plot.subplots(2, 1, layout="constrained")
names = [ f'tau[{n + 1}]' for n in range(data['N']) ]
putil.plot_disc_pushforward_quantiles(
axarr[0], samples_ng, names,
baseline_values=tau_true,
baseline_color=putil.mid_teal,
xlabel="Agent",
xticklabels=range(1, data['N'] + 1),
ylabel="Relative Scale",
display_ylim=[0.5, 1.1],
title="Nested Gumbel Model"
)
names = [ f'tau[{n + 1}]' for n in range(data['N']) ]
putil.plot_disc_pushforward_quantiles(
axarr[1], samples_mig, names,
baseline_values=tau_true,
baseline_color=putil.mid_teal,
xlabel="Agent",
xticklabels=range(1, data['N'] + 1),
ylabel="Relative Scale",
display_ylim=[0.5, 1.1],
title="Nested Mixed Model"
)
plot.show()This leaves inferences for the intra-nest coupling parameters in the two models, which are qualitatively, but not quantitatively, similar. Once we reorient the \lambda_{k} in the nested Gumbel model, they behave qualitatively similar to the \psi_{k} in the mixed model: the alternatives in the second nest are the most strongly coupled, while the alternatives in the third nest are the most weakly coupled.
f, axarr = plot.subplots(2, 3, layout='constrained')
for k in range(1, data['K'] + 1):
util.plot_expectand_pushforward(
axarr[0, k - 1],
1 - samples_ng[f'lambda[{k}]'],
50, flim=[0, 1],
display_name=f'1 - lambda[{k}]',
baseline=1 - truth['lambda_true'][k - 1],
baseline_color=putil.mid_teal
)
for k in range(1, data['K'] + 1):
util.plot_expectand_pushforward(
axarr[1, k - 1],
samples_mig[f'psi[{k}]'],
25, flim=[0, 0.4],
display_name=f'psi[{k}]',
)
plot.show()In between, however, the inferences for 1 - \lambda_{1} fall closer to 1 - \lambda_{3} than 1 - \lambda_{2}, while those of \psi_{1} fall closer to \psi_{2} than \psi_{3}. That said, the uncertainties for the \psi_{k} are relatively large.
Ultimately, when using mixed discrete choice models to approximate other discrete choice models, we have to be careful interpreting any quantities but the choice probabilities.
8.5 Multivariate Normal Mixed Baseline Model 2
Lastly, in Section 5.5 we saw that we can also implement the nested mixed model by introducing nest-wise deviations, and then allocating them to each alternative. This is straightforward to implement in the Stan modeling language.
mig\_joint2.stan
functions {
// Insert a zero into x_free at index anchor
vector add_anchor(vector x_free, int anchor) {
int J = size(x_free) + 1;
if (anchor == 1)
return append_row(0, x_free);
else if (anchor == J)
return append_row(x_free, 0);
else
return append_row(x_free[1:(anchor - 1)],
append_row(0, x_free[anchor:(J - 1)]));
}
// Return the number of elements in vals that equal i
int num_which_int(array[] int vals, int i) {
int N = num_elements(vals);
int NN = 0;
for (n in 1:N) {
if (vals[n] == i) {
NN += 1;
}
}
return NN;
}
// Return the elements in vals that equal i
array[] int which_int(array[] int vals, int i) {
int N = num_elements(vals);
array[N] int selected_idxs;
int NN = 0;
for (n in 1:N) {
if (vals[n] == i) {
NN += 1;
selected_idxs[NN] = n;
}
}
return selected_idxs[1:NN];
}
// Remove the ith row from the matrix X
matrix thin(matrix X, int i) {
int N = rows(X);
array[N - 1] int idxs;
if (i == 1)
idxs = linspaced_int_array(N - 1, 2, N);
else if (i == N)
idxs = linspaced_int_array(N - 1, 1, N - 1);
else
idxs = append_array(linspaced_int_array(i - 1, 1, i - 1),
linspaced_int_array(N - i, i + 1, N) );
return X[idxs,];
}
}
data {
int<lower=1> N; // Number of agents
int<lower=1> J; // Number of alternatives in choice set
// Nesting configuration
int<lower=1, upper=J> K;
array[J] int<lower=1, upper=K> nests;
// Choice subset configurations
int<lower=1> S;
int<lower=1> SJ;
array[S] int<lower=1, upper=SJ> subset_start;
array[S] int<lower=1, upper=SJ> subset_end;
array[SJ] int<lower=1, upper=J> alts;
// Mixed parameterization configuration
int<lower=0, upper=N * S> I_cp;
array[I_cp, 2] int cp_idxs;
int<lower=0, upper=N * S> I_ncp;
array[I_ncp, 2] int ncp_idxs;
// Aggregated observations
array[N, SJ] int<lower=0> choice_counts;
// Anchoring configuration
int<lower=1, upper=J> anchor;
// Prediction configuration
int<lower=1, upper=N> n_pred;
int<lower=1> J_pred;
array[J_pred] int<lower=1, upper=J> pred_alts;
}
transformed data {
// Nest contribution anchoring
int<lower=1, upper=K> anchor_nest = nests[anchor];
matrix[K - 1, K] NA;
matrix[K, K] NA_full = identity_matrix(K);
NA_full[, anchor_nest] += -ones_vector(K);
NA = thin(NA_full, anchor_nest);
}
parameters {
// Relative baseline utilities for non-anchor alternatives
vector[J - 1] rho_free;
// Relative scales for non-anchor agents
array[N - 1] real<lower=0> tau_free;
// Baseline utility mixture model configuration
vector<lower=0>[K] psi;
array[I_cp] vector[K - 1] iota_cp;
array[I_ncp] vector[K - 1] iota_ncp;
}
transformed parameters {
// Relative baseline utilities for all alternatives
vector[J] rho = add_anchor(rho_free, anchor);
// Relative scales for all agents
array[N] real<lower=0> tau = append_array({1}, tau_free);
// Nest contributions to relative baseline utilities
array[N, S] vector[K - 1] iota;
// Alternative log probabilities
array[N] vector[SJ] log_probs;
{
// Transformation of latent covariance
matrix[K - 1, K - 1] Upsilon
= quad_form(diag_matrix(square(psi)), NA');
matrix[K - 1, K - 1] L_Upsilon = cholesky_decompose(Upsilon);
for (i in 1:I_cp)
iota[ cp_idxs[i, 1], cp_idxs[i, 2]] = iota_cp[i];
for (i in 1:I_ncp)
iota[ncp_idxs[i, 1], ncp_idxs[i, 2]] = L_Upsilon * iota_ncp[i];
}
for (s in 1:S) {
int JJ = subset_end[s] - subset_start[s] + 1;
array[JJ] int subset_alts
= alts[subset_start[s]:subset_end[s]];
vector[JJ] subset_rho = rho[subset_alts];
array[JJ] int subset_nests = nests[subset_alts];
for (n in 1:N) {
vector[K] theta = add_anchor(iota[n, s], anchor_nest);
vector[JJ] subset_theta = theta[subset_nests];
log_probs[n][subset_start[s]:subset_end[s]]
= log_softmax( (subset_rho + subset_theta) / tau[n] );
}
}
}
model {
// Transformation of latent covariance
matrix[K - 1, K - 1] Upsilon
= quad_form(diag_matrix(square(psi)), NA');
matrix[K - 1, K - 1] L_Upsilon = cholesky_decompose(Upsilon);
// Prior model
target += normal_lpdf(rho_free | 0, 10);
target += normal_lpdf(tau_free | 0, 10);
target += normal_lpdf(psi | 0, 10);
for (i in 1:I_cp)
target += multi_normal_cholesky_lpdf(iota_cp[i] |
zeros_vector(K - 1),
L_Upsilon);
for (i in 1:I_ncp)
target += normal_lpdf(iota_ncp[i] | 0, 1);
// Observational model
for (s in 1:S) {
int JJ = subset_end[s] - subset_start[s] + 1;
for (n in 1:N) {
vector[JJ] subset_log_probs
= log_probs[n][subset_start[s]:subset_end[s]];
array[JJ] int subset_choice_counts
= choice_counts[n, subset_start[s]:subset_end[s]];
target += multinomial_logit_lpmf(subset_choice_counts |
subset_log_probs);
}
}
}
generated quantities {
array[N, SJ] int<lower=0> choice_counts_pred;
array[SJ] int<lower=0> agg_choice_counts_pred = rep_array(0, SJ);
array[K] int<lower=0> nest_choice_counts_pred = rep_array(0, K);
vector[J_pred] probs_pred;
for (s in 1:S) {
int JJ = subset_end[s] - subset_start[s] + 1;
for (n in 1:N) {
vector[JJ] subset_log_probs
= log_probs[n][subset_start[s]:subset_end[s]];
int MM
= sum(choice_counts[n, subset_start[s]:subset_end[s]]);
choice_counts_pred[n, subset_start[s]:subset_end[s]]
= multinomial_logit_rng(subset_log_probs, MM);
for (j in subset_start[s]:subset_end[s])
agg_choice_counts_pred[j] += choice_counts_pred[n, j];
}
}
for (k in 1:K) {
int JK = num_which_int(nests, k);
array[JK] int nest_alts = which_int(nests, k);
nest_choice_counts_pred[k]
= sum(agg_choice_counts_pred[nest_alts]);
}
{
matrix[K - 1, K - 1] Upsilon
= quad_form(diag_matrix(square(psi)), NA');
matrix[K - 1, K - 1] L_Upsilon = cholesky_decompose(Upsilon);
vector[J_pred] pred_rho = rho[pred_alts];
array[J_pred] int pred_nests = nests[pred_alts];
vector[K - 1] iota_pred
= multi_normal_cholesky_rng(zeros_vector(K - 1), L_Upsilon);
vector[K] theta = add_anchor(iota_pred, anchor_nest);
vector[J_pred] pred_theta = theta[pred_nests];
probs_pred
= softmax( (pred_rho + pred_theta) / tau[n_pred] );
}
}Note that we using the same parameterization configuration that we used above. To focus on the comparison, and avoid having to worry about any parameterization fiddling, let’s prophylactically set \delta_{\mathrm{adapt}} to 0.95. This will reduce the aggressiveness of the sampler adaptation, avoiding divergences at the cost of increased computation.
with open('stan_programs/mig_joint2.stan', 'r') as file:
stan_program = file.read()
model = stan.build(stan_program,
random_seed=8438338,
data=data)
fit = model.sample(num_samples=1024, refresh=0,
delta=0.95)Building...
There are no signs of computational problems with this alternative implementation.
diagnostics = util.extract_hmc_diagnostics(fit)
util.check_all_hmc_diagnostics(diagnostics)
samples_mig2 = util.extract_expectand_vals(fit)
base_samples = util.filter_expectands(samples_mig2,
['rho_free',
'tau_free',
'psi',
'iota_ncp'],
True)
util.check_all_expectand_diagnostics(base_samples)All Hamiltonian Monte Carlo diagnostics are consistent with accurate
Markov chain Monte Carlo.
All expectands checked appear to be behaving well enough for reliable
Markov chain Monte Carlo estimation.
Moreover, the resulting inferences are consistent with those from our previous mixed model implementation, at least up to the expected Markov chain Monte Carlo error.
f, axarr = plot.subplots(2, 1, layout="constrained")
names = [ f'probs_pred[{j + 1}]' for j in range(data['J']) ]
putil.plot_disc_pushforward_quantiles(
axarr[0], samples_mig, names,
baseline_values=probs_true,
baseline_color=putil.mid_teal,
xlabel="Alternative",
xticklabels=range(1, data['J'] + 1),
ylabel="Probability",
display_ylim=[0, 0.25],
title="Implementation 1"
)
names = [ f'probs_pred[{j + 1}]' for j in range(data['J']) ]
putil.plot_disc_pushforward_quantiles(
axarr[1], samples_mig2, names,
baseline_values=probs_true,
baseline_color=putil.mid_teal,
xlabel="Alternative",
xticklabels=range(1, data['J'] + 1),
ylabel="Probability",
display_ylim=[0, 0.25],
title="Implementation 2"
)
plot.show()f, axarr = plot.subplots(2, 1, layout="constrained")
names = [ f'rho[{j + 1}]' for j in range(data['J']) ]
putil.plot_disc_pushforward_quantiles(
axarr[0], samples_mig, names,
xlabel="Alternative",
xticklabels=range(1, data['J'] + 1),
ylabel="Relative\nBaseline-Baseline\nUtility",
display_ylim=[-1.25, 0.75],
title="Implementation 1"
)
names = [ f'rho[{j + 1}]' for j in range(data['J']) ]
putil.plot_disc_pushforward_quantiles(
axarr[1], samples_mig2, names,
xlabel="Alternative",
xticklabels=range(1, data['J'] + 1),
ylabel="Relative\nBaseline-Baseline\nUtility",
display_ylim=[-1.25, 0.75],
title="Implementation 2"
)Mixed discrete choice models encompass a wide range of behaviors. Moreover, these behaviors, can often be implemented in different ways. We are free to derive, and then implement, these mixed models in whichever way is most convenient to ourselves and our collaborators.
9 Conclusion
Mixed discrete choice modeling is a powerful tool for elaborating the behavior of an initial discrete choice model. Many mixed models, in particular multivariate normal mixed baseline models, can be implemented systematically using linear algebra tools, without the need to analytically re-derive choice probabilities for each application. That said, the substitution patterns exhibited by these mixed models are often subtle, and tricky to interpret.
Ultimately, the different modeling strategies that we’ve discussed in Part II and here offer distinct advantages and disadvantages in practice. The benefit in being familiar with as many of these strategies as possible is that we can identify the most productive tool for any given application.
Acknowledgements
I thank Andrés Castro Araújo, jd, and Fred Feinberg for helpful comments.
A very special thanks to everyone supporting me on Patreon: Alessandro Varacca, Alex D, Alexander Noll, Amit, Andrea Serafino, Andrew Mascioli, Andrew Rouillard, Ara Winter, Ari Holtzman, Austin Rochford, Aviv Keshet, Avraham Adler, Ben Matthews, Ben Swallow, Benoit Essiambre, boot, Brendan Galdo, Bryan Chang, Cameron Smith, Canaan Breiss, Cat Shark, Cathy Oliveri, Charles Naylor, Chase Dwelle, Chris Jones, Christina Van Heer, Christopher Mehrvarzi, Colin Carroll, Colin McAuliffe, Damien Mannion, dan mackinlay, Dan W Joyce, Dan Waxman, Dan Weitzenfeld, Daniel Edward Marthaler, Daniel Hammarström, Danny Van Nest, David Burdelski, Doug Rivers, Dr. Jobo, Dr. Omri Har Shemesh, Dylan Maher, Dylan Spielman, Ebriand, Ed Cashin, Edgar Merkle, Edoardo Marcora, Eric LaMotte, Erik Banek, Eugene O’Friel, Felipe Vaca, Fergus Chadwick, Francesco Corona, Geoff Rollins, Glenn Williams, Granville Matheson, Gregor Gorjanc, Guilherme Marthe, Håkan Johansson, Hamed Bastan-Hagh, haubur, Hector Munoz, hs, Hugo Botha, Ian Costley, idontgetoutmuch, Ignacio Vera, Ilaria Prosdocimi, Isaac Vock, Isidor Belic, jacob pine, Jair Andrade, James C, James Hodgson, James Wade, Janek Berger, Jarrett Byrnes, Jason Martin, Jason Pekos, Jason Wong, jd, Jeff Burnett, Jeff Dotson, Jeff Helzner, Jeffrey Erlich, Jerry Lin , Jessica Graves, Joe Sloan, John Flournoy, Jonathan H. Morgan, Jonathon Vallejo, Josh Knecht, JU, Julian Lee, Justin Bois, Kádár András, Karim Naguib, Karim Osman, Konstantin Shakhbazov, Kristian Gårdhus Wichmann, Lars Barquist, lizzie , LOU ODETTE, Mads Christian Hansen, Marek Kwiatkowski, Mariana Carmona, Mark Donoghoe, Markus P., Márton Vaitkus, Matěj, Matthew, Matthieu LEROY, Mattia Arsendi, Maurits van der Meer, Max, Michael Colaresi, Michael DeJesus, Michael DeWitt, Michael Dillon, Michael Lerner, Mick Cooney, MisterMentat , N Sanders, N.S. , Name, Nathaniel Burbank, Nicholas Cowie, Nick S, Nikita Karetnikov, Octavio Medina, Ole Rogeberg, Olivier Ma, Patrick Kelley, Patrick Boehnke, Pau Pereira Batlle, Pieter van den Berg , ptr, quasar, Ramiro Barrantes Reynolds, Raúl Peralta Lozada, Rex, Riccardo Fusaroli, Richard Nerland, Rob Davies, Robert Frost, Robert Goldman, Robert kohn, Robin Taylor, Ryan Gan, Ryan Grossman, Ryan Kelly, S Hong, Sean Wilson, Sergiy Protsiv, Seth Axen, shira, Simon Duane, Simon Lilburn, Simon Steiger, Simone, Spencer Boucher, sssz, Stefan Lorenz, Stephen Lienhard, Steve Harris, Steven Forrest, Stew Watts, Stone Chen, Susan Holmes, Svilup, Tate Tunstall, Tatsuo Okubo, Teresa Ortiz, Theodore Dasher, Thomas Siegert, Thomas Vladeck, Tobychev , Tomas Capretto, Tony Wuersch, Virgile Andreani, Virginia Fisher, Vitalie Spinu, Vladimir Markov, VO2 Maximus Decius, Will Farr, Will Lowe, Will Wen, Xianda Sun, yolhaj , yureq , Zach A, and Zhengchen Cai.
References
License
The code in this case study is copyrighted by Michael Betancourt and licensed under the new BSD (3-clause) license:
https://opensource.org/licenses/BSD-3-Clause
The text and figures in this chapter are copyrighted by Michael Betancourt and licensed under the CC BY-NC 4.0 license:
Original Computing Environment
from watermark import watermark
print(watermark())Last updated: 2026-12-02T17:14:15.007267-05:00
Python implementation: CPython
Python version : 3.12.10
IPython version : 9.6.0
Compiler : Clang 13.0.0 (clang-1300.0.29.30)
OS : Darwin
Release : 24.6.0
Machine : x86_64
Processor : i386
CPU cores : 16
Architecture: 64bit
print(watermark(packages="matplotlib,numpy,stan,scipy"))matplotlib: 3.10.7
numpy : 2.3.4
stan : 3.10.0
scipy : 1.16.3