반응형

/* 2017.6.29

파이썬 선형회귀분석 

by 3개월

*/


파이썬 선형회귀분석 (sklearn 라이브러리 사용)



필요한 라이브러리 임포트

import pandas as pd
from sklearn import datasets, linear_model
import matplotlib.pyplot as plt
import numpy as np


데이터 모양 출력

birth = pd.read_csv("C:/workspace/python/data/birth.csv")
print birth.head()
   case  gram  weeks  smoke
0     1  3147     40      0
1     2  2977     41      0
2     3  3119     38      0
3     4  3487     38      0
4     5  4111     39      0


데이터를 간단히 설명하면 산모의 임신주차(weeks)와 흡연여부(smoke)변수를 통해 태아의 몸무게(gram)을 예측하기 위한 예제 데이터입니다. 관측치(row)는 100개가 있습니다.



데이터 나누기

# split data
print len(birth)
birth_train = birth[0:90]
birth_test = birth[91:100]


90%의 데이터를 트레이닝 데이터, 10%의 데이터를 테스트 데이터로 쓰겠습니다.


# basic linear regression
model1 = linear_model.LinearRegression()
x_vars1 = ["weeks", "smoke"]
model1.fit(birth_train[x_vars1], birth_train["gram"])
print model.coef_, model.intercept_

x = np.linspace(25,50,100)

plt.scatter(birth_train['weeks'], birth_train['gram'], c=birth_train["smoke"])
plt.plot(x, x*model.coef_[0]+model.coef_[1]+model.intercept_)
plt.plot(x, x*model.coef_[0]+model.intercept_)
plt.show()


첫 번째 모델 : gram = W1*weeks + W2*smoke + Intercept



우선 교호작용을 고려하지 않은 첫번째 모델입니다. smoke는 0, 1만 갖는 이진 변수이므로 smoke=1 일 때만, W2*smoke는 하나의 상수가 됩니다. smoke=0 인 경우 W2*smoke는 0입니다. 그러므로 smoke=1일 때 W2 값만큼 회귀식의 절편이 이동합니다.


[ 123.76004061 -283.69489986] -1504.60207489


다음 결과를 통해 W1 = 123.76004, W2 = -283.69, Intercept = -1504.60임을 알 수 있습니다.




따라서 결과 플롯은 위와 같습니다. smoke=1일때가 밑에있는 주황색 선입니다. 또한 보라색 점은 smoke=0인 사람을 나타낸 것이고 노란색 점은 smoke=1 인 사람을 나타낸 것입니다.



교호작용을 고려한 모델


# with interaction term
birth["weekssmoke"] = birth["weeks"]*birth["smoke"]
birth_train = birth[0:90]
birth_test = birth[91:100]
model2 = linear_model.LinearRegression()
x_vars2 = ["weeks", "smoke", "weekssmoke"]
model2.fit(birth_train[x_vars2], birth_train["gram"])
print model.coef_, model.intercept_

x = np.linspace(25,50,100)

plt.scatter(birth_train['weeks'], birth_train['gram'], c=birth_train["smoke"])
plt.plot(x, x*(model.coef_[0]+model.coef_[2])+model.coef_[1]+model.intercept_)
plt.plot(x, x*model.coef_[0]+model.intercept_)
plt.show()


교호작용은 effect modification 이라고도 불리며, 한 변수에 의해 다른 변수의 효과가 변하는 것을 말합니다. 이 경우 모델의 식은 아래와 같습니다.



두 번째 모델 : gram = W1*weeks + W2*smoke + W3*(weeks*smoke) + Intercept


왜 weeks*smoke를 곱한 텀을 넣어주나면 이를 통해 weeks의 gram에 대한 effect를 변화시킬 수 있기 때문입니다. smoke=1인경우 (W1+W3)*weeks가 되기 때문에 smoke에 의한 weeks의 effect의 변화를 고려할 수 있게 됩니다.



[  132.01926109  1316.00125169   -41.03706632] -1820.91949297

위 결과를 통해 coefficient와 intercept를 알 수 있습니다.




Mean Squared Error 구하기

print "Model1 Training Mean squared error: %.2f" % np.mean((model1.predict(birth_train[x_vars1]) - birth_train['gram']) ** 2)
print "Model2 Training Mean squared error: %.2f" % np.mean((model2.predict(birth_train[x_vars2]) - birth_train['gram']) ** 2)

print "Model1 Test Mean squared error: %.2f" % np.mean((model1.predict(birth_test[x_vars1]) - birth_test['gram']) ** 2)
print "Model2 Test Mean squared error: %.2f" % np.mean((model2.predict(birth_test[x_vars2]) - birth_test['gram']) ** 2)

마지막으로 Training MSE와 test MSE를 구하는 코드입니다.


Model1 Training Mean squared error: 227136.45
Model2 Training Mean squared error: 223972.58
Model1 Test Mean squared error: 220233.22
Model2 Test Mean squared error: 226638.72


반응형
반응형