머신러닝의 모든 것 - 2주차
2주차 스터디의 주제는 ‘Regression’ 이였습니다.
“세상의 모든 문제는 하나의 직선으로 그상관 관계를 표현할 수 있다” 라는 개념에서 파생된 회귀!
머신러닝에 있어서는 가장 중요하면서도 가장 간단한 개념이 아닐까 싶은데요!
바로 시작하겠습니다.
Regression-python 실습
모델을 만들 때 가변수는 하나만!
(여러개를 만들면 각각의 효과를 모델이 구분을 할 수가 없는 가변수의 함정에 빠지게 됨.)
큰 데이터 집합인 경우 눈으로 결측값을 찾기 힘드므로 함수를 이용해야 함
Simple Linear Regression
최소제곱법을 이용해서 회귀선을 결정함
Training the Simple Linear Regression model on the Training set

sklearn.linear_model에서 LinearRegression 라이브러리를 가져오고
객체 생성을 해주고
fit함수를 통해 데이터를 넣어 모델을 학습시킬 수 있다.
Predicting the Test set results

LinearRegression의 predict함수를 이용해서 예측값을 가져올 수 있다.
Visualizing the Training set results

plt의 scatter함수(X좌표,Y좌표)를 이용해 그래프에 데이터를 점으로 찍을 수 있음.
plt의 plot함수를 이용해 곡선을 만들 수 있는데 여기서는 직선의 형태가 나옴.
Visualizing the Test set results

두번 째 줄에 test세트를 이용하지 않고 train 세트를 이용한 이유는 선형모델이므로 우리가 예측한 y_pred 가 train set를 fit해 만든 선형 모델인 저 파란 직선에 위치하기 때문이다
Multiple Linear Regression
Building A Model
5 methods of buding models:
- All-in
- Prior knowledge: 사전지식으로 어떤 변수들이 진짜 원인인지 알고 있다면 그냥 모델을 만들면 됨
- You have to: 프레임워크, 정해진 틀이 있기 때문에 무조건 써야하는 부분
- Preparing for Backward Elimination
- Backward Elimination
Step1: Select a signifacance level to stay in the model (e.g. SL= 0.05)
Step2: Fit the full model with all possible predictors
Step3: Consider the predictor with the higehst P-value. If P>SL, go to STEP4, otherwise go to FIN
Step4: Remove the predictor
Step5: Fit model without the variables
- Forward Selection
Step1: Select a signifacance level to stay in the model (e.g. SL= 0.05)
Step2: Fit all simple regression models ~ Select the one with the lowest P-value
Step3: Keep this variable and fit all possible models with one extra predictor added to the one(s) you already have
Step4: Consider the predictor with the lowest P-value. If P<SL, go to STEP3, otherwise go to FIN
- Bidirectional Elimination
Step1: Select a significance level to enter and to stay in the model e.g.: SLENTER = 0.05, SLSTAY = 0.05
Step2: Perform the next step of Forward Selection (new variables must have: P < SLENTER to enter)
Step3: Perform ALL steps of Backward Elimination (old variables must have P < SLSTAY to stay)
Step4: No new variables can enter and no old variables can exit
- Score Comparison
Step1: Select a criterion of goodness of fit (e.g. Akaike criterion r^2)
Step2: Construct ALL Possible Regression Models: total combinations
Step3: Select the one with the best criterion
Data Processing

One-Hot Encoding

Splitting the dataset into the Training set and Test set

다중 선형 회귀 클래스에서 자체적으로 계수를 이용해 각 변수를 조절하기에 가변수의 함정을 생각할 필요가 없다!
위의 building a model 의 스텝들을 직접 밟을 필요가 없다(자동으로 라이브러리에서 계산을 해줌)
나중에 그저 모델 선택을 통해 더 좋은 것을 고르면 됨
Training the Multiple Linear Regression model on the Training set

단순 선형 회귀 모델 만들 때와의 코드와 동일함.
LinearRegression 함수에서 자동으로 요소를 인지 후 다중 선형 회귀로 만든다
Predicting the Test set results

np.set_printoptions(precision=2) —> 소수점 아래 두 자리 수까지만 표시
np.concatenate((a,b),axis=1 or 0) —> a,b 배열을 합치기, axis=1 : 가로(옆으로) =0: 세로(밑으로)
배열.reshape(a,b) —> 배열을 a X b 형태로 재배열함
Polynomial Regression
다항 회귀는 다중 선형 회귀의 한 버전이다.
선형 회귀와 다항 회귀를 비교해보자!
Training the Linear Regression model on the whole dataset

Training the Polynomial Regression model on the whole dataset

