经济学 · 第 5 册 · 本科三年级

University Economics — Year 3

本书暂未推出简体中文版。现有版本:English。

University Economics — Year 3 · 本科三年级

5Binary Outcomes and Maximum Likelihood

Many of the outcomes economists care about are yes or no. A person works or does not; a household buys a car or does not; a commuter takes the bus or drives. The regression methods of the earlier chapters can be applied to a variable that takes the values 0 and 1, and often that is the right thing to do. But a probability cannot exceed one, the effect of a variable on a probability cannot be the same at 2 % as at 98 %, and a choice among several options has a structure that a regression ignores. This chapter builds the models that respect those facts, the method that estimates them — maximum likelihood — and the model of choice among options that economists use to forecast demand for products that do not yet exist.

Share of men with any earnings in 1978 against their earnings in 1975, in thousands of dollars (15,992 men of a 1970s United States population survey, the comparison sample of the job-training study of ; dots are shares in bins, the first one the 1,748 men with no earnings in 1975). Lines: three models of the probability on 1975 earnings alone. Earnings above about $25\,000 are top-coded.
Share of men with any earnings in 1978 against their earnings in 1975, in thousands of dollars (15,992 men of a 1970s United States population survey, the comparison sample of the job-training study of Chapter 3; dots are shares in bins, the first one the 1,748 men with no earnings in 1975). Lines: three models of the probability on 1975 earnings alone. Earnings above about $25 00025\,000 are top-coded. Source: Dehejia and Wahba’s NSW files (survey comparison sample); our computation

Read the chart from the left. Of the men with no earnings in 1975, 44 % had some in 1978; of those who earned a few thousand dollars, 85–87 %; of those near the top, about 95 %. The straight line rises at the same rate everywhere and passes 1 at the top of the range. The logit and probit curves bend toward 1 and are hard to tell apart. And all three miss the first dot badly: they predict 66–70 % for men with no earnings, against an observed 44 %. Men with no earnings at all are not simply men with low earnings, and no choice of curve fixes a model that treats them as if they were (Exercise 5.5). The chapter’s tools are worth learning, but the chart’s first lesson is that the specification matters more than the curve.

You already know

The Year 2 volume estimated regressions by least squares, with heteroskedasticity-robust standard errors. Logistic regression as a tool for classifying is treated in the artificial-intelligence volumes; this chapter reads the same model as an economist does, for its marginal effects, its inference and the choice behaviour behind it.

Notation 5.1 (Symbols of this chapter)

yi∈{0,1}y_i \in \{0, 1\} is the outcome and xix_i the vector of regressors, with a constant; yi∗y_i^* is a latent variable. Λ(z)=1/(1+e−z)\Lambda(z) = 1/(1 + \eu^{-z}) is the logistic and Φ\Phi the standard normal distribution function; pip_i is a fitted probability. In the choice models, UijU_{ij} is the utility of option jj for person ii (a number, not a utility function of goods), VijV_{ij} its systematic part and ηij\eta_{ij} a taste shock. In demand, δj\delta_j is a product’s mean utility (not depreciation) and α\alpha the price coefficient (not a capital share).

5.1 The linear probability model

Definition 5.2 (Linear probability model)

The linear probability model is the regression of a binary outcome on regressors, yi=xi′β+uiy_i = x_i'\beta + u_i, estimated by OLS. Since E[yi∣xi]=Pr⁡(yi=1∣xi)\E[y_i \mid x_i] = \Pr(y_i = 1 \mid x_i), its coefficients are changes in the probability.

The model has real virtues. Its coefficients are read directly as effects on the probability; it is the regression of the earlier chapters, so instruments, fixed effects and differences in differences carry over unchanged; and as a linear approximation to the conditional probability it is often good where most of the data lie. Its errors are heteroskedastic by construction — Var⁡(ui∣xi)=pi(1−pi)\Var(u_i \mid x_i) = p_i(1 - p_i) — so robust standard errors are required. Its weakness is at the edges: fitted values can fall below 0 or above 1, and a constant slope is implausible for a probability near either.

5.2 Logit and probit

Definition 5.3 (Latent variable; probit model; logit model)

Suppose yi=1y_i = 1 if a latent variable yi∗=xi′β+ηiy_i^* = x_i'\beta + \eta_i is positive and yi=0y_i = 0 otherwise, with ηi\eta_i independent of xix_i and symmetric about zero with distribution function FF. Then Pr⁡(yi=1∣xi)=F(xi′β)\Pr(y_i = 1 \mid x_i) = F(x_i'\beta). The probit model takes F=ΦF = \Phi, the standard normal; the logit model takes F=ΛF = \Lambda, the logistic.

The latent variable is a device, and sometimes an interpretation: the gain from working, the net value of buying. Its scale is not identified — multiplying β\beta and the spread of η\eta by the same number changes nothing observed — so the variance of η\eta is fixed by convention: 1 for the probit, π2/3\pi^2/3 for the logit (here π\pi is the circle’s constant, not inflation). That is why logit coefficients are larger than probit coefficients on the same data — by a factor between 1.80 and 1.95 in Output 5.1 below — and why neither set is comparable with the linear model’s.

The latent-variable picture. The outcome is 1 when the shock _i exceeds -x_i'; the shaded area is F(x_i' ). A larger x_i' moves the threshold left and raises the probability.
The latent-variable picture. The outcome is 1 when the shock ηi\eta_i exceeds −xi′β-x_i'\beta; the shaded area is F(xi′β)F(x_i'\beta). A larger xi′βx_i'\beta moves the threshold left and raises the probability.

5.3 The likelihood and its maximum

Definition 5.4 (Likelihood function; log-likelihood; maximum likelihood estimator)

