본문 바로가기

여러가지/Python

섹션 8. 다항식 회귀 (Polynomial Linear Regression)

● URL : https://colab.research.google.com/drive/1z-W384uxJ8AFzNQXCrrKqGeAGCSE-hZv#scrollTo=nQOdXhjXD_AE

 

※ 비선형 관계(곡선 형태의 관계)를 갖는 경우, 다항 회귀를 사용하여 2차, 3차, 4차.. n차 항을 추가하여 비선형성 표현한다.

 

Step 1. Importing the libraries

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

 

Step 2. Importing the dataset

dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:-1].values
y = dataset.iloc[:, -1].values

 

Step 3. Training the Linear Regression model on the whole dataset

from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X, y)

 

Step 4. Training the Polynomial Regression model on the whole dataset

- PolynomialFeatures : 다항 회귀 클래스

- poly_reg : 인스턴스

 - degree : 다항식 차수 지정

from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree = 4)
X_poly = poly_reg.fit_transform(X)
lin_reg_2 = LinearRegression()
lin_reg_2.fit(X_poly, y)

--------------------------------------------------------------------------------------------------------------------------------------------------------------------

(1) poly_reg = PolynomialFeatures(degree = 4) : 4차 다항식 특성 추가
(2) X_poly = poly_reg.fit_transform(X) : X를 다항 특성으로 변환한 X_poly 생성

(3) lin_reg_2.fit(X_poly, y) : 다항 특성으로 변환한 X_poly와 y 학습

--------------------------------------------------------------------------------------------------------------------------------------------------------------------

※ 다항 특성의 X 생성한 뒤, 선형 회귀 모델과 통합한다. 즉, 다항 특성들의 선형 조합

 

Step 5. Visualising the Linear Regression results

plt.scatter(X, y, color = 'red')
plt.plot(X, lin_reg.predict(X), color = 'blue')
plt.title('Truth or Bluff (Linear Regression)')
plt.xlabel('Position Level')
plt.ylabel('Salary')
plt.show()

 

Step 6. Visualising the Polynomial Regression results

plt.scatter(X, y, color = 'red')
plt.plot(X, lin_reg_2.predict(poly_reg.fit_transform(X)), color = 'blue')
plt.title('Truth or Bluff (Polynomial Regression)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()

 

Step 7. Visualising the Polynomial Regression results (for higher resolution and smoother curve)

X_grid = np.arange(min(X), max(X), 0.1)
X_grid = X_grid.reshape((len(X_grid), 1))
plt.scatter(X, y, color = 'red')
plt.plot(X_grid, lin_reg_2.predict(poly_reg.fit_transform(X_grid)), color = 'blue')
plt.title('Truth or Bluff (Polynomial Regression)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()

--------------------------------------------------------------------------------------------------------------------------------------------------------------------

(1) X_grid = np.arange(min(X), max(X), 0.1) : X 데이터의 최소값에서 최대값까지 0.1 간격으로 값 생성

(2) X_grid.reshape((len(X_grid), 1)) : 모델에 입력될 수 있는 형식인 (n, 1) 형태로 변환 

--------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

 

Step 8. Predicting a new result with Linear Regression

※ 관측치는 항상 배열 형태로 입력해야한다.

- predict() : array_like 혹은 희소 행렬로 입력 받음

array_like : Numpy배열 혹은 대괄호 두 쌍으로 이루어진 배열(Python 배열) ([] : 1차원(행), [[]] : 2차원(열))

ex) [[6.5,5],[2,3]] : 행 2개, 열 2개, 첫번째 행 - [6.5,5], 두번째 행 -[2,3]

lin_reg.predict([[6.5]])

 

Step 9. Predicting a new result with Polynomial Regression

lin_reg_2.predict(poly_reg.fit_transform([[6.5]]))

 

 

 

※  함수를 계수들의 선형 조합으로 표현할 수 있는가?
회귀 구축 시 목표는 계수를 찾고 실제 값을 알아내어 그 계수를 사용하여 X를 입력하고 y를 예측하는 것이다.
즉, 계수(b) 구하는 것이다.