Certificate/data analytics-Google

[multiple linear regression]No multicollinearity assumption, 다중공선성, VIF, interaction term, Ridge, Lasso, Elastic, feature selection, 전진선택법, 후진제거법, Extra-sum-of-squares, F-test, 분산분석

Olivia-BlackCherry 2023. 7. 24. 15:43

목차

    1. multiple linear regression

    A technique that estimates the relationship between one continuous dependent variable and two or more independent variables. 

    두 개 이상의 독립변수들이 종속변수에 영향을 미치는 관계를 측정하는 기술이다.

     

     

     

    2. Categorical data

    categorical data를 처리할 수 있는 방법은 두 가지가 있다. One hot encoding과 label encoding이다. linear regression에서 categorical data를 처리할 때는 one hot encoding 방법이 쓰인다. 

     

     

     

    one-hot encoding

    A data transformation technique that turns one categorical variable into several binary variables.

     

     

     

    3. Linear regression assumptions

    1) Linearity

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

     

    2) Independent observations

    Each observation in the dataset is independent.

     

    3) Normality

    The residuals are normally distributed.

     

    4) Homoscedasticity

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

     

    5) No multicollinearity assumption 다중공선성

    No two independent variables(X1, X2) can be highly correlated with each other.

    다중공선성이란 모형의 일부 독립변수가 다른 독립변수와 상관관계가 높을 때 발생하는데, 이는 coefficient의 variance를 증가 시켜 불안정하고 해석하기 어렵게 만들기 때문에 문제가 된다.

    다시 말해 multilinear regression을 만족하려면 두 개 이상의 독립변수들이 서로가 밀접하게 관련되어 있지 않아야 한다.

    = 이 변수들이 linearity하게 관련되지 않아야 한다는 뜻이다. 

     

    판단할 수 있는 방법은? VIF

    Variabce Inflation Factors(VIF) 분산 팽창계수

    Quantifies how correlated each independent variable is with all of the other independent variables.

    VIF를 확인해서 독립변수 간에 얼마나 관련이 높은지를 수치적으로 확인할 수 있다. 

    VIF 10 이하이면 다중 공선성 문제가 적다고 판단한다.

    VIF는 1부터 시작한다. 

     

    p-value 유의확률 

    결정계수 값은 높으나, 독립변수의 유의확률값이 커서 개별 독립ㅂ변수들이 유의하지 않다면 다중공선성을 의심해봐야 한다. 

     

    How to handle?

    - multicollinearity가 높은 변수를 삭제한다. 

    - 남아있는 데이터로 새로운 변수를 생성한다. 

    - 자료 부족이 원인이라면, 자료를 보완한다.

     

     

     

    4. interaction term

    A term that represents how the relationship between two independent variables is associated with changes in the mean of the dependent variable.

    두 개의 독립변수의 연관 관계가 종속 변수의 평균의 값에 영향을 미치는지를 말한다.

     

     

    5. Overfitting 오버피팅

    When a model fits the observaed or training data too specifically, and is unable to generate suitable estimates for the general population.

    R square이 데이터에 얼마나 적합한지를 알 수 있는 지수였다. 그런데 R square이 너무 높다는 뜻은, 모델이 rain data에 과적합되어있을 가능항이 높다.과적합된 모델은 일반 데이터에 대해 제대로 작동하지 못한다. 

     

     

    6. Bias-variance tradeoff

    Balance between two model qualities, bias and variance, to minimize overall error for unobserved data.

    통계와 머신러닝에서 매우 중요한 개념이다. 

     

    1) Bias

    Simplifies the model predictions by making assumptions about the variable relationships. A highly biased model may oversimplify the relationship, underfitting to the observed data, and generating inaccurate estimates.

    변수 관계를 가정하여 모형 예측을 단순화합니다. 고도로 편향된 모형은 관계를 지나치게 단순화하고 관측된 데이터에 적합하지 않으며 부정확한 추정치를 생성할 수 있습니다.

     

     

    2) Variance

    Model flexibility and complexity, so the model learns from exsting data. A model with high variance can overfit to observed data and generate inaccurate estimates for unseen data.

     

     

    3) 좋은 모델은?

    편향과 분산 모두를 낮추는 모델이다.

    어떻게 만들 수 있을까?

    ----> Regularized regression

     

     

     

     

    7. Regularization( Regularize regression)

    A set of regression techniques that shrinks regression coefficient estimates toward zero, adding in bias, to reduce variance. 

    회귀식의 회귀계수 값에 패널티를 부여하면서 low bias에 예측성능을 조절하는 것이다. 

    아래 세 가지의 regularized regression 기술 모두 우리가 만든 모델을 좀더 정확하게 만들어준다.

     

    1) Lasso Regression(L1) 

    y변수를 예측하는데 별로 중요하지 않은 x변수를 제거한다.

    유의미하지 않은 변수들에 대해 계수를 0에 가깝게 추정해 주어 변수 선택 효과를 가져온다. 

    RSS(잔체제곱합) + 패널티항(절대값)

     

    2) Ridge Regression(L2) 능형회귀

    The impact of less relevant variable is minimized but none of the variables will drop out of the equation.

    회귀식에서 큰 임팩트가 없고 관계 부족한 x변수의 영향력을 더욱 최소화시킨다. 그렇다고 제거하지는 않는다.

    그래서 모든 x변수를 포함하고자할 때 릿지는 좋은 해결책이 된다. 

    변수 선택이 불가능하고, 변수 간 상관관계가 높은 상황에서 좋은 예측 성능을 발휘한다.

    RSS(잔차제곱합) +패널티항(제곱)

     

    3) Elastic Regression

    큰 데이터셋인 경우, 종종 우리는 모델에서 변수를 없애야할지 말아야할지 확실히 모르는 경우가 있는데 이때 elastic regression을 쓴다. elastic regression은 lasso, ridge, 하이브리드형 lasso&ridge를 썼을 때 이점을 한번에 test해준다.

    상관관계가 큰 변수를 동시에 선택하고 배제하는 특성을 가진다. 

     

     

     

     

    8. Adjust R squared

    A variation of the R square regression evaluation metric that penalizes unnecessary explanatory variables.

    Adjust R squared는 필요없는 변수에 대해 패널티를 부여한 Rsquared이다.매우 복잡한 모델에서 많이 쓰이고, 다른 변수를 추가할지 아닌지에 대해 우리가 결정해야 한다. 

     

     

     

     

    9. variable selection=feature selection method

    The process of determining which variables or features to include in a given model

    표본에 대한 회귀선의 설명력이란?

    추정된 회귀식이 어느 정도 측정치들과 일치하는지의 정도

     

     

     

    1) Forward selection 전진선택법

    A stepwise variable selection process that begins with the null model, with 0 independent variables, considers all possible variables to add. It incorporates the independent variable that contributes the most explanatory power to the model. 

    절편만 있는 상수모형으로부터 시작해 중요하다고 생각되는 설명변수부터 차례로 모형에 추가

    추가적으로 적절한 변수가 있다면 추가하고 그렇지 않다면 추가하지 않음. 

    한번 추가했다면 제거할 수 X

     

     

    2) Backward elimination 후진제거법

    A stepwise variable selection process that begins with the full model, with all possible independent variables, and removes the independent variable that adds the least explanatory power to the model.

    독립변수 후보 모두를 포함한 모형에서 출발해서 제곱합의 기준으로 가장 작은 영향을 주는 변수부터 하나씩 제거하며, 더이상 유의하지 않은 변수가 없을 때까지 설명변수를 계속 제거한다. 

    한번 제거했다면 추가할 수 X

     

     

    3) Stepwiise method 단계별방법

    - 전진선택법에 의해 변수를 추가하면서 새롭게 추가된 변수와 비교하여 기존의 변수의 중요도가 약하다면, 과거의 변수를 제거하는 등 단계별로 추가 또는 제거되는 변수 여부를 검토하는 방법이다. 

     

     

     

    ----> forward, backward elimination 모두 어떤 스레드홀드에서 변수를 넣어야하거나 제거해야할지를 결정해야 한다. 가장 일반 적인 테스트가 F테스트이다.

    4) Extra-sum-of-squares F-test 분산분석

    Quantifies the difference between the amount of variance that is left unexplained by a reduced model that is explained by the full model.

    F는 분산비율 값이다. 

     

     

     

    Python예제 살펴보기

    Penguins Data

     

    Model  construction

    train, test 셋으로 분리

    X_train, X_test, y_train, y_test = train_test_split(penguins_X, penguins_y, 
                                                        test_size = 0.3, random_state = 42)

     

    categrical value는 formula에 C() 구조로 넣을 수 있다. variable들은 +로 연결한다. 

    ols_formula = "body_mass_g ~ bill_length_mm + C(gender) + C(species)"

     

    ols_data는 X_train, y_trian 값을 합친 것이고 , OLS 모델을 학습시키고 summary하면 아래와 같은 결과가 나온다.

    ols_data = pd.concat([X_train, y_train], axis = 1)
    
    OLS = ols(formula = ols_formula, data = ols_data)
    model = OLS.fit()
    model.summary()

     

     

    데이터교육, 파이썬. 다중회귀분석