For independent observations with densities or probabilities f(yi∣xi;θ)f(y_i \mid x_i; \theta), the likelihood function is L(θ)=∏if(yi∣xi;θ)L(\theta) = \prod_i f(y_i \mid x_i; \theta), the probability of the observed data as a function of the parameters; the log-likelihood is ℓ(θ)=ln⁡L(θ)\ell(\theta) = \ln L(\theta); and the maximum likelihood estimator θ^\hat\theta maximises it.

For a binary model with pi=F(xi′β)p_i = F(x_i'\beta), each observation contributes pip_i if yi=1y_i = 1 and 1−pi1 - p_i if not:

ℓ(β)=∑i[ yiln⁡pi+(1−yi)ln⁡(1−pi)].(5.1)\ell(\beta) = \sum_i \bigl[\, y_i \ln p_i + (1 - y_i) \ln(1 - p_i) \bigr].\tag{5.1}

Proposition 5.5 (The logit log-likelihood is concave; its score equations)

For the logit model, the gradient (the score) and the Hessian of ℓ\ell are

∇ℓ(β)=∑i(yi−pi) xi,∇2ℓ(β)=−∑ipi(1−pi) xixi′.\nabla \ell(\beta) = \sum_i (y_i - p_i)\, x_i, \qquad \nabla^2 \ell(\beta) = -\sum_i p_i (1 - p_i)\, x_i x_i'.

The Hessian is negative semidefinite, so ℓ\ell is concave, and any solution of the score equations ∑i(yi−pi)xi=0\sum_i (y_i - p_i) x_i = 0 is a global maximum. If xix_i contains a constant, the fitted probabilities average to the observed share of ones; if it contains a dummy for a group, they do so within the group.

Proof. With zi=xi′βz_i = x_i'\beta and pi=Λ(zi)p_i = \Lambda(z_i), Λ′(z)=Λ(z)(1−Λ(z))\Lambda'(z) = \Lambda(z)(1 - \Lambda(z)), so ∂ln⁡pi/∂zi=1−pi\partial \ln p_i/\partial z_i = 1 - p_i and ∂ln⁡(1−pi)/∂zi=−pi\partial \ln(1 - p_i)/\partial z_i = -p_i. The derivative of observation ii’s term with respect to ziz_i is yi(1−pi)−(1−yi)pi=yi−piy_i(1 - p_i) - (1 - y_i)p_i = y_i - p_i; the chain rule gives the score. Differentiating again, ∂(yi−pi)/∂zi=−pi(1−pi)\partial (y_i - p_i)/\partial z_i = -p_i(1 - p_i), which gives the Hessian. For any vector vv, v′∇2ℓ v=−∑ipi(1−pi)(xi′v)2≤0v' \nabla^2\ell\, v = -\sum_i p_i(1 - p_i)(x_i'v)^2 \le 0. A concave function’s stationary points are global maxima. Finally, the score equation for the coefficient on a regressor that equals 1 in a group and 0 elsewhere reads ∑i∈group(yi−pi)=0\sum_{i \in \text{group}} (y_i - p_i) = 0. ∎

Proposition 5.6 (Properties of the maximum likelihood estimator)

If the model is correctly specified and regularity conditions hold, the maximum likelihood estimator is consistent and asymptotically normal, with variance estimated by the inverse of minus the Hessian at θ^\hat\theta (the inverse of the observed information).

Proof. Admitted at this level. ∎

The proof expands the score around the true parameter and applies the law of large numbers and the central limit theorem to its terms; it is in graduate texts on econometric theory.

There is no formula for the maximum, so it is found by iteration. Newton’s method replaces the log-likelihood near the current guess by its second-order Taylor expansion and jumps to that quadratic’s maximum: βk+1=βk−[∇2ℓ(βk)]−1∇ℓ(βk)\beta_{k+1} = \beta_k - [\nabla^2\ell(\beta_k)]^{-1} \nabla\ell(\beta_k). The chart shows the simplest case, a logit with only a constant bb on the opening chart’s data, where the maximum is the log of the odds of working, ln⁡(13,820/2,172)=1.8505\ln(13{,}820/2{,}172) = 1.8505.

The log-likelihood of a logit with only a constant b, on the 15,992 men of the opening chart, and Newton’s steps from b = 0.
The log-likelihood of a logit with only a constant bb, on the 15,992 men of the opening chart, and Newton’s steps from b=0b = 0. Source: Dehejia and Wahba’s NSW files (survey comparison sample); our computation

From b=0b = 0 (every probability one half) the first step lands at 1.46, the second at 1.80, the third at 1.850, and the fourth agrees with the maximum to four decimals. Listing 5.2 runs the same method on the five-parameter model of Listing 5.1.

"""Who had earnings in 1978? A linear probability model, a logit and a probit on the
survey sample of men from the NSW files; average marginal effects side by side."""
import numpy as np
import statsmodels.formula.api as smf
from econdata import nsw

d = nsw("cps_controls")
d["work"] = (d.re78 > 0).astype(int)
d["earn75"] = d.re75 / 1000                        # thousands of dollars
f = "work ~ earn75 + age + education + married"

lpm = smf.ols(f, d).fit(cov_type="HC1")
logit = smf.logit(f, d).fit(disp=0)
probit = smf.probit(f, d).fit(disp=0)
ame_l = logit.get_margeff().margeff
ame_p = probit.get_margeff().margeff

print(f"men {len(d)}, share with earnings in 1978 {d.work.mean():.3f}")
print("              LPM     logit   probit |  AME logit  AME probit")
for k, name in enumerate(["earn75", "age", "education", "married"]):
    print(f"{name:10s} {lpm.params[name]:7.4f} {logit.params[name]:8.4f}"
          f" {probit.params[name]:8.4f} | {ame_l[k]:9.4f} {ame_p[k]:10.4f}")
