✳️ 단순선형회귀 실습 - 임의데이터
선형회귀에 대해 실습을 하기위해 필요한 라이브러리들이 없기 때문에 설치하고 시작
! pip install scikit-learn
! pip install numpy
! pip install pandas
! pip install matplotlib
! pip install seaborn
그리고 라이브러리들을 import 해준다.
import sklearn
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
✏️ 데이터 생성
이전 글에 대해서 키와 몸무게로 예시를 들었던 것을 살려서 실습에도 비슷한 데이터로 다뤄보기 위해 데이터를 생성해보자!
weights = [87, 81, 82, 92, 90, 61, 86, 66, 69, 69]
heights = [187, 174, 179, 192, 188, 160, 179, 168, 168, 174]
# 딕셔너리 형태로 데이터 생성
body_df = pd.DataFrame({'height' : heights, 'weight' : weights})
body_df.head(3)
몸무게와 키에 대한 데이터의 분포를 알기 위해 산점도 그래프를 그려보았다.
# 몸무게와 키간의 산점도
sns.scatterplot(data = body_df, x = 'weight', y = 'height')
plt.title('weights vs heights')
plt.xlabel('Weight(kg)')
plt.ylabel('Height(cm)')
plt.show()
산점도 그래프를 보니, 몸무게에 따라 키가 점점 증가하는 것으로 나타나는 것 같았고 연관이 있을 것이라 예측이 되니 선형 머신러닝 라이브러리를 이용하여 평가해보자!
✏️ LinearRegression 이용하기
선형회귀 훈련을 위해서 먼저 sklearn.linear_model에서 LinearRegression을 불러온다.
그리고 LinearRegression 클래스를 변수에 저장해준다.
# 선형회귀 라이브러리 불러오기
from sklearn.linear_model import LinearRegression
model_lr = LinearRegression()
▼ scikilt-learn.linear_model의 LinearRegression에 대한 공식문서
LinearRegression
Gallery examples: Principal Component Regression vs Partial Least Squares Regression Plot individual and voting regression predictions Comparing Linear Bayesian Regressors Linear Regression Example...
scikit-learn.org
✏️ 훈련시키기
먼저 제공된 데이터에 대해서 각각 X와 y변수에 넣어준다.
# 대괄호를 두 개를 입혀서 데이터프레임 형식으로 불러오기
# 훈련(fit)시 차원이 맞지 않는 문제가 생길 수 있기 때문
X = body_df[['weight']]
y = body_df[['height']]
데이터를 LinearRegression 클래스의 fit 메서드를 이용하여 훈련시킨다.
# 데이터 훈련
# 데이터 훈련을 진행하고 나면 가중치와 편향의 값이 알아서 구해지고 입력이 되어진다! 아주 멋짐!
model_lr.fit(X = X, y = y)
⭐ fit(X, y, sample_weight=None)
파라미터
- X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training data - y : array-like of shape (n_samples,) or (n_samples, n_targets)
Target values
Will be cast to X’s dtype if necessary. - sample_weight : array-like of shape (n_samples,), default=None
Individual weights for each sample
Returns
- self : object
Fitted Estimator
학습을 완료했으니,
이제 선형회귀를 이용하여 산점도와 더불어 직선 그래프를 그리는 과정을 가져볼 것이다.
✏️ 가중치와 편향 구하고 수식 만들기
먼저 가중치와 편향을 훈련된 모델에서 가져오고 변수에 지정해준다.
# 가중치(w1)
print(model_lr.coef_)
# 편향(bias, w0)
print(model_lr.intercept_)
# 변수에 가중치와 편향 값을 지정
# 가중치의 경우 데이터프레임형식으로 2차원의 구조이기 때문에 인덱스를 이용하여 값을 꺼내오고
# 편향의 경우는 시리즈 형태이므로 인덱스를 한번만 써서 값을 가져온다
w1 = model_lr.coef_[0][0]
w0 = model_lr.intercept_[0]
# 수식으로 만들기
print('y = {}x + {}'.format(w1, w0))
# 소수점 둘째자리까지만 표시
print('y = {}x + {}'.format(w1.round(2), w0.round(2)))
=> y(height)는 x(몸무게)에 0.86을 곱한 뒤 109.37을 더하면 된다.
✏️ 수동으로 MSE를 계산 해보기
- y = 0.86x + 109.37
- 식을 활용하여 예측값을 구하고 컬럼 추가
- 에러값 구하고 컬럼 추가
- 양수를 만들기 위해 에러값 제곱
- 제곱한 에러값 모두 더하고 데이터의 개수만큼 나누기 => MSE 구함!!
# 예측값 만들기
body_df['pred'] = body_df['weight']*w1 + w0
# 에러 만들기
body_df['error'] = body_df['height'] - body_df['pred']
body_df.head(3)
# 에러 제곱하기
body_df['error^2'] = body_df['error']*body_df['error']
body_df.head(3)
# 에러에 제곱한 값들 모두 더하기
# 더한 값에 데이터 개수만큼 나눠주기
body_df['error^2'].sum()/len(body_df)
✏️ 산점도 그래프에 선형식을 만들어 그래프화 시키기
sns.scatterplot(data = body_df, x = 'weight', y = 'height')
sns.lineplot(data = body_df, x = 'weight', y = 'pred', color='red') # 예측한 값이 선형으로 그려져야 해서 y값은 pred로 가져온다
plt.show()
✏️ 지표를 활용하여 선형회귀 모델 평가
- 회귀(숫자를 맞추는 방법) : MSE(수동계산은 10)
- R Square : 평균대비 설명력 (0이면 제일 낮음, 1일수록 높은 것)
sklearn.metrics에서 MSE와 R square을 구하는 mean_squared_error와 r2_score를 불러온다.
from sklearn.metrics import mean_squared_error, r2_score
▼ sklearn.metrics에 대한 공식 사이트
https://scikit-learn.org/stable/api/sklearn.metrics.html
sklearn.metrics
Score functions, performance metrics, pairwise metrics and distance computations. User guide. See the Metrics and scoring: quantifying the quality of predictions and Pairwise metrics, Affinities an...
scikit-learn.org
# MSE를 자동으로 구하기
# 평가함수는 공통적으로 정답(실제 true), 예측값(pred)
y_true = body_df['height']
y_pred = body_df['pred']
mean_squared_error(y_true, y_pred)
# R square 구하기
r2_score(y_true, y_pred)
이미 예측값을 수식을 통해 수동으로 구해서 'pred'컬럼을 이용해줬지만,
자동으로 .predict()메서드를 이용해 예측값을 구해볼 수 있다.
# 예측값을 자동으로 구하는 법
# 정답을 모르는 상태에서 x값을 주어진 상태일 때 구할 수 있음(그래서 x값에 해당되는 것만 넣어주면 됨)
model_lr.predict(body_df[['weight']])
✳️ 단순선형회귀 실습 - 실제데이터
seaborn에서 제공해주는 tips 데이터로 실습을 한 번 더 해보자
tips_df = sns.load_dataset('tips')
tips_df.head(3)
- X와 y 변수를 지정
- X : total_bill
- y : tip
🤖 산점도 그리기
sns.scatterplot(data = tips_df, x = 'total_bill', y = 'tip')
🤖 훈련시키기
# LinearRegression() 지정
model_lr2 = LinearRegression()
# X, y 지정
X = tips_df[['total_bill']]
y = tips_df[['tip']]
# 훈련시키기
model_lr2.fit(X, y)
🤖 가중치와 편향 구하고 수식 만들기
# y(tip) = w1_tip*x(total_bill) + w0_tip
w1_tip = model_lr2.coef_[0][0]
w0_tip = model_lr2.intercept_[0]
print('y = {}x + {}'.format(w1_tip.round(2), w0_tip.round(2)))
🤖 자동으로 예측값 구해보기
# 예측값 생성
y_true_tip = tips_df['tip']
y_pred_tip = model_lr2.predict(tips_df[['total_bill']])
y_true_tip[:5]
y_pred_tip[:5]
# pred 컬럼 추가하여 예측값 넣기
tips_df['pred'] = y_pred_tip
tips_df.head(3)
🤖 산점도와 선형 그래프 그리기
sns.scatterplot(data = tips_df, x = 'total_bill', y = 'tip')
sns.lineplot(data = tips_df, x = 'total_bill', y = 'pred', color='red')
🤖 지표로 모델 평가하기
☑️ MSE
mean_squared_error(y_true_tip, y_pred_tip)
현재 데이터는 tips 데이터로 아까 키 데이터와 비교해서 MSE를 두면 안된다!
키는 CM이고 tip은 달러 단위로, 서로 단위가 다르기 때문에 두 데이터를 비교하면 안된다.
MSE는 서로 같은 데이터에서 서로 다른 모델끼리 비교할 때 쓰이는 것!
☑️ R Square
r2_score(y_true_tip, y_pred_tip)
이 지표는 분야마다 좋은 모델이라고 평가하는 수치가 조금씩 다르다.
'📒 Today I Learn > 🤖 Machine Learning' 카테고리의 다른 글
[머신러닝 기초] 로지스틱회귀(분류 분석) 이론 (0) | 2024.08.12 |
---|---|
[머신러닝 기초] 선형회귀 정리 (0) | 2024.08.09 |
[머신러닝 기초] 다중선형회귀 실습 (0) | 2024.08.09 |
[머신러닝 기초] 선형회귀 이론 (0) | 2024.08.09 |
[머신러닝 기초] 머신러닝? (0) | 2024.08.09 |