시작하기무료로 시작하기

회귀의 R-제곱 살펴보기

R-제곱은 데이터가 회귀선에 얼마나 잘 맞는지를 나타내므로, 단순 회귀에서 R-제곱은 두 변수의 상관관계와 연관이 있습니다. 특히 상관계수의 크기는 R-제곱의 제곱근이고, 상관계수의 부호는 회귀계수의 부호와 같습니다.

이번 연습에서는 R이나 SAS, MATLAB 같은 소프트웨어에 있는 많은 통계 모델링과 검정을 수행하는 통계 패키지 statsmodels를 사용해 보겠습니다.

두 개의 시리즈 xy의 상관관계를 계산한 다음, statsmodels.api 라이브러리의 OLS(y,x) 함수를 사용해 yx에 대해 회귀하세요(주의: 종속 변수, 즉 오른쪽 항의 변수 y가 첫 번째 인수입니다). 대부분의 선형 회귀에는 절편(회귀식 \(\small y_t=\alpha + \beta x_t + \epsilon_t\)에서의 \(\small \alpha\))인 상수가 포함됩니다. OLS() 함수로 상수를 포함하려면 회귀의 오른쪽 항에 1로 된 열을 추가해야 합니다.

statsmodels.api 모듈은 sm으로 임포트되어 있습니다.

이 연습은 강의의 일부입니다

Python으로 배우는 시계열 분석

강의 보기

연습 안내

  • .corr() 메서드를 사용해 xy의 상관계수를 계산하세요.
  • 회귀를 실행하세요:
    • 먼저 Series x를 DataFrame dfx로 변환하세요.
    • sm.add_constant()로 상수를 추가해 dfx1에 할당하세요.
    • sm.OLS().fit()을 사용해 ydfx1에 회귀하세요.
  • 회귀 결과를 출력하고 R-제곱과 상관계수를 비교하세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

# Import the statsmodels module
import statsmodels.api as sm

# Compute correlation of x and y
correlation = ___
print("The correlation between x and y is %4.2f" %(correlation))

# Convert the Series x to a DataFrame and name the column x
dfx = pd.DataFrame(x, columns=['x'])

# Add a constant to the DataFrame dfx
dfx1 = sm.add_constant(___)

# Regress y on dfx1
result = sm.OLS(___, ___).fit()

# Print out the results and look at the relationship between R-squared and the correlation above
print(result.summary())
코드 편집 및 실행