fitted = lpm.fittedvalues
print(f"LPM fitted values above 1: {np.mean(fitted > 1):.3f} of the sample,"
      f" largest {fitted.max():.3f}")
Listing 5.1. Three models of the same outcome, with average marginal effects. code/bachelor-3/05-binary-outcomes/listings/lpm_logit_probit.py
$ python lpm_logit_probit.py
men 15992, share with earnings in 1978 0.864
              LPM     logit   probit |  AME logit  AME probit
earn75      0.0160   0.1405   0.0722 |    0.0135     0.0131
age        -0.0067  -0.0517  -0.0283 |   -0.0050    -0.0051
education  -0.0118  -0.0754  -0.0420 |   -0.0073    -0.0076
married    -0.0525  -0.2981  -0.1659 |   -0.0287    -0.0301
LPM fitted values above 1: 0.157 of the sample, largest 1.193
Output 5.1. Coefficients; then average marginal effects of the logit and probit.
"""Maximum likelihood by hand: Newton--Raphson for the logit of the previous listing,
printing the log-likelihood at each step, then checking against statsmodels."""
import numpy as np
import statsmodels.formula.api as smf
from choicetools import logit_newton
from econdata import nsw

d = nsw("cps_controls")
d["work"] = (d.re78 > 0).astype(float)
d["earn75"] = d.re75 / 1000
X = np.column_stack([np.ones(len(d)), d[["earn75", "age", "education", "married"]]])

r = logit_newton(d.work.values, X)
for it, ll, b in r["history"]:
    print(f"step {it}: log-likelihood {ll:12.4f}   coefficient on earn75 {b[1]:.6f}")

check = smf.logit("work ~ earn75 + age + education + married", d).fit(disp=0)
print(f"statsmodels:       {check.llf:12.4f}   coefficient on earn75"
      f" {check.params['earn75']:.6f}")
print(f"standard error on earn75: by hand {r['se'][1]:.6f},"
      f" statsmodels {check.bse['earn75']:.6f}")
Listing 5.2. Newton–Raphson by hand, with the library function logit_newton. code/bachelor-3/05-binary-outcomes/listings/newton_logit.py
$ python newton_logit.py
step 0: log-likelihood  -11084.8097   coefficient on earn75 0.000000
step 1: log-likelihood   -5722.0545   coefficient on earn75 0.063927
step 2: log-likelihood   -5208.8965   coefficient on earn75 0.111530
step 3: log-likelihood   -5149.5424   coefficient on earn75 0.135446
step 4: log-likelihood   -5147.8443   coefficient on earn75 0.140320
step 5: log-likelihood   -5147.8422   coefficient on earn75 0.140498
step 6: log-likelihood   -5147.8422   coefficient on earn75 0.140498
step 7: log-likelihood   -5147.8422   coefficient on earn75 0.140498
statsmodels:         -5147.8422   coefficient on earn75 0.140498
standard error on earn75: by hand 0.003362, statsmodels 0.003362
Output 5.2. The log-likelihood climbs, then stops moving.

The log-likelihood rises from −11,084.8-11{,}084.8 to −5,147.84-5{,}147.84 in five steps; the last two change nothing that is printed, the quadratic convergence of Newton’s method. The hand-made estimates and standard errors agree with the library’s to every digit.

5.4 Marginal effects and how to report them

A logit coefficient is the change in the log odds, ln⁡[p/(1−p)]\ln[p/(1 - p)], for a unit change in a regressor. Few readers think in log odds. The change in the probability itself depends on where one starts: ∂pi/∂xik=F′(xi′β) βk\partial p_i/\partial x_{ik} = F'(x_i'\beta)\,\beta_k, which is largest when pip_i is one half and vanishes at the edges.

Definition 5.7 (Average marginal effect)

The average marginal effect of a continuous regressor xkx_k in a binary model is the sample average of F′(xi′β^) β^kF'(x_i'\hat\beta)\,\hat\beta_k; for a dummy, the average over the sample of the change in the fitted probability when the dummy is switched from 0 to 1.

In Output 5.1 the logit and probit coefficients differ by a factor of about two, as their scales require, but their average marginal effects agree to within 0.002: a thousand dollars more of 1975 earnings goes with a probability of working in 1978 higher by 1.35 points (logit) or 1.31 (probit). The linear model’s coefficient, 1.60 points, is larger: it is a single slope for everyone, and fits the steep rise near zero earnings as well as the flat top. And 15.7 % of its fitted probabilities exceed one.

How it is measured — Reporting a logit: odds ratios and marginal effects

Three numbers are reported for a logit coefficient, and they answer different questions. The coefficient βk\beta_k is the change in the log odds. Its exponential eβk\eu^{\beta_k} is the odds ratio: the factor by which the odds p/(1−p)p/(1 - p) are multiplied when xkx_k rises by one, the same for everyone in the model; it is the standard in medicine. The average marginal effect is the change in the probability, averaged over the people in the sample; it is the standard in economics, because policy questions are about how many more people will work, buy or move. The effect at the mean, computed at the average values of the regressors, is a fourth number, often close to the average effect and sometimes far from it, because the average person may resemble no one: the average of a dummy for marriage is a person 0.7 married.

5.5 Discrete choice from random utility

With more than two options — car, bus, train, air; four brands of a good — the latent variable becomes a utility for each option.

Definition 5.8 (Random utility model; multinomial logit)

In a random utility model, person ii facing options j=1,…,Jj = 1, \dots, J derives utility Uij=Vij+ηijU_{ij} = V_{ij} + \eta_{ij} from option jj, where VijV_{ij} depends on observed characteristics of the option and the person and ηij\eta_{ij} is a taste shock, and chooses the option with the highest utility. When the ηij\eta_{ij} are independent across options and people with the extreme-value (Gumbel) distribution, Pr⁡(η≤t)=exp⁡(−e−t)\Pr(\eta \le t) = \exp(-\eu^{-t}), the model is the multinomial logit (or conditional logit when VijV_{ij} depends on characteristics of the options).

