Module contents
Lesson 9 of 28Advanced 110 min

Structural models II: discrete choice and sample selection

Derive discrete-choice models from random utility, calculate marginal effects, study substitution and IIA, and distinguish Tobit censoring from Heckman selection and truncation.

After this lesson you can

  • Derive binary logit and probit and conditional logit from random utility.
  • Calculate average marginal effects and effects at the mean with delta-method standard errors.
  • Estimate conditional logit on transport mode choices and examine IIA.
  • Implement two-step and maximum-likelihood Heckman estimation and discuss exclusion.
  • Distinguish censoring, truncation and selection and choose an appropriate model.

Before you start

Deciding and observing are different

A team chooses among security tools. Each has different cost, deployment time and coverage. Predicting what happens when a new tool arrives requires a substitution model, not only historical shares of existing tools. In another problem, wages are observed only for people who work: can you estimate the education-offered-wage relationship while ignoring why some people work and others do not?

Both questions require specifying decisions and observation. Good fit does not guarantee preferences are invariant under a new policy or that selection has been corrected.

Random utility and probabilities

In a random utility model, person ii chooses the available alternative with highest Uij=Vij+ϵijU_{ij}=V_{ij}+\epsilon_{ij}. Component VV summarizes observed attributes and parameters; ϵ\epsilon captures unobserved differences. Only utility differences matter: adding the same constant or multiplying all utilities by a positive scale does not change choice. A disturbance scale must therefore be normalized.

If disturbances are independent identically distributed type-I Gumbel with scale s>0s>0, integrating the probability that jj exceeds all others gives

Pij=exp⁡(Vij/s)∑kexp⁡(Vik/s).P_{ij}=\frac{\exp(V_{ij}/s)}{\sum_k\exp(V_{ik}/s)}.

To see the integration, condition on ϵj=e\epsilon_j=e, multiply its density by distribution functions Fk(e+Vj−Vk)F_k(e+V_j-V_k) and substitute t=exp⁡(−e/s)t=\exp(-e/s). The remaining integral is exponential and yields the preceding ratio. In binary choice, the difference of two iid Gumbels is logistic; usual normalization s=1s=1 yields logit. If the error difference is normal, probit results: P(Y=1∣x)=Φ(x⊤β)P(Y=1\mid x)=\Phi(x^\top\beta) after fixing its deviation. In multinomial choice, normal errors yield multinomial probit, generally without a softmax formula. Train develops the assumptions.

InteractiveFrom random utility to softmax

Each decision maker chooses the largest utility Vⱼ+εⱼ. Bars are simulated frequencies; marks show exact softmax for the Gumbel model. Segments show 95% Wilson intervals for individual frequencies, not simultaneous intervals.

Alternative A54.14 %; CI [53.04 %, 55.23 %]
Exact logit: 53.14 % · simulated choices: 4331
Alternative B28.06 %; CI [27.09 %, 29.06 %]
Exact logit: 29.17 % · simulated choices: 2245
Alternative C17.80 %; CI [16.98 %, 18.65 %]
Exact logit: 17.69 % · simulated choices: 1424
0 %100 %

For iid Gumbel location 0 and scale s, P(j)=exp(Vⱼ/s)/Σₖexp(Vₖ/s). Simulation uses ε=−s log(−log U), with independent uniform U. The common utility level is irrelevant: only differences relative to scale matter.

With iid zero-mean normal noise, σ=πs/√6 matches Gumbel marginal variance π²s²/6. Bars then estimate multinomial probit probabilities; marks remain the logit reference, not exact probabilities for the normal model. Matching variances does not match distributions or choice probabilities.

The simulation assumes disturbances independent across alternatives and decision makers with the same scale for each alternative. Changing seed changes Monte Carlo error; an individual interval can miss its probability in a particular sample.

Noise distribution
0.8
0.2
-0.3
1.00
8000
1
Gumbel scale s1.00
Equivalent normal standard deviation1.283
Choices8000
Compare simulated frequencies with logit-model probabilities.

Directly comparing logit and probit coefficients ignores their different scale normalizations. A nonlinear coefficient is also generally not the change in probability.

To derive binary probit, write U1−U0=x⊤θ+ηU_1-U_0=x^\top\theta+\eta with η∼N(0,τ2)\eta\sim N(0,\tau^2). Then P(U1>U0∣x)=Φ(x⊤θ/τ)P(U_1>U_0\mid x)=\Phi(x^\top\theta/\tau). Only β=θ/τ\beta=\theta/\tau is identified from choices: multiplying θ\theta and τ\tau simultaneously by a positive constant leaves probability unchanged. In logit, the logistic-difference scale plays the same role.

Marginal effects and uncertainty

In binary logit, pi=Λ(xi⊤β)p_i=\Lambda(x_i^\top\beta) and, for a continuous regressor xjx_j without additional transformations,

∂pi∂xij=βjpi(1−pi),AMEj=1n∑iβjpi(1−pi).\frac{\partial p_i}{\partial x_{ij}}=\beta_jp_i(1-p_i),\qquad AME_j=\frac1n\sum_i\beta_jp_i(1-p_i).

The average marginal effect averages individual effects. The effect at the mean evaluates the derivative at xˉ\bar x; generally p(xˉ)≠pˉp(\bar x)\ne\bar p and it does not equal the AME. For binary indicators it may be more interpretable to compare predictions changing from zero to one while holding other variables fixed.

