Certificate/data analytics-Google

[linear regression] residual, SSR, OLS, linear regression assumption, linearity, normality, independent observation, Homoscedasticity, pairplot, r-squared, 결정계수

Olivia-BlackCherry 2023. 7. 22. 23:24

목차

    <simple linear regression>

    A technique that estimates the linear relationship between one independent variable X, and one continuous dependent variable Y.

     

    1. Linear regression equation 방정식

    1) Best fit line

    아래 식으로 수많은 선을 그릴 수 있지만 우리는 손실함수를 가장 최소로 하는 선을 그리고 싶다. 

     

     

    2) error

    에러를 찾아야 한다 

    Residual 

    The difference betwe  en observed or actual values and the predicted values(예상되는 값) of the regression line

    엡실론= E

     

     

    3) Sum of Suared Residuals(SSR) 

     

     

     

    2. Ordinary least squeares estimation technique OLS 최소제곱추정량

    A method that minimizeds the sum of squared residuals to estimate parameters in a linear regression model 

    SSR이 최소가 되도록 선형회귀 모델의 파라미터를 측정하는 방법이다. 

     

     

     

    3. Four linear regression assumptions

    회귀모형에서 오차항에 대한 정규성, 등분산성, 독립성을 가정한다. 이런 가정이 성립해야 회귀분석 결과가 타당해진다. 

    1) Linearity assumption 선형성

    Each predictor variable X is linearly related to the outcome variable Y

    독립변수의 변화에 따라 종속변수도 변화하는 선형인 모형이다.

    산점도 그래프 그리는 것이 가장 빠름

     

     

    2) Normality 정상성

    The residuals or errors are normally distributed.

    잔차항이 정규분포를 이뤄야 한다.

     

     qunatile-quantile plot

     

     

     

    3) Independent observations 독립성

    잔차와 독립변수의 값이 관련되어 있지 않다.

    Each observation in the dataset is independent.

    no pattern, randomly. random cloud.

    ---> 데이터가 어떻게 수집되어 있는지를 파악하는 것이 중요하다. 

     

    4) Homoscedasticity 등분산성

    The variation of the residuals is constant or similar across the model.

    오차항들의 분포는 동일한 분산을 갖는다. 

    Having the same scatter.

     random cloud.

     

     

    4. Build a linear regression model in Python

    파이썬으로 간편하게 OLS를 이용해서 B1, B0 파라미터를 알 수 있다. 

     

     

    1) pairplot()

    sns.pairplot(penguins_final)

    짝을 이뤄서 스캐터그래프를 그려준다.

    두 변수 사이에 관계를 scatterplot matrix로 일괄 표현해준다. 

    이 pairplot을 이용해서 선형회귀 가정을 판단해보자.

     

     Linearity

    bill_length와 body_mass는 correlated 하다. bill length와 flipper length도 correlated하다. flipper length와 body mass 역시 correlated하다.

     

     Normality

    빨강색으로 칠해진부분은 대략적으로 continuous variable의 분포를 보여준다.분포가 정규형을 따르므로 잔차항도 정규분포일 것이라 가정할 수 있다. linear assumption인 정상성을 만족한다고 볼 수 있지만, 차후에 모델을 만들고 난 후에 잔차항에 대한 그래프를 그려서 다시 한번 확인해보도록 하자. 

     

     independent observations

    independent observations assumption은 데이터 수집에 관한 것이다. 

    각각의 모두 다른 펭귄들이 대상이 되므로, 이 펭귄들이 서로에게 영향을 미친다고 할 수는 없다.

     

     Homoscedasticity

    ----> 모델을 만들고 그래프를 그리기 전에는 알 수가 없다.

     

     

    2) regplot

    진한 선이 가장 fit된 선이고, 그 옆으로 shade 된 부분이 불확실한 부분이다.

    bill length, body mass가 강한 상관관계가 있으므로 이것을 x, y변수로 삼도록 한다.

    ols_data = penguins_final[["bill_length_mm", "body_mass_g"]]
    sns.regplot(x = "bill_length_mm", y = "body_mass_g", data = ols_data)

     

     

    3) linear regression formula

    y_vairable ~ x_variable

    ~ 가 중요한 의미를 갖는다. 컴퓨터가 이해할 수 있는 formula로 적어줘야 한다. 

    ols_formula = "body_mass_g ~ bill_length_mm"

     

    해당 라이브러리를 import 한다.

    from statsmodels.formula.api import ols

     

    ols()함수로 OLS 모델을 만들고, 데이터를 학습시킨다.

    ols(formula=, data=)
    fit()
    OLS = ols(formula = ols_formula, data = ols_data)
    model = OLS.fit()

     

    summary()

    모델의 정보를 요약해준다. 

    model.summary()

     

    모델에서 intercept와 slope에 해당하는 가장 적합한 두 개의 coefficient가 나왔다

     

     

    4) check model assumption---> 잔차 분석

    To justify using simple linear regression, check that the four linear regression assumptions are not violated.

    여기까지 하면, 선형회귀 공식이 도출되었다. 

    하지만 여기서 멈추면 안되고 linear regression assumtion 중에 해결되지 않은 부분인 normality, homoscedasticity assumption에 대해 잔차를 검증하면서 다시 확인해보자.  

     

    # X variable
    X = ols_data["bill_length_mm"]
    
    # 예측값
    fitted_values = model.predict(X)
    
    #잔차
    residuals = model.resid

     

      scatterplot

    residual이 랜덤이고 등분산성을 띈다. 독립성 역시 침해되지 않은 것을 확인한다.

    # Import matplotlib
    import matplotlib.pyplot as plt
    fig = sns.scatterplot(x=fitted_values, y=residuals)
    
    # Add reference line at residuals = 0
    fig.axhline(0)
    
    # Set x-axis and y-axis labels
    fig.set_xlabel("Fitted Values")
    fig.set_ylabel("Residuals")
    
    # Show the plot
    plt.show()

     

      histogram

    잔차가 정규분포와 가까운 것을 보고, 정상성 가정을 충족한다고 볼 수 있다. 

    하지만 히스토그램이 완벽히 정규분포를 이루지 않고 오른쪽에 skew가 발생하고 있으므로, QQplot을 통해 다시 한번 재확인을 해보자.

    import matplotlib.pyplot as plt
    fig = sns.histplot(residuals)
    fig.set_xlabel("Residual Value")
    fig.set_title("Histogram of Residuals")
    plt.show()

     

     

     QQplot

    import matplotlib.pyplot as plt
    import statsmodels.api as sm
    fig = sm.qqplot(model.resid, line = 's')
    plt.show()

     

     

     

    5. Evaluate linear regression model using metrics

    PACE

    1. plan : problem에 대해 생각하고 사용 가능한 데이터를 확인했다.
    2. analyze: 해당 데이터를 더 잘 알기 위해서 EDA를 통해 데이터를 분석하고, 빌드할 모델에 대한 assumptions들을 체크했다.
    3. construct: 1) 모델빌딩하고 파라미터를 찾았다. 2) 해당 모델을 평가한다.
    4.execute

     

     

    1) Model evaluation

    데이터 분석에서 매우 중요한 과정이다. 내가 만든 regression model에 대해 제대로 평가하고 해석하는 것이 이 모델의 퍼포먼스와 정확도를 이해하는데 도움을 주기 때문이다. 

     

    예를 들어보자. 

    만약 빌드한 모델의 결과로 y= 141x -1707이라는 선형회귀식을 도출했다고 하자. 

    아무리 모델이 좋다해도, 실제 데이터값과 예측값 사이에는 차이가 발생한다.  

     

    model의 summary를 다시 살펴보자. 

     

     

    2) confidence band

    The area surrounding the line that describes the uncertainty around the predicted outcome at every value of X

    ---> 데이터분석가는 언제나 모델의 부정확도에 관한 정보도 함께 제공해야 한다.

     

     

    3) Common evaluation Metrics

     R-squared 결정계수

    = The coefficient of determination 결정계수

    Measures the proportion of variation in the dependent variable, Y, explained by the independent variables, X

     

    아래의 그래프를 보면 파란색 선이 만들어진 회귀 모델이다. 그런데 실제 데이터가 놓여진 위치를 보면, 데이터들이 완벽히 선과 일치하지 않는다는 것을 알 수 있다. 

    R스퀘어는 X 변수의 변동이 Y 변수의 변동을 얼마나 설명하는지를 확인하는데 도움이 된다.

     

    0< R-squared <1

    범위를 갖는데 1이면 완벽히 일치한다. 0이면 완벽히 다르다는 것을 알려준다. 1에 가깝게 될 수록 효율적인 모델이다. 

     

     

     

     

      hold-out sample 

    A random sample of observed data that is not used to fit the model

    학습되지 않은 샘플들을 가지고 해당 모델이 얼마나 잘 작동하는지 평가할 수 있다. 

     

     

     

    6. Interpreting results

    -communication이 가장 중요하다. 

     

    데이터교육, 데이터분석, 선형회귀