Study_note(zb_data)/Machine Learning
์คํฐ๋๋ ธํธ (Regression)
KloudHyun
2023. 9. 28. 18:13
๐ ํ์ต์ ์ข ๋ฅ
๐ป์ง๋ ํ์ต์๋ ๋ถ๋ฅ์ ํ๊ท๊ฐ ์๋ค
๐ป๋น์ง๋ ํ์ต์ ์ข ๋ฅ
๐ ์ ํ ํ๊ท์ ๋ํด์ ์์๋ณด์
๐ปOLS
- Ordinary Linear Least Square์ ๊ธฐ๋ณธ ๊ฐ๋ ์ ๋ฆฌ
-
๐ปOLS ์ค์ตํ๊ธฐ (Code๋ก ์ฝ๊ฒ ํ ์ ์๋ค!)
import pandas as pd
data = {'x':[1,2,3,4,5], 'y':[1,3,4,6,5]}
df = pd.DataFrame(data)
df
import statsmodels.formula.api as smf
lm_model = smf.ols(formula='y ~ x', data=df).fit() # y=ax+b <- ('y ~ x')
lm_model.params
>>>>
Intercept 0.5
x 1.1
dtype: float64
๐ปlmplot ์ฌ์ฉํ์ฌ ์ง์ ์ ๊ทธ๋ ค๋ณด์
import matplotlib.pyplot as plt
import seaborn as sns
plt.figure(figsize=(10, 7))
sns.lmplot(x='x', y='y', data=df)
plt.xlim([0, 5])
plt.show()
๐ป์์ฐจ ํ๊ฐ
- ์์ฐจ๋ ํ๊ท ์ด 0์ธ ์ ๊ท๋ถํฌ๋ฅผ ๋ฐ๋ฅด๋ ๊ฒ์ด์ด์ผ ํ๋ค
- ์์ฐจ ํ๊ฐ๋ ์์ฐจ์ ํ๊ท ์ด 0์ด๊ณ , ์ ๊ท๋ถํฌ๋ฅผ ๋ฐ๋ฅด๋์ง ํ์ธํด์ผํ๋ค.
# ์ ์ ์ OLS ํ์ธํ๋ model๋ก ๊ฐ์์ ์์ฐจ๋ฅผ ํ์ธ
resid = lm_model.resid
resid
>>>>
0 -0.6
1 0.3
2 0.2
3 1.1
4 -1.0
dtype: float64
๐ป๊ฒฐ์ ๊ณ์ R-Squared
import numpy as np
mu = np.mean(df['y'])
y= df['y']
y_hat = lm_model.predict()
np.sum((y_hat - mu)**2 / np.sum((y-mu)**2))
>>>>
0.8175675675675673
lm_model.rsquared
>>>>
0.8175675675675673
๐ป์์ฐจ์ ๋ถํฌ๋ ํ์ธ
sns.distplot(resid, color='black')