The delta method propagates estimated covariance of β^\hat\beta. If h(β)h(\beta) is the AME, Var⁡^[h(β^)]=∇h⊤Var⁡^(β^)∇h\widehat{\operatorname{Var}}[h(\hat\beta)]=\nabla h^\top\widehat{\operatorname{Var}}(\hat\beta)\nabla h. For a fixed continuous design, the gradient is

∇h=1n∑i[ejpi(1−pi)+βjpi(1−pi)(1−2pi)xi].\nabla h= \frac1n\sum_i\left[e_jp_i(1-p_i) +\beta_jp_i(1-p_i)(1-2p_i)x_i\right].

The covariance matrix must match sampling design and observation dependence. This formula treats rows xix_i as given; other uncertainty sources can require a different estimate.

Conditional logit and substitution

In conditional logit, Vij=αj+xij⊤βV_{ij}=\alpha_j+x_{ij}^\top\beta can include alternative-varying attributes such as price or time. A reference alternative constant must be fixed. A characteristic identical across a person’s alternatives cancels with a common coefficient; it can be identified through suitable alternative interactions. McFadden’s formulation estimates parameters by maximizing the sum of log probabilities of chosen alternatives.

With linear utility and nonzero cost coefficient, βtiempo/βcoste\beta_{\mathrm{tiempo}}/\beta_{\mathrm{coste}} is the cost change compensating one unit of time saved: it follows by imposing ΔU=βtiempo(−1)+βcosteΔcoste=0\Delta U=\beta_{\mathrm{tiempo}}(-1)+\beta_{\mathrm{coste}}\Delta\mathrm{coste}=0. If both coefficients are negative, that marginal willingness to pay is positive. It is a parameter ratio with its own uncertainty, not necessarily a causal valuation.

Logit’s independence of irrelevant alternatives implies Pij/Pik=exp⁡[(Vij−Vik)/s]P_{ij}/P_{ik}=\exp[(V_{ij}-V_{ik})/s] regardless of other available alternatives. Adding a duplicate bus can make this restriction distribute substitution implausibly.

InteractiveThe red bus and the blue bus

Car and red bus always exist. Blue, if added, has the same observable utility as red. Bars are calculated probabilities, not shares from real data.

Simple logitCar 33.3 % · Red 33.3 % · Blue 33.3 %Nested logitCar 44.8 % · Red 27.6 % · Blue 27.6 %
  • Car
  • Red bus
  • Blue bus

Set Vcar=0 and Vred=Vblue=Δ. In simple logit each weight is exp(V); the ratio of car and red probabilities does not change when blue appears. In nested logit both buses share a nest with dissimilarity λ: nest weight is [Σⱼ exp(Vⱼ/λ)]^λ and within it choices are proportional to exp(Vⱼ/λ). Car forms its own nest.

With λ=1 nested logit matches simple logit. Reducing λ makes the new alternative take relatively more share from the similar bus, but it may also take share from car; only as λ→0 does the outside share remain unchanged in this exact-duplicate example. Standard parameterization requires 0<λ≤1.

0.30
0.0
Car before adding blue50.0 %
Car under simple logit33.3 %
Car under nested logit44.8 %
Car / red ratio under logit1.000
Add a duplicate and compare substitution under simple and nested logit.

Check shares and the limiting case with the figure’s explicit model:

[ ]Red and blue bus sharesBrowser
import numpy as np

def shares(delta, lam, blue):
    n=2 if blue else 1
    v=np.exp(delta)
    simple_car=1/(1+n*v)
    nested_car=1/(1+n**lam*v)
    return np.array([simple_car,(1-simple_car)/n,(1-simple_car)/n if blue else 0]), \
           np.array([nested_car,(1-nested_car)/n,(1-nested_car)/n if blue else 0])

for lam in (.3,1.):
    for blue in (False,True):
        simple,nested=shares(0,lam,blue)
        assert np.isclose(simple.sum(),1) and np.isclose(nested.sum(),1)
        if lam==1: assert np.allclose(simple,nested)
        print('lambda, azul, logit y anidado:',lam,blue,simple,nested)
print('Con λ tendiendo a cero, cuota externa de coche con duplicados:',shares(0,1e-9,True)[1][0])

Nested logit permits unobserved utility correlation within a nest. For dissimilarity 0<λ≤10<\lambda\le1, a nest’s weight is [∑j∈mexp⁡(Vj/λ)]λ[\sum_{j\in m}\exp(V_j/\lambda)]^\lambda with upper scale normalized to one; within the nest choice is softmax with scale λ\lambda. With λ=1\lambda=1 simple logit is recovered. Duplicating an alternative can also reduce other nests’ shares; only in particular limiting cases does all substitution come from the similar option. Train’s chapter details the structure and restrictions.

Mixed logit integrates logit probabilities over a distribution of random coefficients. Conditional on those coefficients the logit form remains, but the mixture generally does not satisfy IIA. Simulated likelihood approximates the integral with draws: chosen distribution, Monte Carlo precision and draw design matter.

Softmax regression shares probability normalization; alternative-specific attributes determine how utility changes when an option changes here. The Bradley-Terry model uses binary logit to compare utilities. Inverse reinforcement learning also infers preferences from choices, although trajectories and sequential decisions add assumptions absent from this static choice.

The Hausman-McFadden test compares estimates with and without an alternative under its assumptions. The covariance difference can be non-positive-definite in finite samples; an invalid comparison or failure to reject does not prove IIA. Availability and compared samples must be defined before estimation.

Censoring, truncation and Tobit

