Econometrics · Week 3
Simple and multiple regression簡單回歸與多元回歸
Regression turns a question such as “how much more do people with more schooling earn?” into a number. This week builds the linear regression model, derives the ordinary least squares (OLS) estimator from scratch, and then writes the whole method in one line of matrix algebra.
回歸分析把「多讀書的人收入高多少?」這類問題變成一個數字。本週建立線性回歸模型,從零推導普通最小二乘(OLS)估計量,最後用一行矩陣代數寫出整個方法。
- Builds on 先修內容
- Weeks 1–2
- Reading time 閱讀時間
- About 40 minutes
- Data 數據
wage2, n = 935- Code 程式碼
- R, Python
The simple linear regression model簡單線性回歸模型
Regression starts from a question about averages: if we know , what value of should we expect? Week 2 called this the conditional expectation function, . The simple linear regression model assumes that it is a straight line:
回歸分析從一個關於平均值的問題開始:如果知道 ,我們應該預期 是多少?第 2 週把這稱為條件期望函數 。簡單線性回歸模型假設它是一條直線:
Raise by one unit and the expected value of rises by exactly , whatever the starting point:
把 提高一個單位, 的期望值便會上升 ,與起點無關:
So is the average change in for a one-unit change in . The same model is usually written with an error term :
所以 是 每改變一個單位時 的平均變化。同一個模型通常會加上誤差項 來表達:
The error is how far an individual observation lies from its conditional mean. It collects every factor other than that affects . Holding those factors fixed, is the marginal effect of on : .
誤差項 是單個觀測值與其條件平均值的距離,它包含了 以外所有影響 的因素。在這些因素保持不變的情況下, 就是 對 的邊際效應:。
Ordinary least squares普通最小二乘法
We never observe and . We observe a sample of pairs and must use it to estimate them. For any candidate line , the residual is the prediction error for observation . Ordinary least squares picks the line that makes the sum of squared residuals as small as possible:
我們永遠觀測不到 和 ,只能觀測到 對數據 ,並用它們來估計。對任何一條候選直線 ,殘差 就是第 個觀測值的預測誤差。普通最小二乘法選擇令殘差平方和最小的那條直線:
Squaring stops positive and negative errors from cancelling, penalises large misses more than small ones, and, as the next steps show, gives an answer in closed form.
取平方可以避免正負誤差互相抵銷,對較大的誤差給予更重的懲罰,而且正如下面所示,可以得出一條明確的公式。
- –
- –
- –
- –
Drag any point. The line is always the one that makes the total area of the shaded squares as small as possible.
拖動任何一點。圖中的直線永遠是令所有陰影正方形總面積最小的那一條。
At the minimum, both partial derivatives are zero. These are the first-order conditions, evaluated at the OLS estimates and :
在最小值處,兩個偏導數都等於零。這就是一階條件,在 OLS 估計值 和 處成立:
Two equations, two unknowns. Solving them gives the OLS estimators:
兩條方程、兩個未知數,解出來便得到 OLS 估計量:
Show every step 顯示完整推導
Intercept. Divide the first condition by and split the sum. Since and :
截距。把第一個條件除以 ,再把總和拆開。由於 、:
Slope. Substitute this into the second condition. Then , so
斜率。把上式代入第二個條件,得到 ,所以
Centring. Deviations from a mean add up to zero: . So subtracting from on either side changes nothing:
中心化。離均差的總和必定為零:。因此在兩邊把 換成 不會改變結果:
Dividing gives the formula for . It exists only if , that is, if the are not all equal. SSR is a sum of squares and is convex in , so this stationary point is the minimum.
兩邊相除便得到 的公式。公式成立的前提是 ,即 不能全部相等。SSR 是平方和,對 是凸函數,所以這個駐點就是最小值。
Divide the top and bottom of by and a familiar pair appears: the sample covariance of and over the sample variance of .
把 的分子和分母同時除以 ,就會出現兩個熟悉的量: 與 的樣本協方差,除以 的樣本方差。
Fitted values, residuals and interpretation擬合值、殘差與係數解讀
Once the estimates are in hand, every observation gets a fitted value and a residual:
有了估計值之後,每個觀測值都有一個擬合值和一個殘差:
is the predicted change in when rises by one unit.
是 增加一個單位時 的預測變化。
is the predicted value of when . Treat it with care when lies far outside the data.
是 時 的預測值。如果 遠在數據範圍之外,解讀時要特別小心。
Three properties hold in every sample estimated by OLS with an intercept. They are not assumptions; they follow directly from the first-order conditions.
凡是包含截距的 OLS 估計,以下三個性質在任何樣本中都成立。它們不是假設,而是一階條件的直接結果。
The first is the first-order condition for ; the second is the one for . The third follows from the first, since . And because , the fitted line always passes through the point of means .
第一個性質就是 的一階條件,第二個是 的一階條件。第三個由第一個推出,因為 。又因為 ,擬合直線必定經過平均值點 。
Goodness of fit: R-squared擬合優度:判定係數
How much of the variation in does the line account for? Split the total variation into an explained part and a residual part:
這條直線解釋了 多少的變化?我們可以把總變異拆成已解釋部分和殘差部分:
Show every step 顯示完整推導
Write each deviation as , square it and add up:
把每個離差寫成 ,平方後加總:
The cross term vanishes. Substituting and using the first two properties from Section 3:
交叉項等於零。代入 ,並利用第 3 節的前兩個性質:
The coefficient of determination is the explained share:
判定係數就是已解釋部分所佔的比例:
With an intercept in the regression, . The closer it is to 1, the larger the share of the sample variation in explained by .
只要回歸包含截距,便有 。數值越接近 1, 所解釋的 樣本變異比例就越大。
Example: education and earnings例子:教育與收入
Does schooling raise earnings, and by how much? The wage2 dataset records monthly earnings, years of education and an IQ score for 935 men in the United States in 1980. Start with the simple regression
教育能否提高收入?提高多少?wage2 數據集記錄了 1980 年美國 935 名男性的月收入、受教育年數和智商分數。先做簡單回歸:
| (1) Simple | (2) With IQ | |
|---|---|---|
| Intercept 截距 | 146.95(77.72) | −128.89(92.18) |
educ 教育年數 |
60.21(5.70) | 42.06(6.55) |
IQ 智商 |
— | 5.14(0.96) |
| 0.107 | 0.134 | |
| Observations 樣本數 | 935 | 935 |
Standard errors in parentheses. They measure how much an estimate would vary from sample to sample, and are used for hypothesis tests in later weeks.
括號內為標準誤,反映估計值在不同樣本之間會有多大變化,會在之後幾週的假設檢定中使用。
In column (1), each extra year of education is associated with about $60 more in monthly earnings, on average. The intercept, $147, is the prediction for someone with no schooling at all. Nobody in the sample has fewer than 9 years, so it has no useful meaning here. : education accounts for about a tenth of the variation in earnings.
第 (1) 欄顯示,平均而言每多一年教育,月收入約高 60 美元。截距 147 美元是完全沒有受過教育的人的預測收入,但樣本中沒有人少於 9 年教育,所以這裏的截距沒有實際意義。,即教育解釋了收入變異的大約十分之一。
But education and earnings could both be driven by ability. Adding IQ as a proxy for ability gives column (2):
然而,教育和收入可能同樣受能力影響。加入智商作為能力的代理變數,得到第 (2) 欄:
Holding IQ fixed, an extra year of education is now associated with $42, not $60. People with more schooling tend to have higher IQ scores (the correlation in this sample is 0.52), so in column (1) the education coefficient was also picking up part of what IQ explains.
在智商不變的情況下,多一年教育現在只對應 42 美元,而不是 60 美元。受教育較多的人往往智商分數也較高(此樣本中兩者的相關係數為 0.52),所以第 (1) 欄的教育係數其實也包含了部分本應由智商解釋的效果。
Column (2) is more persuasive as an estimate of the causal effect of education, provided IQ is a good proxy for ability. It is still not proof: other unobserved factors may remain in the error term.
如果智商是能力的良好代理,第 (2) 欄作為教育因果效應的估計會更有說服力。但這仍然不是證明:誤差項中可能還有其他未被觀測的因素。
Multiple regression多元回歸
The multiple linear regression model lets the conditional mean of depend on explanatory variables:
多元線性回歸模型讓 的條件平均值取決於 個解釋變數:
Each coefficient now has a “holding the others fixed” reading. For :
每個係數現在都要以「其他變數保持不變」來解讀。以 為例:
is the average change in for a one-unit change in , with held at the same values. Regression holds those variables fixed statistically, without needing an experiment that holds them fixed in practice.
是在 保持不變時, 每改變一個單位 的平均變化。回歸是在統計上把這些變數固定,而不需要真的做一個把它們固定下來的實驗。
OLS in matrix form矩陣形式的普通最小二乘法
Writing out the model for all observations gives equations. Stack them:
把模型對全部 個觀測值寫出來,便得到 條方程。把它們疊起來:
The whole system becomes one line:
整個方程組變成一行:
Each row of is one observation; the first column of ones carries the intercept. For a candidate vector , the residuals are , and the sum of squared residuals is their inner product with themselves:
的每一行是一個觀測值,第一列全是 1,對應截距。對任何候選向量 ,殘差是 ,殘差平方和就是這個向量與自身的內積:
Setting the derivative to zero and solving gives the most famous formula in econometrics:
令導數等於零並求解,便得到計量經濟學中最著名的公式:
Show every step 顯示完整推導
Expanding. Multiply out: . The two middle terms are the same number: is , and a scalar equals its own transpose, . That gives the above.
展開。乘出來得到 。中間兩項其實是同一個數: 是 的純量,而純量等於自身的轉置,,所以合併成上面的 。
Differentiating. Two rules from Week 1: , and when is symmetric. is symmetric, so the first-order condition is
求導。用第 1 週的兩條規則:;當 對稱時,。 是對稱矩陣,所以一階條件是
Solving. Rearranging gives the normal equations . Multiply both sides on the left by , and the identity matrix leaves the boxed formula:
求解。整理後得到正規方程 。兩邊左乘 ,左邊只剩單位矩陣 ,便得到上面方框中的公式:
Checking with one regressor. When , the normal equations are
用單一解釋變數驗證。當 ,正規方程是
which are the two first-order conditions of Section 2, rearranged. The matrix formula is the same method, for any number of regressors.
這正是第 2 節的兩個一階條件,只是重新排列。矩陣公式是同一個方法,只不過適用於任意數量的解釋變數。
The normal equations can also be written : the residual vector is orthogonal to every column of . This is the matrix version of and , and it means the residuals are uncorrelated in the sample with every regressor.
正規方程也可以寫成 :殘差向量與 的每一列都正交。這就是 和 的矩陣版本,表示殘差在樣本中與每個解釋變數都不相關。
The ability to write very different questions as is the point. Returns to education, what drives a share price, the value of a house, tomorrow’s electricity demand: each becomes the same problem of estimating well from a sample.
能把截然不同的問題都寫成 ,正是這套方法的力量。教育回報、股價的驅動因素、房屋的價值、明天的電力需求,全都變成同一個問題:如何從樣本中準確估計 。
Reproduce the results自己重現結果
The data come with the free wooldridge package for R and Python. Both snippets fit column (2) and then compute the same estimates directly from the matrix formula.
數據收錄在 R 和 Python 的免費套件 wooldridge 中。以下兩段程式碼都會估計第 (2) 欄,再直接用矩陣公式計算出相同的估計值。
# install.packages("wooldridge") # run once
library(wooldridge)
data("wage2")
m1 <- lm(wage ~ educ, data = wage2)
m2 <- lm(wage ~ educ + IQ, data = wage2)
summary(m1)
summary(m2)
# The matrix formula, by hand
X <- cbind(1, wage2$educ, wage2$IQ)
y <- wage2$wage
solve(t(X) %*% X, t(X) %*% y) # -128.89, 42.06, 5.14
# pip install wooldridge numpy
import numpy as np
import wooldridge as wd
df = wd.data("wage2")
X = np.column_stack([np.ones(len(df)), df["educ"], df["IQ"]])
y = df["wage"].to_numpy()
# Solve (X'X) b = X'y rather than inverting X'X
beta_hat = np.linalg.solve(X.T @ X, X.T @ y)
print(beta_hat.round(2)) # [-128.89 42.06 5.14]
Check your understanding自我測驗
-
Every person in a sample has exactly 12 years of education. Can OLS estimate the return to education?
樣本中每個人都恰好受過 12 年教育。OLS 能估計教育回報嗎?
Answer 答案
No. , so the formula for divides by zero. In matrix terms, the education column is 12 times the column of ones, so the columns of are not linearly independent and cannot be inverted.
不能。, 的公式分母為零。以矩陣來說,教育一列等於常數列的 12 倍, 的各列並非線性獨立, 不可逆。
-
Using column (1), what monthly earnings are predicted for someone with 16 years of education?
根據第 (1) 欄,受過 16 年教育的人預測月收入是多少?
Answer 答案
, so about $1,110 a month.
,即每月約 1,110 美元。
-
You run OLS with an intercept and find that the residuals add up to 5. What has happened?
你用含截距的 OLS 做回歸,發現殘差總和是 5。發生了甚麼事?
Answer 答案
Something is wrong. With an intercept, in every sample, because it is the first-order condition for . Check the calculation, or whether the intercept was left out.
一定是哪裏出錯了。只要有截距, 在任何樣本中都成立,因為這正是 的一階條件。請檢查計算,或者確認是否漏了截距。
-
Adding IQ raised from 0.107 to 0.134. Does that show the second model is the right one?
加入智商後, 由 0.107 升至 0.134。這是否證明第二個模型才是正確的?
Answer 答案
No. Adding a regressor can never lower : OLS could always set its coefficient to zero and keep the old fit, so SSR cannot rise. A higher on its own says little about whether a model is right.
不是。加入解釋變數永遠不會令 下降:OLS 大可把新係數設為零而保留原來的擬合,所以 SSR 不會上升。單憑 上升,並不能說明模型是否正確。
-
Why does the education coefficient fall from 60.21 to 42.06 when IQ is added?
為甚麼加入智商後,教育係數由 60.21 降至 42.06?
Answer 答案
IQ raises earnings and is positively related to education. Leaving it out lets education take credit for part of IQ’s effect: .
智商會提高收入,而且與教育正相關。不把它放進模型,教育便會「搶走」部分屬於智商的效果:。
Sources and acknowledgement 資料來源與鳴謝
- Lecture materials for Introductory Econometrics (ETC2410) by Associate Professor Didier Nibbering, Department of Econometrics and Business Statistics, Monash Business School.
- Jeffrey M. Wooldridge, Introductory Econometrics: A Modern Approach, Chapters 2 and 3, and Appendix E.
- Data: wage2, distributed with the textbook and in the wooldridge R package. All estimates on this page were computed from it.
Any errors are our own.