Python/통계
단순회귀분석 예시
GinaKim
2024. 1. 14. 12:18
728x90
회귀분석은 독립변수가 종속변수에 영향을 미치는지 알아보고자 하는 인과관계 분석
- 귀무가설 : sepal_length가 sepal_width에 영향을 끼치지 않는다.
- 대립가설 : sepal_length가 sepal_width에 영향을 끼친다.
1. 우선 라이브러리 불러오기
import numpy as np
import matplotlib.pyplot as plt
import statsmodels
import statsmodels.formula.api as smf
2. 데이터 불러오기
import seaborn as sns
iris = sns.load_dataset('iris')
iris.head(5)
3. 회귀분석 결과를 요약 출력하기
model = smf.ols(formula = 'sepal_length ~ sepal_width', data = iris).fit()
model.summary()
4. 위 표에서 절편(상수항)과 기울기 출력하기
intercept = model.params.Intercept #절편 (상수항)
slope = model.params.sepal_width # 기울기
print(intercept, slope)
5. 회귀분석 결과 그림으로 그림
회귀식이 y = a(기울기)x+b(절편) 이므로 fig.axes[0].plot(x,slope*x+intercept)으로 식 작성
fig, ax = plt.subplots(1, 2, figsize=(10, 6), sharey=True)
x = np.linspace(0,5)
sns.scatterplot(data = iris, x = 'sepal_width', y = 'sepal_length', ax = ax[0])
fig.axes[0].set_title("The best-fitting regression line")
fig.axes[0].set_xlabel("sepal_width (cm)")
fig.axes[0].set_ylabel("sepal_length (cm)")
fig.axes[0].plot(x,slope*x+intercept)
plt.show()
=> 결론 : p값이 0.05보다 크므로 귀무가설을 채택하지만, 분산이 너무 커서 불확실성이 크다고 봄(통계적 검정이 불확실)
분산이 큰 경우, 표본에서 얻은 통계량이 실제 모집단의 특성을 잘 반영하지 않을 가능성이 높아지기 때문에, 다른 통계적 방법이나 모델 개선이 필요 ( 추가적인 조사, 적절한 모델 선택, 또는 더 큰 표본을 사용하여 불확실성을 감소시키는 등의 방법을 고려)
728x90