Under censoring, whether an outcome exceeds a limit is observed although some exact values are hidden. Under truncation only observations within a region appear and the rest never enter the sample. Under selection, covariates and decision may be observed for everyone but the outcome only for those selected. These are different mechanisms with noninterchangeable likelihoods.

Tobit censored below at zero assumes Y=max⁡(0,Y∗)Y=\max(0,Y^*), Y∗=μ+ϵY^*=\mu+\epsilon, μ=x⊤β\mu=x^\top\beta and ϵ∼N(0,σ2)\epsilon\sim N(0,\sigma^2) independent of xx. With z=μ/σz=\mu/\sigma,

E[Y∣x]=Φ(z)μ+σϕ(z),∂E[Y∣x]∂xj=βjΦ(z)E[Y\mid x]=\Phi(z)\mu+\sigma\phi(z),\qquad \frac{\partial E[Y\mid x]}{\partial x_j}=\beta_j\Phi(z)

if σ\sigma is constant. The total effect can be decomposed into change in probability of exceeding the limit and change in the mean among uncensored observations. This McDonald-Moffitt decomposition does not turn every zero into censoring: a real zero may result from another decision.

Indeed, E[Y∣x]=P(Y>0∣x)E[Y∣Y>0,x]E[Y\mid x]=P(Y>0\mid x)E[Y\mid Y>0,x], where P(Y>0∣x)=Φ(z)P(Y>0\mid x)=\Phi(z) and E[Y∣Y>0,x]=μ+σϕ(z)/Φ(z)E[Y\mid Y>0,x]=\mu+\sigma\phi(z)/\Phi(z). The product rule divides βjΦ(z)\beta_j\Phi(z) between the participation margin and change in the positive conditional mean. This decomposition depends on Tobit specification.

Selection and the inverse Mills ratio

In the Heckman selection model, Y=x⊤β+uY=x^\top\beta+u is observed only if s=1{z⊤γ+v>0}s=1\{z^\top\gamma+v>0\}. Suppose (u,v)(u,v) are jointly normal, independent of covariates, with zero means, variances σ2\sigma^2 and one and correlation ρ\rho. For a=z⊤γa=z^\top\gamma,

E[Y∣x,z,s=1]=x⊤β+ρσλ(a),λ(a)=ϕ(a)Φ(a).E[Y\mid x,z,s=1]=x^\top\beta+\rho\sigma\lambda(a), \qquad\lambda(a)=\frac{\phi(a)}{\Phi(a)}.

The ratio appears because E[v∣v>−a]=ϕ(a)/Φ(a)E[v\mid v>-a]=\phi(a)/\Phi(a) and E[u∣v]=ρσvE[u\mid v]=\rho\sigma v. If ρ≠0\rho\ne0, regression on observed cases omits a term depending on selection probability. Two-step estimation first fits probit of ss on zz in the full sample and adds λ^\hat\lambda to the observed-outcome regression. Ordinary standard errors of that second regression do not automatically account for the first stage: use an appropriate correction or bootstrap repeating both stages.

A variable excluded from the outcome but relevant to selection provides useful variation, provided exclusion is credible. Without it, Mills nonlinearity can identify under normality and functional form, but identification may be fragile; this does not make the specification an empirical truth. Heckman develops selection as an omitted-variable problem.

InteractiveThe cloud we see only in part

Each point is a person in a simulated population of 1000. Nonparticipants’ wages are faded only because the simulation reveals them; in real data they are unobserved. Lines show the structural mean, OLS fit among participants and structural part of the Heckman fit.

  • Participate
  • Do not participate, simulation only
  • Structural mean
  • OLS on selected
  • Heckman, structural mean

Model and exclusion: X, Z, v and η are independent standard normals. Offered wage is Y=1+1.1X+u, with u=ρv+√(1−ρ²)η. Y is observed when −0.2+0.9X+1.2Z+v>0. Z affects participation but not Y directly and is independent of errors. This also equals accepting an offer exceeding threshold R=1.2+0.2X−1.2Z+u−v. Seed is 270903; changing ρ changes wages, not decisions.

First stage: participation probit on a constant, X and Z for the whole sample. For each participant calculate λ=φ(estimated index)/Φ(estimated index); the second stage regresses observed wage on a constant, X and λ. The corrected line omits λ to represent the structural mean, not the selected sample’s prediction. Probit estimates coefficient 1.282 for Z.

This is one sample and no correction is guaranteed to approach truth in every replicate. The method relies on joint normal specification and credible exclusion; zero correlation does not rule out all selection mechanisms. Standard errors are not shown: ordinary second-stage errors ignore that λ was estimated and require correction or full resampling.

0.80
Participate44.9 %
True slope1.100
OLS on participants0.966
Two-step Heckman1.118
Mills coefficient0.811
Change correlation and compare the selected sample with the simulated population.

Maximum likelihood jointly models selection and outcome. For a selected observation, with e=(y−x⊤β)/σe=(y-x^\top\beta)/\sigma, its contribution is

1σϕ(e)Φ(z⊤γ+ρe1−ρ2);\frac1\sigma\phi(e) \Phi\left(\frac{z^\top\gamma+\rho e}{\sqrt{1-\rho^2}}\right);

for someone not selected it is Φ(−z⊤γ)\Phi(-z^\top\gamma). The formula requires joint normality and ∣ρ∣<1|\rho|<1; transforming parameters and using stable logarithms helps optimization. No selection method automatically recovers the population if model or exclusion fails.

Lab: transport-mode choice

