선형 회귀의 기초

scikit-learn으로 배우는 지도 학습

George Boorman

Core Curriculum Manager, DataCamp

회귀 메커니즘

  • $y = ax + b$

    • 단순 선형 회귀는 하나의 특성 사용

      • $y$ = 타깃

      • $x$ = 단일 특성

      • $a$, $b$ = 모델의 매개변수/계수 - 기울기, 절편

  • $a$와 $b$는 어떻게 선택할까요?

    • 임의의 주어진 선에 오류 함수를 정의

    • 오류 함수를 최소화하는 선을 선택

  • 오류 함수 = 손실 함수 = 비용 함수

scikit-learn으로 배우는 지도 학습

손실 함수

scatter plot

scikit-learn으로 배우는 지도 학습

손실 함수

regression line running from bottom left to top right, through the middle of the observations

scikit-learn으로 배우는 지도 학습

손실 함수

red lines from the regression line to each observation

scikit-learn으로 배우는 지도 학습

손실 함수

the red lines represent residuals

scikit-learn으로 배우는 지도 학습

손실 함수

arrow highlighting a postive arrow, as the observation is above the regression line

scikit-learn으로 배우는 지도 학습

최소제곱법

second arrow pointing to a residual beneath the regression line, representing a negative residual

$RSS = $ $\displaystyle\sum_{i=1}^{n}(y_i-\hat{y_i})^2$

최소제곱법(OLS): RSS 최소화

scikit-learn으로 배우는 지도 학습

고차원에서의 선형 회귀

$$ y = a_{1}x_{1} + a_{2}x_{2} + b$$

  • 선형 회귀 모델을 여기에 학습시키려면:
    • 3개의 변수를 지정해야 함: $ a_1,\ a_2,\ b $
  • 고차원에서는:
    • 다중 회귀로 알려짐
    • 각 특성의 계수와 변수 $b$를 지정해야 함

$$ y = a_{1}x_{1} + a_{2}x_{2} + a_{3}x_{3} +... + a_{n}x_{n}+ b$$

  • scikit-learn도 같은 방식으로 작동:
    • 특성과 타깃, 두 개의 배열을 전달
scikit-learn으로 배우는 지도 학습

모든 특성을 사용한 선형 회귀

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
reg_all = LinearRegression()
reg_all.fit(X_train, y_train)
y_pred = reg_all.predict(X_test)
scikit-learn으로 배우는 지도 학습

R-제곱

  • $R^2$: 특성으로 설명되는 타깃 값의 분산을 정량화 함

    • 값은 0에서 1{{1}}까지
  • 높은 $R^2$:

regression line at 45 degrees running from bottom left to top right and close to all the observations

  • 낮은 $R^2$:

regression line running horizontally, where observations are spread out away from the line

scikit-learn으로 배우는 지도 학습

scikit-learn의 R-제곱

reg_all.score(X_test, y_test)
0.356302876407827
scikit-learn으로 배우는 지도 학습

평균 제곱 오차와 평균 제곱근 오차

$MSE = $ $\displaystyle\frac{1}{n}\sum_{i=1}^{n}(y_i-\hat{y_i})^2$

  • $MSE$는 목표 단위의 제곱으로 측정됨

$RMSE = $ $\sqrt{MSE}$

  • 대상 변수와 동일한 단위로 $RMSE$ 측정
scikit-learn으로 배우는 지도 학습

scikit-learn의 RMSE

from sklearn.metrics import root_mean_squared_error

root_mean_squared_error(y_test, y_pred)
24.028109426907236
scikit-learn으로 배우는 지도 학습

연습해 봅시다!

scikit-learn으로 배우는 지도 학습

Preparing Video For Download...