선형 회귀(Linear Regression)란?

한 개 이상의 독립 변수(설명 변수) X와 종속 변수 y와의 선형 상관 관계를 모델링하는 회귀분석기법

- 단순 선형 회귀 : 1 개의 설명 변수

- 다중 선형 회귀 : 2개 이상의 설명 변수

 

라이브러리 임포트

import numpy as np
import matplotlib.pyplot as plt
import random
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
r = np.random.RandomState(123)
x = 10 * r.rand(123)
y = 2 * x - 3 * r.rand(123)
plt.scatter(x,y)
plt.show()

 

print(x.shape)
print(y.shape)

(123,)

(123,)

 

사이킷런에 사용할 훈련 세트(이 글에서 x) 2차원 배열이어야 한다

=> reshape(-1, 1) 사용해서 1차원 배열 -> 2차원 배열로 변환시키자

 

x = x.reshape(-1,1)
print(x.shape)

(123, 1)

 

선형 회귀 모델 생성 및 학습

model = LinearRegression()
model.fit(x,y)

예측

x_new = np.linspace(-1, 11, 123) # 새로운 배열 생성
x_new = x_new.reshape(-1,1)     # 새로운 배열 reshape
y_new = model.predict(x_new)    # 예측

 

MSE 평가

mse = mean_squared_error(y, y_new) # y_true, y_pred
mse

75.47517842704247

 

시각화

plt.scatter(x, y, label='input data')
plt.plot(x_new, y_new, color='red', label='regression line')

 

'What I study > Python' 카테고리의 다른 글

[Python 텍스트 분석]  (0) 2022.12.11

+ Recent posts