본문 바로가기

계량경제학/인과추론의 데이터과학

Fixed effects

https://theeffectbook.net/ch-FixedEffects.html

 

Chapter 16 - Fixed Effects | The Effect

Chapter 16 - Fixed Effects | The Effect is a textbook that covers the basics and concepts of research design, especially as applied to causal inference from observational data.

theeffectbook.net

위 글을 참고하여 작성한 글입니다 


Fixed effect이란?

우리가 원하는 효과를 identify 하려면, 보고싶은 변수 외의 모든 변수들을 control 해야 함 

만약 control 해야 하는 여러 변수들을 한번에 포괄하는 larger category가 있고, 그 안에서 변수들이 constant 하다면, 해당 larger category로 변수들을 손쉽게 control 할 수 있다. 

 

예시1: 시골에 전기가 들어오는 것이 생산성에 미치는 영향 

  • '지리'는 backdoor이 될 수 있음 (시골의 지리에 따라 전기가 들어오는 영향이 달라짐, 시골의 지리가 생산성에 영향을 미침)
  • 지리적 위치가 동일한 시골 데이터만을 사용 -> 시골의 지리 차이에서 오는 생산성 차이가 사라지므로 backdoor이 차단됨 

예시2: 독일 총리의 방문(Chancellor Visit)이 독일과의 무역(TradewithGermany)에 미치는 영향

독일과의 무역에 영향이 되는 다양한 요인이 있음: 독일과의 역사, 지리, 정치, 문화 등.. -> 대부분은 하나의 Country 내에서 일정함 

-> 국가별로 control 하면 독일과의 역사, 지리, 정치 등의 변수의 효과를 control 할 필요가 없어짐 (정치는 동일한 국가 안에서도 시간이 지남에 따라 달라질 수 있으므로 국가 변수로 묶을 수 없음) 

 

The Variation Within (개인 내 변동) 

fixed effect

= individual에서 오는 모든 차이 (variation between individual)를 control 하겠다 

-> individual 내 차이 (variation within individual)은 어떻게 control 할 수 있는가?

-> variation within individual을 control 하는 방법: individual 간 평균을 빼주기

 

예시: 운동이 1년간 감기에 걸리는 횟수에 미치는 영향 

variation within individual을 control 하는 방법

  • 개인 별로 year에 따라 운동량이 차이남
  • -> variation within individual이 생김
  • -> 개인 별로 Exercise - meanExercise = WithinExercise를 계산
  • -> variation within individual이 control 되어서 variation between individual을 비교할 수 있게 됨 

각 unit의 데이터에서 exercise hours per week, colds per year의 평균을 0점으로 맞춘 후 (variation within individual을 통제) 비교할 수 있음 

 

Fixed Effect in Action (실제 데이터로 Fixed Effect를 적용해보기)

예시: 건강한 식생활 알림이 실제 건강한 식생활에 미치는 영향

1) raw data: unit의 fixed effect를 고려하지 않았을 때 intensity of reminders ~ healthy eating score의 correlation = 0.111 

 

2) fixed effect 적용 

개인마다 알림이 오는 주기와 건강한 식생활 정도를 선택할 수 있다는 backdoor이 있으므로 개인 별 효과 차이를 fixed effect를 통해 제어함 

unit 별 x,y 평균을 (0,0)으로 맞춘 뒤 4개 unit의 그래프를 하나로 그렷을 때 상관관계는 .363으로 1)에 비해 상관관계가 높아짐 

 

Fixed Effect의 Regression Estimators

 

βi: 절편이 서로 다름 -> intercept를 individual마다 다양하도록 허용 -> 각 individual을 control

β1: 모든 unit이 동일한 기울기를 가짐 

 

Q1. 절편을 individual 별로 서로 다르게 설정 했을 때 효과 차이가 어떻게 달라지는가? 

예시: 1인당 GDP와 기대수명 (인도와 브라질 데이터) 

 

1) 절편을 고정하는 경우

  • Yit = β0 + β1 * Xit + εit
  • 나라간 차이를 고려하지 못함 

2) 절편을 country 별로 다르게 설정하는 경우 

  • Yit = βi + β1 * Xit + εit
  • 나라 간 차이가 고려됨 

Q2. individual intercept를 고려할 때 회귀선을 추정하는 방법 

