Polynomial Regression 을 이용한 Underfitting, Overfitting 이해¶
cosine 곡선에 약간의 Noise 변동값을 더하여 실제값 곡선을 만듬
In [1]:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
%matplotlib inline
# random 값으로 구성된 X값에 대해 Cosine 변환값을 반환.
def true_fun(X):
return np.cos(1.5 * np.pi * X)
# X는 0 부터 1까지 30개의 random 값을 순서대로 sampling 한 데이타 입니다.
np.random.seed(0)
n_samples = 30
X = np.sort(np.random.rand(n_samples))
# y 값은 cosine 기반의 true_fun() 에서 약간의 Noise 변동값을 더한 값입니다.
y = true_fun(X) + np.random.randn(n_samples) * 0.1
In [2]:
plt.scatter(X, y)
Out[2]:
<matplotlib.collections.PathCollection at 0x201fcf9c460>
In [5]:
plt.figure(figsize=(14, 5))
degrees = [1, 4, 13]
# 다항 회귀의 차수(degree)를 1, 4, 15로 각각 변화시키면서 비교합니다.
for i in range(len(degrees)):
ax = plt.subplot(1, len(degrees), i + 1)
plt.setp(ax, xticks=(), yticks=())
# 개별 degree별로 Polynomial 변환합니다.
polynomial_features = PolynomialFeatures(degree=degrees[i], include_bias=False)
linear_regression = LinearRegression()
pipeline = Pipeline([("polynomial_features", polynomial_features),
("linear_regression", linear_regression)])
pipeline.fit(X.reshape(-1, 1), y)
# 교차 검증으로 다항 회귀를 평가합니다.
scores = cross_val_score(pipeline, X.reshape(-1,1), y,scoring="neg_mean_squared_error", cv=10)
coefficients = pipeline.named_steps['linear_regression'].coef_
print('\nDegree {0} 회귀 계수는 {1} 입니다.'.format(degrees[i], np.round(coefficients),2))
print('Degree {0} MSE 는 {1:.2f} 입니다.'.format(degrees[i] , -1*np.mean(scores)))
# 0 부터 1까지 테스트 데이터 세트를 100개로 나눠 예측을 수행합니다.
# 테스트 데이터 세트에 회귀 예측을 수행하고 예측 곡선과 실제 곡선을 그려서 비교합니다.
X_test = np.linspace(0, 1, 100)
# 예측값 곡선
plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model")
# 실제 값 곡선
plt.plot(X_test, true_fun(X_test), '--', label="True function")
plt.scatter(X, y, edgecolor='b', s=20, label="Samples")
plt.xlabel("x"); plt.ylabel("y"); plt.xlim((0, 1)); plt.ylim((-2, 2)); plt.legend(loc="best")
plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(degrees[i], -scores.mean(), scores.std()))
plt.show()
Degree 1 회귀 계수는 [-2.] 입니다.
Degree 1 MSE 는 0.41 입니다.
Degree 4 회귀 계수는 [ 0. -18. 24. -7.] 입니다.
Degree 4 MSE 는 0.04 입니다.
Degree 13 회귀 계수는 [ 1.82000000e+02 -6.20600000e+03 1.04046000e+05 -9.98445000e+05
5.93306800e+06 -2.30761730e+07 6.08725620e+07 -1.10896251e+08
1.39728771e+08 -1.19631045e+08 6.64602580e+07 -2.16163140e+07
3.12554800e+06] 입니다.
Degree 13 MSE 는 1323082.48 입니다.
'머신러닝 > 회귀' 카테고리의 다른 글
5.9 Regression실습-Bike Sharing Demand(수정)__UCI데이터셋 (0) | 2022.10.25 |
---|---|
05-1_실습_UCIDATASET_콘크리트_회귀실습 (0) | 2022.10.25 |
05_회귀 실습_자전거 대여 수요 예측_ 캐글 (0) | 2022.10.25 |
04_데이터 전처리(정규화,로그변환, 스케일러, 원-핫 인코딩 ) (0) | 2022.10.25 |
3_규제 선형 회귀__릿지, 라쏘, 엘라스틱넷 (0) | 2022.10.25 |