Proposition 5.9 (Logit choice probabilities)

In the multinomial logit, Pr⁡(i chooses j)=eVij/∑keVik\Pr(i \text{ chooses } j) = \eu^{V_{ij}} / \sum_k \eu^{V_{ik}}.

Proof. We prove it for two options; the general case follows by the same integration over all options. Option 1 is chosen when η2<V1−V2+η1\eta_2 < V_1 - V_2 + \eta_1. Conditional on η1=t\eta_1 = t, this has probability exp⁡(−e−(V1−V2+t))\exp(-\eu^{-(V_1 - V_2 + t)}). The density of η1\eta_1 is e−texp⁡(−e−t)\eu^{-t}\exp(-\eu^{-t}). Writing c=1+e−(V1−V2)c = 1 + \eu^{-(V_1 - V_2)}, the probability is

∫−∞∞e−texp⁡(−c e−t) dt=[1cexp⁡(−c e−t)]−∞∞=1c=eV1eV1+eV2,\int_{-\infty}^{\infty} \eu^{-t} \exp(-c\,\eu^{-t})\, dt = \Bigl[\tfrac{1}{c}\exp(-c\,\eu^{-t})\Bigr]_{-\infty}^{\infty} = \frac1c = \frac{\eu^{V_1}}{\eu^{V_1} + \eu^{V_2}},

substituting s=e−ts = \eu^{-t} in the integral if one prefers. ∎

Definition 5.10 (Independence of irrelevant alternatives)

A choice model has the property of independence of irrelevant alternatives (IIA) if the ratio of the probabilities of any two options does not depend on which other options are available or on their characteristics.

Proposition 5.11 (Logit has IIA)

In the multinomial logit, Pr⁡(j)/Pr⁡(k)=eVij−Vik\Pr(j)/\Pr(k) = \eu^{V_{ij} - V_{ik}}. Adding or removing an option, or changing its characteristics, leaves the ratio unchanged; a new option draws its users from the others in proportion to their probabilities.

Proof. The denominators of Pr⁡(j)\Pr(j) and Pr⁡(k)\Pr(k) are the same sum and cancel. The ratio involves only VijV_{ij} and VikV_{ik}. If a new option takes probability qq, every other probability is multiplied by 1−q1 - q, since the ratios among them are fixed and they sum to 1−q1 - q. ∎

The textbook warning is the red bus and the blue bus. If commuters split evenly between a car and a red bus, and an identical blue bus is added, common sense says the buses share the bus riders: car one half, each bus one quarter. Logit says each option gets one third, because the new bus must take from the car in proportion. Whenever options are closer substitutes for some than for others, IIA misleads; nested logit, which groups similar options, and models whose taste coefficients vary across people relax it.

Listing 5.3 estimates a conditional logit on real data: 210 travellers, each choosing air, train, bus or car for one journey, with each option’s cost, time in the vehicle and time waiting at the terminal.

"""Discrete choice on real data: 210 travellers choose air, train, bus or car.
Conditional logit with a constant for each mode (car is the base), cost and times."""
import numpy as np
from choicetools import clogit
from econdata import sm_dataset

m = sm_dataset("modechoice")                 # one row per traveller and mode
names = ["air", "train", "bus"]
for k, name in enumerate(names, start=1):
    m[name] = (m["mode"] == k).astype(float)
cols = names + ["invc", "invt", "ttme"]  # cost ($); in-vehicle, terminal time (min)
r = clogit(m.choice.values, m[cols].values, m.individual.values)
for name, b, se in zip(cols, r["beta"], r["se"]):
    print(f"{name:6s} {b:8.4f} ({se:.4f})")
b = dict(zip(cols, r["beta"]))
print(f"value of in-vehicle time: {60 * b['invt'] / b['invc']:.1f} dollars an hour")

P = r["prob"].reshape(210, 4)               # rows: travellers; columns: air .. car
print("actual shares    ", np.round(m.groupby("mode").choice.mean().values, 3))
print("predicted shares ", np.round(P.mean(0), 3))
no_air = P[:, 1:] / (1 - P[:, [0]])          # the same model with air removed
print("without air      ", np.round(no_air.mean(0), 3), "(train, bus, car)")
Listing 5.3. A conditional logit by Newton’s method (clogit), and the forecast without air travel. code/bachelor-3/05-binary-outcomes/listings/travel_mode.py
$ python travel_mode.py
air      4.7399 (0.8675)
train    3.9532 (0.4686)
bus      3.3062 (0.4583)
invc    -0.0139 (0.0067)
invt    -0.0040 (0.0008)
ttme    -0.0969 (0.0103)
value of in-vehicle time: 17.2 dollars an hour
actual shares     [0.276 0.3   0.143 0.281]
predicted shares  [0.276 0.3   0.143 0.281]
without air       [0.386 0.188 0.426] (train, bus, car)
Output 5.3. Coefficients with standard errors; car is the base mode.

The ratio of the time and cost coefficients is a price of time: travellers trade an hour in the vehicle for 17.2 dollars. The model fits the four shares exactly, a consequence of the mode constants: the multinomial analogue of the score equations in Proposition 5.5. Without air travel, it sends the air travellers to the other modes in proportion, for each traveller, to their probabilities. In these data the households of air travellers have incomes like those of car travellers and well above those of bus travellers; common sense would send many of them to the car and few to the bus, and IIA cannot.

On the record — Forecasting a new rail line from a logit model