Use the statsmodels modechoice dataset: four alternatives per person and mode-specific attributes. The sample was selected by chosen mode; its shares, coefficients and tests describe this sample and do not automatically estimate population shares. The source describes non-work travel in Australia in 1987. Estimating population preferences under this design requires accounting for sampling.

[ ]Conditional logit from scratch and with statsmodelsBrowser
"""Logit condicional en datos modechoice; muestra seleccionada por alternativa.

Los atributos varían entre alternativas. Una constante de alternativa común
se fija a cero para identificar las otras. Los costes se escalan por 100.
"""
import numpy as np
import statsmodels.api as sm
from scipy.optimize import minimize
from scipy.special import logsumexp
from statsmodels.discrete.conditional_models import ConditionalLogit

df = sm.datasets.modechoice.load_pandas().data.sort_values(['individual','mode'])
counts = df.groupby('individual')['choice'].agg(['size','sum'])
if not (counts['size'].eq(4).all() and counts['sum'].eq(1).all()):
    raise ValueError('Cada individuo debe tener cuatro modos y una elección')
group = df['individual'].to_numpy()
mode = df['mode'].to_numpy()
# Coche es la referencia; no hay intercepto común.
design = np.column_stack([(mode == j).astype(float) for j in (1,2,3)] +
                         [df['invt'].to_numpy()/100,
                          df['invc'].to_numpy()/100,
                          df['ttme'].to_numpy()/100])
X = design.reshape(-1,4,6)
choices = df['choice'].to_numpy().reshape(-1,4)
if np.linalg.matrix_rank((X-X.mean(axis=1,keepdims=True)).reshape(-1,6)) < 6:
    raise ValueError('El diseño residualizado por individuo no tiene rango completo')


def choice_stats(beta, X, Y):
    """Log-verosimilitud, gradiente y Hessiano analíticos."""
    utility = X@beta
    logp = utility-logsumexp(utility,axis=1,keepdims=True)
    p = np.exp(logp)
    loss = -float(np.sum(Y*logp))
    grad = np.einsum('ijk,ij->k',X,p-Y)
    mean_x = np.einsum('ij,ijk->ik',p,X)
    centered = X-mean_x[:,None,:]
    H = np.einsum('ij,ijk,ijl->kl',p,centered,centered)
    return loss, grad, H, p


def estimate_choice(X, Y, start=None):
    if start is None: start = np.zeros(X.shape[2])
    def objective(beta):
        loss,grad,_,_ = choice_stats(beta,X,Y)
        return loss,grad
    result = minimize(objective,start,jac=True,method='BFGS',options={'gtol':1e-8,'maxiter':400})
    if np.linalg.norm(result.jac,ord=np.inf)>1e-5:
        raise RuntimeError('No se alcanzó un punto estacionario')
    loss,grad,H,p = choice_stats(result.x,X,Y)
    if np.linalg.eigvalsh(H).min() <= 0:
        raise RuntimeError('Información sin rango; revisa las normalizaciones')
    return result.x, np.linalg.inv(H), loss, p


beta, cov, loss, probs = estimate_choice(X,choices)
reference = ConditionalLogit(df['choice'].to_numpy(),design,groups=group)
# ConditionalLogit.fit en statsmodels 0.14.6 no reenvía gtol a su optimizador.
# Iniciar en el óptimo propio permite contrastar función, score y Hessiano.
ref = reference.fit(start_params=beta,disp=False,maxiter=400)
print('Diferencia máxima de coeficientes y covarianzas frente a statsmodels:',
      np.max(np.abs(beta-ref.params)),np.max(np.abs(cov-ref.cov_params())))
assert abs(reference.loglike(beta)+loss) < 1e-7
assert np.max(np.abs(reference.score(beta))) < 1e-5
assert np.allclose(beta,ref.params,atol=2e-4,rtol=2e-4)
assert np.allclose(cov,ref.cov_params(),atol=2e-4,rtol=2e-4)
print('Individuos, filas, alternativas:',len(X),len(df),X.shape[1])
print('Logit propio:',beta,'EE:',np.sqrt(np.diag(cov)))
print('Statsmodels:',ref.params,'log-verosimilitud:',-loss)
print('Conteos elegidos en muestra por modo:',choices.sum(axis=0))
print('Cuotas predichas en esta muestra:',probs.mean(axis=0))
print('Muestra elegida según modo: las cuotas no son cuotas poblacionales.')

Cost and time variables are divided by 100 during estimation. The next calculation returns probability changes per extra dollar of own cost, compares average effect with effect at the mean vector and propagates covariance via centered differences. Elasticity first averages individual elasticities; it is not elasticity of the aggregate share.

[ ]Marginal effects and elasticitiesBrowser
"""Efectos medios y elasticidades; requiere la celda modechoice_logit."""
import numpy as np


def effects_cost(parameters):
    _,_,_,p = choice_stats(parameters,X,choices)
    # X[:,:,4] = coste / 100. Efectos por un dólar adicional del modo j.
    own = parameters[4]/100*p*(1-p)
    return own.mean(axis=0)


def effects_at_mean(parameters):
    representative = X.mean(axis=0,keepdims=True)
    _,_,_,p = choice_stats(parameters,representative,choices[:1])
    return (parameters[4]/100*p*(1-p))[0]