1) absorbing the fixed effect 

독립변수, 종속변수 모두에서 동일 i에 대한 평균을 빼준 뒤 regression 진행 

import numpy as np
import statsmodels.formula.api as sm
from causaldata import gapminder
import matplotlib.pyplot as plt 

gm = gapminder.load_pandas().data
gm['logGDPpercap'] = gm['gdpPercap'].apply('log')

gm[['logGDPpercap_within','lifeExp_within']] = (gm.
groupby('country')[['logGDPpercap','lifeExp']].
transform(lambda x: x - np.mean(x)))

m1 = sm.ols(formula = 'lifeExp_within ~ logGDPpercap_within', 
data = gm).fit()
m1.summary()

표 해석

  • logGPDpercap의 coef = 9.769
  • R2 = 0.410
from sklearn.linear_model import LinearRegression

plt.plot(gm[gm['country']=='India'].sort_values(by='year')['logGDPpercap_within'],
         gm[gm['country']=='India'].sort_values(by='year')['lifeExp_within'],'o',
         label = 'India')
plt.plot(gm[gm['country']=='Brazil'].sort_values(by='year')['logGDPpercap_within'],
         gm[gm['country']=='Brazil'].sort_values(by='year')['lifeExp_within'],'o',
         label = 'Brazil')

X = gm[gm['country'].isin(['India','Brazil'])]['logGDPpercap_within'].values.reshape(-1,1)
y = gm[gm['country'].isin(['India','Brazil'])]['lifeExp_within'].values.reshape(-1,1)
lr = LinearRegression().fit(X,y)
X_lin = np.linspace(X.min(), X.max(), 100)
y_lin = lr.intercept_[0] + lr.coef_[0][0] * X_lin
plt.plot(X_lin, y_lin, color = 'black')

plt.legend()
plt.xlabel('GDP per Capita - Within (log scale)')
plt.ylabel('Life Expectancy - Within')

plt.show()

X, Y에서 각각 individual 별 평균을 빼준 값을 regression 적합 가능 

 

 

2) 모든 individual에 대한 dummy variable을 회귀식에 추가 

m2 = sm.ols(formula = "lifeExp ~ logGDPpercap + C(country)", 
            data = gm).fit()
m2.summary()

표 해석 

  • logGPDpercap의 coef = 9.769
  • R2 = 0.846

3) regression의 coefficient를 해석하는 방법

(1) coefficient 해석 

logGDPpercap의 계수는 1),2) 모두에서 9.769이다 

-> """특정 국가에서 1인당 log GPD가 해당 국가의 일반적인 수치보다 1단위 더 높아졌을 때 

기대 수명은 그 나라의 평균 수명보다 9.769년만큼 높아진다. """

 

(2) R2 해석 

1)의 R2 = 0.410

= lifeExp_within의 변동 대비 잔차의 변동성 

= within R2으로, 2)의 R2 대비 낮음  

2)의 R2 = 0.846

= lifeExp의 전체 변동 대비 잔차의 변동성 

 

(3) fixed effect의 coefficient에 대한 해석 

2)의 regression에서 India에 대한 dummy variable의 coefficient = 13.971, Brazil에 대한 dummy variable의 coefficient = 6.318

 

Yit = β0 + β1 * Xit + βindia * Dindia + βbrazil * Dbrazil + .... + εit

  • βindia = 13.971
  • βbrazil = 6.318
  • Dindia: country = india인지 결정하는 dummy variable
  • Dbrazil: country = brazil인지 결정하는 dummy variable

-> Dindia = 1일 때 Yit = β0 + β1 * Xit + 13.971

Dbrazil = 1일 때 Yit = β0 + β1 * Xit + 6.318 

-> 따라서, 인도와 브라질의 1인당 GDP가 같다면 인도의 기대수명이 브라질의 기대수명보다 7.653(=13.971-6.318)만큼 길 것이다

 

'계량경제학 > 인과추론의 데이터과학' 카테고리의 다른 글

DID 관련 읽어볼 논문 리스트  (1) 2024.04.28
Two-way Fixed Effects  (0) 2024.04.14
PSM에 대한 논쟁  (0) 2024.04.04
Difference-in-Difference  (2) 2024.03.17
Research Design의 중요성  (0) 2024.03.16