다중 회귀 모델을 설계하는 법은 먼저 PolynomialFeatures(차수=n)으로 객체 생성 후 feature을 fit_traonsform 으로 다항의 요소로 만든다.
그리고 그 요소들로 선형 회귀 모델로 만들면 됨
Visualising the Linear Regression results

Visualising the Polynomial Regression results

선형 회귀에 비해 다항 회귀가 확연히 데이터를 잘 표현 하는 것을 볼 수 있음
PolynomialFeatures의 degree을 너무 높게 설정한다면 모델이 훈련데이터셋에 과적합될 수 있음

predict 함수를 쓸 때 인자로 드가는 것은 2차원 배열의 형태이므로 [[x]]의 형태로 써야함
Support Vector Regression
ε-Insensitive Tube
튜브안의 오류들은 신경을 안씀
튜브 밖의 점들에 대한 거리가 최소가 되도록 튜브를 결정한다.
데이터 집합의 성질에 따라 선형 커널 또는 비선형 커널을 이용해서 각각의 데이터셋에 맞게 모델을 설계할 수 있다.
Import the dataset



feature scaling 할 때 1차원 벡터를 넣을 수 없기에 2차원 배열로 만들어줌
Feature Scaling
SVR은 선형 회귀와 달리 요소를 조절해줄 계수가 없기 때문에 feature scale을 해줘야함


x, y의 평균과 표준편차가 다르기 때문에 각각 scaler를 구해줘야함
Training the SVR model on the whole dataset

sklearn.svm에 SVR 함수를 사용하는데 이 때 kernel=’rbf’를 사용한다.
rbf란 Radial Bias Function 의 약자로 방사형 기저 함수이다.
Predicting a new result

scaling 한 값을 넣어야 하므로 sc_X.transform을 사용하고 그 결과를 다시 원래 값으로 바꿔야 하므로 sc_y.inverse_transform을 사용한다.
regressor.predict(sc_X.transform([[6.5]]))값이 1차원 배열로 나오므로 reshape를 해줘서 2차원 배열로 만들어줘야한다 reshape에서 -1을 넣은 자리는 가능한 shape를 자동계산해서 반영해주는 방식이다.
Visualising the SVR results

scale 한 값을 역변환하는 것을 주의해서 input값에 넣어주어야 한다.
나머지는 선형회귀를 visualize하는것과 같음
Visualising the SVR results(for higher resolution and smoother curve)

해상도를 높이고 좀 더 부드러운 곡선을 위해서는 X를 0.1값으로 쪼개서 재구성해주고 그 값을 input값으로 넣어준다.
Decision Tree Regression
이는 상위 노드로부터 하위노드로 트리 구조를 형성해 데이터를 예측하는 방법이다.
보통 의사결정트리 회귀는 고차원의 데이터집합일 때 사용을 한다.
Data processing을 한 후,
Training the Decision Tree Regression model on the whole dataset

sklearn.tree의 DecisionTreeRegression 함수를 이용함
Predicting a new result

Visualising the Decision Tree Regression results(for higher resolution)

2차원일때만 시각화를 할 수 있음(보통 의사결정트리가 고차원의 데이터 집합일 때 사용하므로 직관적으로 의사결정트리가 어떠한 것인지 파악하기엔 좋지만 굳이..인듯 하다)
Random Forest Regression
RandomForest는 수많은 Decision Tree가 모여서 생성된다.
많은 feature들 중 랜덤으로 몇 개를 선택해서 결정트리를 만들고, 이를 반복해서 나온 많은 예측값들 중 가장 많이 나온 값을 최종 예측값으로 결정한다.
Random Forest Intuition
STEP1: Pick at random K data points from the Training set.
STEP2: Build the Decision Tree associated to these K data points.
STEP3: Choose the number of Ntree of trees you want to build and repeat STEPS 1&2
STEP4: For a new data point, make each one of your Ntree trees predict the valud of Y to for the data point in question, and assign the new data point the average across all of the predicted Y values.
코드가 Decision Tree Regression 과 거의 같음

sklearn.ensemble.RandomForestRegressor 을 사용해주면 의사결정트리→랜덤포레스트트리가 된다.
RandomForestRegressor(n_estimators=트리개수)
고차원 데이터 집합에 더 알맞는 회귀모형이다.

회귀 모델 성능 평가
잔차제곱합 Sum of Squared residuals
Total of Sum of Squred
이 1에 가까울수록 좋다.
p - number of regressors
n - sample size
본 스터디는 Udemy의 <【한글자막】 머신러닝의 모든 것 with Python, R> 강의를 활용해 진행됐습니다. 강의에 대한 자세한 정보는 아래에서 확인하실 수 있습니다.
프밍 스터디는 Udemy Korea와 함께 합니다.