Before the Bay Area Rapid Transit system opened in San Francisco, McFadden’s group surveyed commuters in 1972, estimated a multinomial logit of their journey to work, and used it to forecast the choices of 631 commuters surveyed again in 1975, after the new line opened. The forecast share of work trips by the new line was 6.3 % (standard error 2.5 %); the realised share was 6.2 %. The forecasts for driving alone (55.8 % against 59.9 %) and for the bus (14.9 % against 12.2 %) were less exact, and McFadden notes that the model overestimated people’s willingness to walk to the new stations.

Logit demand for products

The same model, applied to the market shares of differentiated products, is the workhorse of empirical industrial organisation. Each consumer buys one of JJ products or nothing (option 0, with V0=0V_0 = 0), and Vj=δj=xj′γ+αpj+ξjV_j = \delta_j = x_j'\gamma + \alpha p_j + \xi_j, where ξj\xi_j is quality seen by consumers but not by the economist.

Definition 5.12 (Log-share inversion)

In the logit demand model, the log-share inversion recovers each product’s mean utility from its market share and the outside share: ln⁡sj−ln⁡s0=δj=xj′γ+αpj+ξj\ln s_j - \ln s_0 = \delta_j = x_j'\gamma + \alpha p_j + \xi_j, a linear equation that can be estimated by regression across products and markets (Berry 1994).

The inversion follows from sj/s0=eδj/e0s_j/s_0 = \eu^{\delta_j}/\eu^{0}. Its value is that it turns a nonlinear choice model into a regression, so that the tools of Chapter 1 apply: prices are set by firms that know ξj\xi_j, so pjp_j is correlated with the error, and OLS is biased toward zero (Exercise 5.11). Instruments are costs, or characteristics of rival products.

"""Logit demand on a simulated market: 300 towns, four products and an outside option.
Shares come from utility delta_j = 1 + 0.5 x_j - 2 p_j + xi_j and logit taste shocks;
the log-share inversion recovers the price coefficient by OLS."""
import numpy as np
import statsmodels.api as sm

rng = np.random.default_rng(1994)
T, J, alpha = 300, 4, -2.0
x = rng.uniform(0, 2, (T, J))                 # an observed quality
p = 1 + 0.3 * x + rng.uniform(0, 0.5, (T, J))  # prices, unrelated to xi here
xi = rng.normal(0, 0.3, (T, J))               # quality the economist does not see
delta = 1 + 0.5 * x + alpha * p + xi
s = np.exp(delta) / (1 + np.exp(delta).sum(1, keepdims=True))
s0 = 1 - s.sum(1)

y = (np.log(s) - np.log(s0)[:, None]).ravel()  # ln s_j - ln s_0 = delta_j
fit = sm.OLS(y, sm.add_constant(np.column_stack([x.ravel(), p.ravel()]))).fit()
print(f"price coefficient: true {alpha}, estimated {fit.params[2]:.3f}"
      f" (s.e. {fit.bse[2]:.3f})")

a = fit.params[2]                              # elasticities in town 1
print("shares in town 1:", np.round(s[0], 3), " outside", round(s0[0], 3))
for j in range(J):
    own = a * p[0, j] * (1 - s[0, j])
    cross = [-a * p[0, k] * s[0, k] for k in range(J) if k != j]
    print(f"product {j + 1}: own {own:6.2f}  with respect to each other price",
          " ".join(f"{c:5.2f}" for c in cross))
Listing 5.4. Logit demand on 300 simulated markets: the inversion and the elasticities. code/bachelor-3/05-binary-outcomes/listings/logit_demand.py
$ python logit_demand.py
price coefficient: true -2.0, estimated -2.033 (s.e. 0.060)
shares in town 1: [0.065 0.194 0.097 0.14 ]  outside 0.504
product 1: own  -3.06  with respect to each other price  0.40  0.32  0.47
product 2: own  -1.65  with respect to each other price  0.21  0.32  0.47
product 3: own  -2.94  with respect to each other price  0.21  0.40  0.47
product 4: own  -2.87  with respect to each other price  0.21  0.40  0.32
Output 5.4. Own and cross price elasticities in one town.

The own elasticity is αpj(1−sj)\alpha p_j(1 - s_j) and the cross elasticity of jj’s share with respect to kk’s price is −αpksk-\alpha p_k s_k, the same for every jj: in each column of Output 5.4, a rise in product kk’s price raises every rival’s share by the same percentage. That is IIA again, and it is why logit demand, used to judge a merger, says that two products that are close substitutes compete no harder than two that are not.

Model — Random utility and logit demand

Assumes. Each person chooses the option with the highest utility, a mean utility depending on observed characteristics plus a taste shock independent across options and people with the extreme-value distribution.

Predicts. Choice probabilities eVj/∑keVk\eu^{V_j}/\sum_k \eu^{V_k}; fitted shares equal to observed shares when each option has a constant; substitution in proportion to shares (IIA); a price of time equal to the ratio of time and cost coefficients.

Tested. In forecasting the share of a new rail line in 1975 from 1972 data, the logit came within 0.1 percentage point; its forecasts for other modes were off by up to four points.

Breaks. When options are close substitutes for each other (two buses, two similar cars), IIA sends too many customers to unlike options; nested logit and random-coefficient models relax it. When prices respond to unobserved quality, estimates of the price coefficient need instruments.

5.6 Exercises

Exercise 5.1 ★

In the opening chart, where do the three fitted lines differ most, and where do all three fail? Which feature of the data explains the failure?

Solution

Solution of Exercise 5.1.

They differ most at the edges: at zero earnings the linear model predicts 0.704, the logit 0.665 and the probit 0.681; near the top the linear model reaches 1 while the curves flatten at about 0.97. All three fail for the men with no earnings in 1975, whose observed share is 0.438. Those men form a group of their own — most were out of work — and a smooth function of earnings that also fits the men with earnings cannot drop to them.

Exercise 5.2 ★

