Machine Learning/Models (with codes)

Simple Linear Regression Model (w/scikit-learn)

metamong 2022. 4. 16.

** 저번 포스팅에서 단순선형회귀 '개념'에 대해 자세히 공부했었다! 😚

 

Simple Linear Regression (concepts)

** 우리는 저번시간에 Supervised Learning - Regression - Linear Regression까지 concepts에 대해 배웠다 (↓↓↓↓↓↓ 하단 포스팅 참조 ↓↓↓↓↓↓) ML Supervised Learning → Regression → Linear Regr..

sh-avid-learner.tistory.com

 

** 이젠 직접 scikit-learn을 사용하여 직접 단순선형회귀모델을 만들어보자. 코드구현!

1. - feature matrix & label vector -

👆 먼저 scikit-learn library를 활용한 모델에 집어넣기 전에 feature matrix(X) & label vector(y) 준비

 

 

feature matrix특성행렬로 주로 X로 표현하며 2차원 행렬 (여러 feature가 있다면..!)

→ shape) [n_samples, n_features]

(-- 그러나 단순선형회귀의 경우 feature는 1개이기에 X는 1차원 행렬임 --)

 

label vector타겟배열로 y로 주로 표현하며 우리가 모르는 data에 대한 알고자 하는 결괏값들의 배열

→ shape) [n_samples]

 

🤙 주어진 tabular data → matrix와 같은 위의 변환이 많아서 선형대수학을 배우는 이유..! 🤙

2. Step-by-Step (in using Scikit-learn estimator API)

👨 앞으로 사용하게 될 Scikit-learn 관련 모든 estimator class는 아래와 같은 과정을 거칠지어니... 기억! 👨

 

① 'Choose a class of model by importing the appropriate estimator class from Scikit-Learn.'

 어떤 model 부류를 사용할 지 모델 부류를 정한다!

(ex) 선형모델을 만들고 싶으면 sklearn의 linear_model을 import하면 됨!)

 

② 'Choose model hyperparameters by instantiating this class with desired values.'

 모델의 인자를 설정하는게 ❌ (ML term에서 통용되는 부분 - 헷갈리지 말기)

→ model 부류(class)를 선택했다면 해당 부류의 어떤 모델을 선택할 지 고르는 단계

(ex) 선형모델을 import 했다면 다양한 선형 모델 중 한 종류의 model을 import 한다! - 예를 들어 import LinearRegression)

→ 여기서 model을 고르는 과정에서 cross-validation 기법을 사용하기도 함

 

③ 'Arrange data into a features matrix and target vector following the discussion above.'

 위 1.에서 배운 대로 모델에 들어갈 data 두 종류 X와 y 준비!

 

④ 'Fit the model to your data by calling the fit() method of the model instance.'

→ 이젠 주어진 X와 y를 model에 fitting해서 model 완성!

 

⑤ 'Apply the Model to new data'

≫ For supervised learning, often we predict labels for unknown data using the predict() method.

≫ For unsupervised learning, we often transform or infer properties of the data using the transform() or predict() method.

→ 지도학습, 비지도학습 학습 종류에 따라 약간 다르다! - 하튼 새로운 data를 집어넣어 완성한 모델에 의거해 예측값을 생성하자!

 

👊 이 5가지 step-by-step 차례대로 '단순선형회귀' code 구현 시작 👊

3. Simple Linear Regression model (w/Scikit-learn)

> 필요한 library - module import

 

from sklearn.linear_model import LinearRegression

 

> regression model 객체 생성

 

model = LinearRegression()

 

「LinearRegression() docu」

https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html 

 

class sklearn.linear_model.LinearRegression(*, fit_intercept=True, normalize='deprecated', copy_X=True, n_jobs=None, positive=False)

 

→ 해당 linear regression은 Ordinary least squares Linear Regression (OLS기법으로 결정되는 model)

 

'LinearRegression fits a linear model with coefficients w = (w1, …, wp) to minimize the residual sum of squares between the observed targets in the dataset, and the targets predicted by the linear approximation.'

 

👁 중요! 우리는 model을 만들기 위한 일종의 model의 판을 뜬 것이지 아직 model 완성 안했다. 헷갈리지 말기👁

 

③> 두 종류 X와 y 준비! (X와 y의 데이터 형태에 주의!)

 

ex) 예시로 seaborn 내장 geyser dataset을 가져왔고 X(간헐천 대기시간)에 따른 y(간헐천 지속시간)에의 영향이 있는 지, 즉 대기시간과 지속시간에 선형관계가 존재하는 지 model을 구축하여 관계를 따져보자!

 

#preparing X & y
#converting to ndarray
geyser = sns.load_dataset('geyser')

X = geyser['waiting'].values[:,np.newaxis]
print('X\'s shape is ', np.shape(X)) #(272,1)

y = geyser['duration'].values
print('y\'s shape is ', np.shape(y)) #(272,)

 

🤘 쉽게 시각화 & 모델링을 하기 위해 series 형태의 data를 ndarray형태로 모두 변환한다.

.values를 붙이면 자동으로 ndarray형태로 변환됨