ame = effects_cost(beta)
mem = effects_at_mean(beta)
gradient = np.empty((4,len(beta)))
gradient_mem = np.empty((4,len(beta)))
for k in range(len(beta)):
    step = 1e-5*max(1.,abs(beta[k]))
    displacement = np.zeros(len(beta)); displacement[k] = step
    gradient[:,k] = (effects_cost(beta+displacement)-effects_cost(beta-displacement))/(2*step)
    gradient_mem[:,k] = (effects_at_mean(beta+displacement)-effects_at_mean(beta-displacement))/(2*step)
se = np.sqrt(np.diag(gradient@[email protected]))
se_mem = np.sqrt(np.diag(gradient_mem@cov@gradient_mem.T))
# Media de elasticidades individuales, no elasticidad de la cuota media.
elasticity = np.mean((beta[4]/100)*df['invc'].to_numpy().reshape(-1,4)*(1-probs),axis=0)

# Comprobación independiente: perturbar solo el coste de cada alternativa.
for j in range(4):
    delta = 1e-3
    xp, xm = X.copy(), X.copy()
    xp[:,j,4] += delta/100
    xm[:,j,4] -= delta/100
    pp = choice_stats(beta,xp,choices)[3][:,j]
    pm = choice_stats(beta,xm,choices)[3][:,j]
    assert np.isclose(np.mean((pp-pm)/(2*delta)),ame[j],atol=1e-8)
    xp_mean, xm_mean = X.mean(axis=0,keepdims=True), X.mean(axis=0,keepdims=True)
    xp_mean[:,j,4] += delta/100
    xm_mean[:,j,4] -= delta/100
    p_plus = choice_stats(beta,xp_mean,choices[:1])[3][0,j]
    p_minus = choice_stats(beta,xm_mean,choices[:1])[3][0,j]
    assert np.isclose((p_plus-p_minus)/(2*delta),mem[j],atol=1e-8)
print('AME del coste propio por dólar, por modo:',ame)
print('EE por método delta:',se)
print('Efecto en vector medio de atributos por alternativa:',mem)
print('EE del efecto en la media por método delta:',se_mem)
print('Media de elasticidades individuales del coste:',elasticity)
print('Cambios de un dólar, resto de atributos fijos; asociación bajo el modelo, no efecto causal.')

To compare scales, also fit binary logit and probit and multinomial logit to individual characteristics. These descriptive models answer different questions from the preceding conditional specification.

[ ]Discrete models with statsmodelsBrowser
"""Logit, probit y MNLogit descriptivos; continúa el laboratorio modechoice."""
import numpy as np
import statsmodels.api as sm

chosen = df[df['choice'] == 1].sort_values('individual')
outcome = chosen['mode'].to_numpy(dtype=int)
W = np.column_stack((np.ones(len(chosen)),chosen['hinc'].to_numpy()/10,
                     chosen['psize'].to_numpy()))
air = (outcome == 1).astype(int)
binary_logit = sm.Logit(air,W).fit(disp=False)
binary_probit = sm.Probit(air,W).fit(disp=False)
multinomial = sm.MNLogit(outcome,W).fit(disp=False,maxiter=200)
if not all(model.mle_retvals['converged'] for model in (binary_logit,binary_probit,multinomial)):
    raise RuntimeError('Algún ajuste no converge')
print('Logit binario: coeficientes y AME:',binary_logit.params,binary_logit.get_margeff().margeff)
print('Probit binario: coeficientes y AME:',binary_probit.params,binary_probit.get_margeff().margeff)
print('MNLogit: parámetros con una categoría base:',multinomial.params)
print('Escalas de utilidad logit y probit distintas; AME, no coeficientes, se comparan.')
print('Las cuotas y modelos corresponden a la muestra seleccionada por modo, no a la población.')

The next diagnostic removes bus and those who chose it. The classical covariance-matrix difference must be appropriate for the Hausman-McFadden test; if indefinite, it is not interpreted as a chi-square distance. The paired bootstrap resamples entire individuals and provides an exploratory comparison, but does not repair choice-based sampling or make misspecification valid.

[ ]IIA and first bootstrap blockBrowser
"""Diagnóstico al retirar autobús, continuación del logit condicional.

Conserva solo individuos cuya elección sobrevive y retira la alternativa.
El bootstrap remuestrea individuos completos en ambas estimaciones.
"""
import numpy as np
from scipy.stats import chi2

other_modes = [0,1,3]
other_params = [0,1,3,4,5]
survives = choices[:,2] == 0
Xr = X[survives][:,other_modes,:][:,:,other_params]
Yr = choices[survives][:,other_modes]
beta_r, cov_r, _, _ = estimate_choice(Xr,Yr,beta[other_params])
delta = beta_r-beta[other_params]
hausman_diff = cov_r-cov[np.ix_(other_params,other_params)]
print('Individuos con elección restante:',len(Xr))
print('Coeficientes sin autobús:',beta_r)
print('Diferencia con el modelo completo:',delta)
eigenvalues = np.linalg.eigvalsh((hausman_diff+hausman_diff.T)/2)
print('Autovalores de V_reducida − V_completa:',eigenvalues)
if eigenvalues.min() <= 0:
    print('La resta de covarianzas es indefinida: el Hausman clásico no se calibra aquí.')
else:
    stat = float([email protected](hausman_diff,delta))
    print('Hausman clásico y p chi2:',stat,chi2.sf(stat,len(delta)))