A logit has x′β^=0.8x'\hat\beta = 0.8 for a person, and the coefficient on a regressor is 0.5. Compute the person’s probability and the marginal effect of the regressor on it. Repeat for x′β^=3x'\hat\beta = 3.

Solution

Solution of Exercise 5.2.

Λ(0.8)=1/(1+e−0.8)=0.690\Lambda(0.8) = 1/(1 + \eu^{-0.8}) = 0.690; marginal effect 0.690×0.310×0.5=0.1070.690 \times 0.310 \times 0.5 = 0.107. Λ(3)=0.953\Lambda(3) = 0.953; marginal effect 0.953×0.047×0.5=0.0220.953 \times 0.047 \times 0.5 = 0.022 (0.023 from the unrounded values). The same coefficient moves the probability a fifth as much near the top.

Exercise 5.3 ★

The logit coefficient on being married in Output 5.1 is −0.2981-0.2981. Compute the odds ratio and say what it means.

Solution

Solution of Exercise 5.3.

e−0.2981=0.742\eu^{-0.2981} = 0.742: other things equal, a married man’s odds of having earnings in 1978 are 0.74 times an unmarried man’s, about a quarter lower.

Exercise 5.4 ★

Describe data on commuters’ choices before and after a new tram line opened that would contradict IIA.

Solution

Solution of Exercise 5.4.

IIA says the tram takes the same percentage of each mode’s users. Data showing that the bus lost a large percentage of its riders while driving lost a small one (say the bus share fell by 40 % and the car share by 5 %) contradict it, as does a change in the ratio of car to bus riders after the tram opened.

Exercise 5.5 ★★

Add a dummy for no earnings in 1975 to the logit of the opening chart.

  1. Compare the log-likelihoods and the mean fitted probability for men with no earnings in 1975 with the observed share.
  2. With controls for age, education and marriage, report the average marginal effect of the dummy and of 1975 earnings.
Solution

Solution of Exercise 5.5.

The tested solution is ex05_zero_earnings.py, in the chapter’s exercises/ folder.

  1. The log-likelihood rises from −5,507.9-5{,}507.9 to −5,149.5-5{,}149.5, and the mean fitted probability for men with no earnings in 1975 falls from 0.665 to 0.438, exactly the observed share.
  2. The average marginal effect of the dummy is −0.135-0.135: having no earnings in 1975 lowers the probability of earnings in 1978 by 13.5 points beyond what a low income predicts. That of a thousand dollars of 1975 earnings falls to 0.0082.

Exercise 5.6 ★★

Five observations have y=(1,0,1,1,0)y = (1, 0, 1, 1, 0) and fitted logit probabilities p=(0.8,0.3,0.6,0.9,0.5)p = (0.8, 0.3, 0.6, 0.9, 0.5). Compute the log-likelihood. Which observation contributes the most to it in absolute value, and why?

Solution

Solution of Exercise 5.6.

ln⁡0.8+ln⁡0.7+ln⁡0.6+ln⁡0.9+ln⁡0.5=−0.223−0.357−0.511−0.105−0.693=−1.889\ln 0.8 + \ln 0.7 + \ln 0.6 + \ln 0.9 + \ln 0.5 = -0.223 - 0.357 - 0.511 - 0.105 - 0.693 = -1.889. (For y=0y = 0 the term is ln⁡(1−p)\ln(1 - p).) The fifth observation contributes most, −0.693-0.693: its outcome had a fitted probability of only one half.

Exercise 5.7 ★★

Using the elasticities printed in Output 5.4, by how many percent do the shares of products 2 and 3 change if product 1’s price rises by 1 %? And if product 4’s price rises by 1 %? Why are the answers the same for products 2 and 3?

Solution

Solution of Exercise 5.7.

A 1 % rise in product 1’s price raises the shares of products 2 and 3 by 0.21 % each; a 1 % rise in product 4’s price raises them by 0.47 % each.

The cross elasticity with respect to product kk’s price is −αpksk-\alpha p_k s_k, which does not depend on the product whose share responds: IIA.

Exercise 5.8 ★★

A logit with only a constant is fitted to nn observations with n1n_1 ones.

  1. Write the log-likelihood and the Newton step from bb.
  2. With n=100n = 100 and n1=80n_1 = 80, compute two Newton steps from b=0b = 0 and compare with the maximum, ln⁡4\ln 4.
Solution

Solution of Exercise 5.8.

  1. ℓ(b)=n1b−nln⁡(1+eb)\ell(b) = n_1 b - n\ln(1 + \eu^b); the score is n1−npn_1 - np and the second derivative −np(1−p)-np(1 - p), with p=Λ(b)p = \Lambda(b). The Newton step is b+(n1−np)/(np(1−p))b + (n_1 - np)/(np(1 - p)).
  2. From b=0b = 0: p=0.5p = 0.5, b1=0+30/25=1.2b_1 = 0 + 30/25 = 1.2. Then p=Λ(1.2)=0.7685p = \Lambda(1.2) = 0.7685 and b2=1.2+(80−76.85)/(100×0.7685×0.2315)=1.2+0.177=1.377b_2 = 1.2 + (80 - 76.85)/(100 \times 0.7685 \times 0.2315) = 1.2 + 0.177 = 1.377, against ln⁡4=1.386\ln 4 = 1.386.

Exercise 5.9 ★★

How would you check, in the linear probability model of Listing 5.1, that the linear form is wrong? Give two checks that use only its fitted values and the data.

Solution

Solution of Exercise 5.9.

First, sort the sample by fitted value, cut it into ten groups and compare each group’s mean outcome with its mean fitted value: a linear model that is wrong will be off systematically at the ends. Second, count fitted values outside [0,1][0, 1]: 15.7 % exceed one here. A third check adds the squared fitted values as a regressor; a significant coefficient signals curvature the model misses.

Exercise 5.10 ★★★