→ 이 때 X의 경우 np.newaxis를 붙여서 한 차원 늘려 표현 (2D array)

 

- model fitting & predicting을 위해서는 2D-array로 반드시 변환해야 함을 docu에서 알려주고 있다 -

(당연히 SLR은 feature가 1개이므로 단순히 np.newaxis를 붙여 2D-array 껍데기 형태로만 data를 변환해줌)

 

 

④> 이제 model 객체에 data를 fitting해서 model을 완성하자! (+coef & intercept 확인하기)

 

model.fit(X, y)

 

'This fit() command causes a number of model-dependent internal computations to take place, and the results of these computations are stored in model-specific attributes that the user can explore. In Scikit-Learn, by convention all model parameters that were learned during the fit() process have trailing underscores'

(편의를 위해 model의 attribute는 모두 밑줄이 끝에 들어가 있다는 뜻)

 

> 기울기 확인하기 <

 

model.coef_
#array([[0.07562795]])

 

'Estimated coefficients for the linear regression problem. If multiple targets are passed during the fit (y 2D), this is a 2D array of shape (n_targets, n_features), while if only one target is passed, this is a 1D array of length n_features.'

→ 선형 직선의 기울기는 약 0.07정도

 

> 절편 확인하기 <

 

model.intercept_
#array([-1.87401599])

 

'Independent term in the linear model.' (independent - 즉 x값에 영향을 받지 않는 항인 '절편'을 말함 ㅇㅇ)

→ 선형 직선의 y절편은 약 -1.87정도

 

> fitting한 단순선형회귀모델 시각화! <

 

 positive relationship을 가짐을 육안으로 확인 가능

 

#import libraries
import seaborn as sns
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from sklearn.linear_model import LinearRegression #lr modeling

#lr 
model = LinearRegression()

#preparing X & y
#converting to ndarray
geyser = sns.load_dataset('geyser')

#X = geyser['waiting'].values
X = geyser['waiting'].values[:,np.newaxis]
print('X\'s shape is ', np.shape(X)) #(272,1)

y = geyser['duration'].values
print('y\'s shape is ', np.shape(y)) #(272,)

#fitting
model.fit(X, y)

print('model\'s coef is ', model.coef_)
print('model\'s intercept is ', model.intercept_)

#visualization
plt.style.use("grayscale")
plt.rcParams["figure.figsize"] = (5,5)
plt.rcParams["grid.linewidth"] = 1

title_font = {
    'fontsize': 20,
    'fontweight' : 'bold',
}
plt.title('Simple Linear Regression model', fontdict=title_font, pad=17)
plt.scatter(X, y,color='#FD3115', s=20)

#predicting
plt.plot(X, model.predict(X),color='#310903',linewidth=4)

plt.xlabel('geyser waiting time')
plt.ylabel('geyser duration time')

plt.show()

 

- 출력결과 - 

더보기

X's shape is  (272, 1)
y's shape is  (272,)
model's coef is  [0.07562795]
model's intercept is  -1.8740159864107384

 

 

⑤> 이젠 interpolate or extrapolate 기법으로 새로운 data를 집어넣어 예측해보자..!

 

'Once the model is trained, the main task of supervised machine learning is to evaluate it based on what it says about new data that was not part of the training set. In Scikit-Learn, this can be done using the predict() method.'

(df 전체를 training set으로 간주하여 model을 만들었다. 이렇게 model을 만들기 위해 사용하는 dataset을 training set이라고 한다. 모델 성능 최종 test를 위해 본래 df에서 test set을 일부 떼어놓는다)

→ 해당 예의 경우 extrapolate 기법으로 waiting time이 100일 때 (X=100)를 넣어보자 - 그 때의 duration time 예측하기

(→ predict에 넣는 X와 출력된 예측값 y 모두 2D-array 형태)

 

X_test = [[100]]
y_pred = model.predict(X_test)

y_pred[0][0]
#5.688778808775533

 

▦ 최종결론) 주어진 data를 통해 단순선형회귀모델을 만들었고

이 모델에 기반하여 waiting time이 100일 때를 집어넣으면 duration time은 약 5.69가 된다. ▦

 

> Typically the efficacy of the model is evaluated by comparing its results to some known baseline - 해당 모델은 baseline model과 비교를 함으로서 모델의 효용성을 평가한다. 이 때 다양한 evaluation metrics를 쓸 수 있음. (추후 포스팅)

 

- 하단 baseline model 포스팅 참고 -

 

Baseline Model

- 맨 하단 글 일부 발췌 - 🧐 "A baseline is a simple model that provides reasonable results on a task and does not require much expertise and time to build. Common baseline models include linea..

sh-avid-learner.tistory.com

 

*** scikit-learn은 docu가 정말 기가 막히게 너무너무 정리가 잘 되어 있다 ***

 docu 보는걸 정말정말 꼭! 강추

 

*출처1) https://stackoverflow.com/questions/51150153/valueerror-expected-2d-array-got-1d-array-instead

*출처2) https://jakevdp.github.io/PythonDataScienceHandbook/05.02-introducing-scikit-learn.html#Basics-of-the-API

댓글