# Bootstrap pareado de personas, sin fingir que arregla el muestreo por elección.
rng_boot = np.random.default_rng(270903)
boot, failures = [], 0
def bootstrap_batch(count):
    global failures
    for _ in range(count):
        draw = rng_boot.integers(0,len(X),size=len(X))
        try:
            full,_,_,_ = estimate_choice(X[draw],choices[draw],beta)
            valid = draw[choices[draw,2] == 0]
            reduced,_,_,_ = estimate_choice(X[valid][:,other_modes,:][:,:,other_params],
                                             choices[valid][:,other_modes],beta_r)
            boot.append(reduced-full[other_params])
        except (RuntimeError, np.linalg.LinAlgError):
            failures += 1

bootstrap_batch(40)
print('Bootstrap: completado primer bloque de 40.')
[ ]Second bootstrap blockBrowser
"""Segundo bloque del bootstrap pareado; ejecuta después de modechoice_iia."""
bootstrap_batch(40)
print('Bootstrap: completado segundo bloque de 40; válidas:',len(boot))
[ ]Third block and interpretationBrowser
"""Tercer bloque y diagnóstico; ejecuta después de modechoice_iia_more."""
bootstrap_batch(40)
boot_arr = np.asarray(boot)
print('Bootstrap pareado: réplicas válidas y fallidas:',len(boot),failures)
if len(boot) > len(delta):
    V_boot = np.cov(boot_arr,rowvar=False,ddof=1)
    if np.linalg.matrix_rank(V_boot) == len(delta):
        stat_boot = float([email protected](V_boot,delta))
        print('Wald con covarianza bootstrap y referencia asintótica chi2(5):',stat_boot,chi2.sf(stat_boot,len(delta)))
    else:
        print('Covarianza bootstrap sin rango; no se calcula el Wald.')
print('Diagnóstico exploratorio: la comparación requiere un muestreo y una especificación compatibles con la nula.')
print('No certifica IIA ni corrige el muestreo por elección; 120 réplicas dejan incertidumbre Monte Carlo.')

Lab: Heckman selection

Generate a population where offered wages are known even for nonparticipants. The access variable affects selection and is excluded from the wage equation by construction; with real data that exclusion requires justification.

[ ]Simulated population and selectionBrowser
import numpy as np
from scipy.optimize import minimize
from scipy.special import log_ndtr, ndtr

# CELDA 1: modelo y datos completamente simulados.
rng = np.random.default_rng(921)
n = 1200
x = rng.normal(size=n)
acceso = rng.normal(size=n)  # afecta a la participación, no al resultado
X = np.column_stack((np.ones(n), x))
Z = np.column_stack((X, acceso))
beta_verdadero = np.array([1.0, 1.5])
gamma_verdadero = np.array([-0.25, 0.35, 1.0])
sigma_verdadera, rho_verdadero = 1.2, 0.65
v = rng.normal(size=n)
e = rng.normal(size=n)
u = sigma_verdadera * (rho_verdadero * v + np.sqrt(1-rho_verdadero**2) * e)
d = (Z @ gamma_verdadero + v > 0).astype(float)
y = X @ beta_verdadero + u
y_observado = np.where(d == 1, y, np.nan)
print('seleccionados:', int(d.sum()), 'de', n)
print('parámetros verdaderos:', beta_verdadero, sigma_verdadera, rho_verdadero)

Estimate probit and then the outcome equation with Mills. The stacked sandwich includes first-stage estimation; the displayed ordinary error is a comparator that does not.

[ ]Two-step HeckmanBrowser
# CELDA 2: dos etapas y sandwich de ecuaciones apiladas.
def logpdf_normal(t):
    return -0.5*t*t - 0.5*np.log(2*np.pi)

def mills(t):
    # φ(t)/Φ(t), estable también para t muy negativo.
    return np.exp(logpdf_normal(t) - log_ndtr(t))

def probit_fit(Z, d):
    def f(g):
        t = Z @ g
        return -np.sum(d*log_ndtr(t) + (1-d)*log_ndtr(-t))
    def grad(g):
        t = Z @ g
        return -(Z.T @ (d*mills(t) - (1-d)*mills(-t)))
    result = minimize(f, np.zeros(Z.shape[1]), jac=grad, method='BFGS',
                      options={'gtol': 1e-7, 'maxiter': 300})
    if not result.success and np.linalg.norm(grad(result.x), ord=np.inf) > 1e-5:
        raise RuntimeError(result.message)
    return result.x

def heckman_dos_etapas(X, Z, d, y):
    sel = d == 1
    gamma = probit_fit(Z, d)
    t = Z @ gamma
    lam = mills(t)
    W = np.column_stack((X, lam))
    theta = np.linalg.lstsq(W[sel], y[sel], rcond=None)[0]
    resid = y[sel] - W[sel] @ theta
    # Scores individuales del probit y momentos individuales de segunda etapa.
    score1 = Z * (d*mills(t) - (1-d)*mills(-t))[:, None]
    score2 = np.zeros_like(W)
    score2[sel] = W[sel] * resid[:, None]
    scores = np.column_stack((score1, score2))
    # Jacobiano analítico de los momentos con respecto a (gamma, theta).
    k, p = Z.shape[1], W.shape[1]
    jac = np.zeros((k+p, k+p))
    lm = mills(t)
    lp = -lm*(t+lm)
    lm_neg = mills(-t)
    score_deriv = d*lp - (1-d)*lm_neg*(lm_neg-t)
    jac[:k, :k] = Z.T @ (score_deriv[:, None]*Z)
    jac[k:, k:] = -(W[sel].T @ W[sel])
    # d[W r]/dgamma = e_lambda lambda' z' r - W theta_lambda lambda' z'.
    q = np.zeros(p)
    q[-1] = 1.0
    aux = (resid[:, None]*q[None, :] - theta[-1]*W[sel]) * lp[sel, None]
    jac[k:, :k] = aux.T @ Z[sel]
    inv = np.linalg.inv(jac)
    cov = inv @ (scores.T @ scores) @ inv.T
    # Comparador incorrecto: trata la función generada como variable conocida.
    naive = np.sqrt(np.diag(np.linalg.inv(W[sel].T @ W[sel]) *
                            (resid @ resid)/(int(d.sum())-p)))
    return gamma, theta, np.sqrt(np.maximum(np.diag(cov)[k:], 0)), naive