Show that in a logit with a constant, the fitted probabilities average to the observed share, and that in a logit whose only regressors are dummies for mutually exclusive groups (and no constant), the maximum likelihood fitted probability in each group is the group’s observed share. What does that say about the opening chart’s first dot in Exercise 5.5?

Solution

Solution of Exercise 5.10.

The score equation for the constant is ∑i(yi−pi)=0\sum_i (y_i - p_i) = 0, so 1n∑ipi=1n∑iyi\frac1n\sum_i p_i = \frac1n\sum_i y_i. With only group dummies and no constant, every member of group gg has the same index βg\beta_g and probability pg=Λ(βg)p_g = \Lambda(\beta_g); the score equation for βg\beta_g is ∑i∈g(yi−pg)=0\sum_{i \in g} (y_i - p_g) = 0, so pgp_g is the group’s share. In Exercise 5.5 the dummy for no earnings plays this role, together with the constant: the fitted share for that group equals the observed 0.438 whatever the other regressors.

Exercise 5.11 ★★★

Repeat the simulation of Listing 5.4, but let firms raise the price of products with high unobserved quality: pj=1+0.3xj+cj+0.8 ξjp_j = 1 + 0.3 x_j + c_j + 0.8\,\xi_j, where cjc_j is a cost that does not enter demand.

  1. Estimate the price coefficient by OLS on the log-share inversion. In which direction is it biased, and why?
  2. Estimate it by two-stage least squares with cjc_j as the instrument.
Solution

Solution of Exercise 5.11.

The tested solution is ex11_endogenous_price.py, in the chapter’s exercises/ folder.

  1. OLS gives −1.071-1.071 against a true −2-2. It is biased toward zero: products with high unseen quality have both high prices and high shares, so price seems to hurt sales less than it does.
  2. Two-stage least squares with the cost as instrument gives −2.033-2.033 (s.e. 0.064).

Exercise 5.12 ★★★

In a town, 60 % of commuters drive, 30 % take the bus and 10 % cycle. A new cycle lane will make cycling attractive enough to take 10 % of all commuters from the other modes (a new option, “cycle lane”).

  1. Under IIA, what are the new shares?
  2. Why is that forecast doubtful, and in which direction is it likely to err for each mode?
Solution

Solution of Exercise 5.12.

  1. Each existing share is multiplied by 0.9: car 54 %, bus 27 %, cycling 9 %, cycle lane 10 %.
  2. The lane is a close substitute for cycling and a poor one for driving. It should take mostly from cyclists and some bus riders: IIA overstates the fall in driving and understates the fall in cycling on the old roads.

5.7 Problem: A New Bus Line in Brenmoor

Problem 5.1

Weekend problem — a new bus line in Brenmoor

Brenmoor (invented) surveys 1,500 commuters. Each commutes by car, bus or bicycle; the survey records, for each commuter and each mode, the cost of the trip in dalens (the bus fare is 2.52.5 dalens, cycling costs nothing) and the door-to-door time in minutes. Of the 1,500, 992 chose the car or the bus.

A statistician estimates two models by maximum likelihood. The first is a binary logit of choosing the car rather than the bus, among those 992, on the differences car minus bus in cost and in time. The second is a three-way conditional logit with a constant for the car and for the bicycle (the bus is the base), a cost and a time coefficient.

The forecast adds to the three-way model an express bus with the ordinary bus fare, the bus constant and a door-to-door time 10 minutes shorter than the bus for every commuter.

Part I — car or bus.

  1. Write the probability of choosing the car in the binary logit, in terms of the cost and time differences.
  2. A commuter’s car trip costs 4.54.5 dalens and takes 30 minutes; the bus costs 2.52.5 dalens and takes 45 minutes. Compute x′β^x'\hat\beta and the probability that she drives.
  3. Interpret the constant. Why does it matter that the bus is the base?
  4. Is the cost coefficient significantly different from zero? Give its tt-statistic.
  5. Why does the logit need no assumption about the variance of the taste shocks to be estimated, but fix it anyway?
  6. Why might estimating on the 992 car and bus users only, leaving out the cyclists, still give consistent estimates in this model?

Part II — marginal effects and the value of time.

  1. For the commuter of Question 2, compute the marginal effect of the bus fare on her probability of driving.
  2. Compute the effect of cutting the bus time by 10 minutes on the same probability, using the marginal effect, and then exactly. Why do they differ?
  3. Compute the value of travel time from the binary logit, in dalens per hour.
  4. Compute it from the three-way logit.
  5. Give one reason why the two estimates differ.
  6. A road scheme would save each of 20,000 car commuters 5 minutes a day for 220 days a year. Value the saving with the three-way estimate.

Part III — three modes.

  1. Write the probability of cycling in the three-way logit.
  2. Check that the fitted shares equal the observed shares, and explain why.
  3. Interpret the bicycle constant.
  4. For a commuter with Vcar=−2.0V_{\text{car}} = -2.0, Vbus=−3.0V_{\text{bus}} = -3.0 and Vbicycle=−2.5V_{\text{bicycle}} = -2.5, compute the three probabilities.
  5. For the same commuter, compute the ratio of the car and bus probabilities. What happens to it if the bicycle becomes unavailable?
  6. Is the time coefficient the same for the three modes? Is that a reasonable assumption for cycling?

Part IV — the express line.

  1. What share does the model forecast for the express?
  2. From which mode does it take the most riders, in percentage points, and in percent of each mode’s share?
  3. Why does the model take riders from each mode in nearly equal proportions?
  4. Which mode would you expect the express to take most of its riders from in fact, and why?
  5. How would a nested logit, with the two buses in one nest, change the forecast?
  6. What survey, run after the express opens, would test the forecast, as McFadden’s group did for a new rail line?
  7. State the results: the commuters’ value of travel time, in dalens per hour, from the three-way model, and the express line’s forecast share, with the caveat that applies to it.
