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 chooses the available alternative with highest . Component summarizes observed attributes and parameters; 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 , integrating the probability that exceeds all others gives
To see the integration, condition on , multiply its density by distribution functions and substitute . The remaining integral is exponential and yields the preceding ratio. In binary choice, the difference of two iid Gumbels is logistic; usual normalization yields logit. If the error difference is normal, probit results: after fixing its deviation. In multinomial choice, normal errors yield multinomial probit, generally without a softmax formula. Train develops the assumptions.
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 with . Then . Only is identified from choices: multiplying and 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, and, for a continuous regressor without additional transformations,
The average marginal effect averages individual effects. The effect at the mean evaluates the derivative at ; generally 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 . If is the AME, . For a fixed continuous design, the gradient is
The covariance matrix must match sampling design and observation dependence. This formula treats rows as given; other uncertainty sources can require a different estimate.
Conditional logit and substitution
In conditional logit, 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, is the cost change compensating one unit of time saved: it follows by imposing . 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 regardless of other available alternatives. Adding a duplicate bus can make this restriction distribute substitution implausibly.
Check shares and the limiting case with the figure’s explicit model:
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 , a nest’s weight is with upper scale normalized to one; within the nest choice is softmax with scale . With 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 , , and independent of . With ,
if 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, , where and . The product rule divides 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, is observed only if . Suppose are jointly normal, independent of covariates, with zero means, variances and one and correlation . For ,
The ratio appears because and . If , regression on observed cases omits a term depending on selection probability. Two-step estimation first fits probit of on in the full sample and adds 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.
Maximum likelihood jointly models selection and outcome. For a selected observation, with , its contribution is
for someone not selected it is . The formula requires joint normality and ; 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.
"""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.
"""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.
"""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.
"""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.')"""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))"""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.
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.
# 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.
# 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.
# 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.
# 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
Step 1 of 3. Conditioning on alternative j's error, what integral expresses its victory?
Step 1 of 3. What is the mean of v among selected observations?
The next cell checks the numerical calculation and shows why replacing probability at the mean with mean probability requires additional information:
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)))import numpy as np
def average_marginal_effects(model, X):
"""Devuelve efectos marginales medios y sus errores delta."""
passTest figures come from these reproducible fits and get_margeff; synthetic data are generated with a fixed seed:
"""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'])