g, th, se, se_naive = heckman_dos_etapas(X, Z, d, y_observado)
ols = np.linalg.lstsq(X[d == 1], y_observado[d == 1], rcond=None)[0]
print('MCO seleccionados:', np.round(ols, 4))
print('Heckman dos etapas, beta y rho*sigma:', np.round(th, 4))
print('errores sandwich apilado:', np.round(se, 4))
print('errores MCO ingenuos:', np.round(se_naive, 4))
print('probit gamma:', np.round(g, 4))
print('Mills(-20), valor finito:', round(float(mills(-20.0)), 6))

Maximum likelihood imposes joint normality. Observed information is approximated by centered differences and transformations keep scale and correlation determinant positive.

[ ]Maximum-likelihood HeckmanBrowser
# CELDA 3: máxima verosimilitud bajo normalidad conjunta.
def heckman_ml(X, Z, d, y):
    sel = d == 1
    gamma, theta, _, _ = heckman_dos_etapas(X, Z, d, y)
    sigma0 = np.std(y[sel] - X[sel] @ theta[:-1])
    rho0 = np.clip(theta[-1]/sigma0, -0.8, 0.8)
    p, k = X.shape[1], Z.shape[1]
    initial = np.r_[gamma, theta[:-1], np.log(sigma0), np.arctanh(rho0)]
    def objective(a):
        gamma, beta = a[:k], a[k:k+p]
        sigma, rho = np.exp(a[-2]), np.tanh(a[-1])
        t = Z @ gamma
        eps = (y[sel] - X[sel] @ beta) / sigma
        cond = (t[sel] + rho*eps) / np.sqrt(1-rho*rho)
        return -(np.sum(log_ndtr(-t[~sel])) +
                 np.sum(logpdf_normal(eps)-np.log(sigma)+log_ndtr(cond)))
    result = minimize(objective, initial, method='BFGS', options={'gtol': 1e-5, 'maxiter': 300})
    if not result.success and np.linalg.norm(result.jac, ord=np.inf) > 5e-4:
        raise RuntimeError(result.message)
    a = result.x
    # Información observada por diferencias centrales del logaritmo de verosimilitud.
    h = 1e-4
    m = len(a)
    H = np.empty((m, m))
    f0 = objective(a)
    steps = np.eye(m)*h
    for i in range(m):
        H[i, i] = (objective(a+steps[i])-2*f0+objective(a-steps[i]))/h**2
        for j in range(i):
            H[i, j] = H[j, i] = (objective(a+steps[i]+steps[j]) -
                                  objective(a+steps[i]-steps[j]) -
                                  objective(a-steps[i]+steps[j]) +
                                  objective(a-steps[i]-steps[j]))/(4*h*h)
    if np.min(np.linalg.eigvalsh(H)) <= 0:
        raise RuntimeError('La información observada no es definida positiva.')
    se_trans = np.sqrt(np.diag(np.linalg.inv(H)))
    # Método delta para pasar de log(sigma) y atanh(rho) a sigma y rho.
    se_natural = np.r_[se_trans[:k+p], np.exp(a[-2])*se_trans[-2],
                       (1-np.tanh(a[-1])**2)*se_trans[-1]]
    return a[:k], a[k:k+p], np.exp(a[-2]), np.tanh(a[-1]), result.fun, se_natural

g_ml, beta_ml, sigma_ml, rho_ml, nll, se_ml = heckman_ml(X, Z, d, y_observado)
print('MV beta:', np.round(beta_ml, 4), 'sigma:', round(sigma_ml, 4), 'rho:', round(rho_ml, 4))
print('MV gamma:', np.round(g_ml, 4), 'menos log-verosimilitud:', round(nll, 4))
print('MV errores de información observada (gamma, beta, sigma, rho):', np.round(se_ml, 4))

Omitting a variable that actually enters selection changes the model; it does not prove functional identification is sufficient.

[ ]Omit a selection variableBrowser
# CELDA 4: el mismo conjunto sin la variable excluida.
g_sin, th_sin, se_sin, _ = heckman_dos_etapas(X, X, d, y_observado)
print('sin exclusión, beta y rho*sigma:', np.round(th_sin, 4))
print('sin exclusión, errores sandwich:', np.round(se_sin, 4))
print('con exclusión, error sandwich de beta_x:', round(se[1], 4))
print('sin exclusión, error sandwich de beta_x:', round(se_sin[1], 4))
print('La última especificación omite una variable real de selección; no es una comparación que pruebe identificación funcional.')

Now generate another selection where that excluded variable does not exist. Identification by curvature depends on assumptions and may be weak in a particular sample.

[ ]A world without a true exclusionBrowser
# CELDA 5: segundo mundo, ahora sí correctamente especificado sin exclusión.
d0 = (X @ gamma_verdadero[:2] + v > 0).astype(float)
y0 = np.where(d0 == 1, y, np.nan)
g0, th0, se0, _ = heckman_dos_etapas(X, X, d0, y0)
print('sin exclusión en el modelo generador, seleccionados:', int(d0.sum()))
print('beta y rho*sigma:', np.round(th0, 4))
print('errores sandwich:', np.round(se0, 4))
print('Con normalidad, la curvatura de Mills identifica formalmente; la precisión depende de la muestra y del rango del índice.')