Solution

Solution of Problem 5.1.

1. Pr⁡(car)=Λ(0.6131−0.3198 Δcost−0.0537 Δtime)\Pr(\text{car}) = \Lambda(0.6131 - 0.3198\,\Delta\text{cost} - 0.0537\,\Delta\text{time}), with differences car minus bus.

2. Δcost=2\Delta\text{cost} = 2, Δtime=−15\Delta\text{time} = -15: x′β^=0.6131−0.6396+0.8055=0.779x'\hat\beta = 0.6131 - 0.6396 + 0.8055 = 0.779; Pr⁡=Λ(0.779)=0.685\Pr = \Lambda(0.779) = 0.685.

3. At equal cost and time, the log odds of driving are 0.61: a probability of Λ(0.6131)=0.65\Lambda(0.6131) = 0.65. It measures what the model leaves out (comfort, flexibility) relative to the bus; a different base would change its meaning but not the probabilities.

4. t=−0.3198/0.0546=−5.86t = -0.3198/0.0546 = -5.86: clearly different from zero.

5. Only the ratio of the coefficients to the spread of the taste shocks is identified. The logit fixes the spread (variance π2/3\pi^2/3) so that the coefficients are defined; ratios such as the value of time do not depend on the choice.

6. If the three-way logit is right, IIA implies that among those who chose the car or the bus, the choice between them follows a binary logit with the same coefficients; dropping the cyclists loses information but not consistency.

7. p(1−p)×0.3198=0.685×0.315×0.3198=0.069p(1 - p) \times 0.3198 = 0.685 \times 0.315 \times 0.3198 = 0.069: a dalen more on the bus fare raises her probability of driving by about 7 points.

8. The marginal effect gives 0.2158×(−0.0537)×10=−0.1160.2158 \times (-0.0537) \times 10 = -0.116. Exactly: x′β^x'\hat\beta falls by 0.537 to 0.242, and Λ(0.242)=0.560\Lambda(0.242) = 0.560, a fall of 0.125. The probability curve is not straight; the marginal effect is its slope at the starting point only.

9. 60×0.0537/0.3198=10.160 \times 0.0537/0.3198 = 10.1 dalens an hour.

10. 60×0.0730/0.3335=13.160 \times 0.0730/0.3335 = 13.1 dalens an hour.

11. Both are estimates with sampling error, and the binary model uses fewer commuters and only the car–bus comparisons; its cost and time coefficients have larger standard errors (0.0546 and 0.0114 against 0.0467 and 0.0073).

12. 20,000×5×220=22,000,00020{,}000 \times 5 \times 220 = 22{,}000{,}000 minutes, or 366,667366{,}667 hours, times 13.13 dalens: about 4.84.8 dalens million a year.

13. Pr⁡(bicycle)=eVb/(eVc+eVu+eVb)\Pr(\text{bicycle}) = \eu^{V_b}/(\eu^{V_c} + \eu^{V_u} + \eu^{V_b}), with Vc=0.4053−0.3335 costc−0.0730 timecV_c = 0.4053 - 0.3335\,\text{cost}_c - 0.0730\,\text{time}_c, Vu=−0.3335×2.5−0.0730 timeuV_u = -0.3335 \times 2.5 - 0.0730\,\text{time}_u and Vb=−0.6719−0.0730 timebV_b = -0.6719 - 0.0730\,\text{time}_b.

14. 0.448, 0.213 and 0.339 in both columns. With a constant for every mode but the base, the score equations for the constants say that fitted and observed shares are equal.

15. At equal cost and time, the bicycle is less attractive than the bus by 0.672 in utility: worth 0.672/0.3335=2.00.672/0.3335 = 2.0 dalens a trip, or 0.672/0.0730=9.20.672/0.0730 = 9.2 minutes. It stands for effort, weather and danger.

16. e−2=0.1353\eu^{-2} = 0.1353, e−3=0.0498\eu^{-3} = 0.0498, e−2.5=0.0821\eu^{-2.5} = 0.0821, sum 0.2672: car 0.506, bus 0.186, bicycle 0.307.

17. e−2/e−3=e=2.72\eu^{-2}/\eu^{-3} = \eu = 2.72. Without the bicycle it is still 2.72 (IIA): car 0.731, bus 0.269.

18. Yes, by assumption. A minute on a bicycle is effort and exposure, not a seat; a mode-specific time coefficient would let the data say whether it costs more.

19. 0.297, almost three commuters in ten.

20. Car: 0.448−0.319=0.1290.448 - 0.319 = 0.129 points, 28.8 % of its share. Bus: 0.213−0.143=0.0700.213 - 0.143 = 0.070 points, 32.9 %. Bicycle: 0.339−0.241=0.0980.339 - 0.241 = 0.098 points, 28.9 %. Most riders come from the car; the largest percentage from the bus.

21. For each commuter, the express takes from every mode in proportion to that commuter’s probabilities (IIA). The percentages differ across modes only because the express is more attractive to some commuters, those for whom the bus is already a good option.

22. From the ordinary bus: the express is the same product, only faster. Commuters who drive because they dislike buses will mostly keep driving.

23. With the two buses in one nest, tastes for bus travel are shared by the two options, and the express takes most of its riders from the ordinary bus; the bus-type share grows less, and the car and bicycle lose fewer riders.

24. Survey the same commuters after the express opens, compare each mode’s forecast share with the realised one, and tabulate forecast against actual choices.

25. The commuters value travel time at about 13.1 dalens an hour. The three-way logit forecasts that an express line 10 minutes faster than the bus would carry 29.7 % of commuters; because of IIA the forecast takes too many from the car and the bicycle and too few from the ordinary bus, and is probably too high.

本章定义的术语

在术语表中查看全部 1086 个术语