Exercises

ProofFrom independent Gumbel to logit
Prove: Let Uj=Vj+ϵjU_j=V_j+\epsilon_j, with independent Gumbel disturbances of scale s>0s>0 and distribution F(e)=exp⁡[−exp⁡(−e/s)]F(e)=\exp[-\exp(-e/s)]. Derive the probability of choosing jj.
The proof will appear here as you work.

Step 1 of 3. Conditioning on alternative j's error, what integral expresses its victory?

ProofSelection introduces Mills
Prove: Suppose Y=x⊤β+uY=x^\top\beta+u, selection s=1{a+v>0}s=1\{a+v>0\} and jointly normal (u,v)(u,v) independent of covariates, with zero means, variances σ2\sigma^2 and one and correlation ρ\rho.
The proof will appear here as you work.

Step 1 of 3. What is the mean of v among selected observations?

NumericEffect at the mean
In binary logit a continuous regressor has coefficient 0.8 and probability evaluated at the mean covariate vector is 0.3. What is the marginal effect at that vector?
QuizAn instrument with a limit
A sensor retains all cases but reports zero when a normal latent concentration is negative and the exact value when positive. What mechanism and model fit these assumptions?
QuizAn incomplete register
A register includes only firms with revenue above a threshold. Lower-revenue firms do not appear and their covariates are unknown. What mechanism describes the register?
QuizWages only for workers
A survey observes everyone's education and participation, but wages only for workers. Heckman is proposed with an access variable excluded from wages. What must be defended?
QuizTop-coded income
A survey retains everyone but replaces income above a limit by that limit. What is observed?
QuizObserved or censored zero
A study records the exact number of purchases, including zero. What can you conclude solely from the presence of zeros?

The next cell checks the numerical calculation and shows why replacing probability at the mean with mean probability requires additional information:

[ ]Check the effect at the meanBrowser
import numpy as np
from scipy.special import expit

beta_x = 0.8
print('Efecto en la media con p(x media)=0,3:', beta_x*0.3*(1-0.3))
x = np.array([-3.0, 0.0, 1.0])
p = expit(beta_x*x)
print('Media de probabilidades, probabilidad en media, AME:',
      p.mean(), expit(beta_x*x.mean()), np.mean(beta_x*p*(1-p)))
CodeAverage marginal effects with uncertainty
Implement average_marginal_effects(model, X) for a fitted statsmodels.Logit result. Two-dimensional X has observations in rows and the same columns and order as the fit. Calculate average marginal effects of continuous variables as the mean of beta[j] p[i] (1 - p[i]), where p[i] = sigmoid(X[i] @ beta). Return two one-dimensional arrays, (effects, errors), one entry per X column except the constant, in original order. The constant index is model.model.data.const_idx; it may be None when there is no constant. Use the delta method: differentiate each average effect with respect to the full coefficient vector, including the constant, and combine its gradient with model.cov_params(). This covariance treats X rows as fixed and propagates only coefficient uncertainty; it does not include variation of the empirical covariate distribution. Treat variables as continuous even if they only take 0 and 1. Do not calculate discrete changes or interpret results as causal without additional assumptions. Raise ValueError for empty or non-two-dimensional X, nonfinite values or columns incompatible with model.params, as well as parameters or covariance with incompatible shape or nonfinite values. If there is a constant, check its index is a valid integer and its column constant and nonzero. Use numerically stable sigmoid and derivative evaluation to avoid overflow with large linear indices. The supplied covariance is assumed symmetric positive semidefinite.
import numpy as np


def average_marginal_effects(model, X):
  """Devuelve efectos marginales medios y sus errores delta."""
  pass
Shift+Enter to run

Test figures come from these reproducible fits and get_margeff; synthetic data are generated with a fixed seed:

[ ]Exercise references with statsmodelsBrowser
"""Genera los valores de referencia con statsmodels fuera de Pyodide."""
import json
import numpy as np
import statsmodels.api as sm

def generate(name, X, y):
    result = sm.Logit(y, X).fit(disp=False, maxiter=200)
    margins = result.get_margeff(at='overall', method='dydx', dummy=False, count=False)
    return dict(name=name, X=X.tolist(), params=result.params.tolist(),
                cov=result.cov_params().tolist(), effect=margins.margeff.tolist(),
                se=margins.margeff_se.tolist(), const_idx=result.model.data.const_idx)

rng = np.random.default_rng(930)
x = np.linspace(-2.5, 2.5, 72)
p = 1 / (1 + np.exp(-(-.2 + .9*x)))
y = rng.binomial(1, p)
one = generate('una_variable', np.column_stack((np.ones(len(x)), x)), y)

x1 = rng.normal(size=100)
x2 = rng.normal(size=100)
p = 1 / (1 + np.exp(-(.35 + .8*x1 - .6*x2)))
y = rng.binomial(1, p)
# Constante en última posición; no se debe confundir con un efecto marginal.
two = generate('dos_variables', np.column_stack((x1, x2, np.ones(len(x1)))), y)

for item in (one, two):
    print('Caso:', item['name'])
    print('Parámetros:', item['params'])
    print('Covarianza:', item['cov'])
    print('AME y errores por delta:', item['effect'], item['se'])