소개
이 실습에서는 Scikit-learn Elastic-Net 회귀 모델을 사용하여 추정량의 성능이 학습 데이터와는 달리 미지의 데이터 (테스트 데이터) 에서 어떻게 다른지 보여줍니다. 샘플 데이터를 생성하고 학습 및 테스트 오류를 계산한 후 결과 함수를 플롯합니다.
VM 팁
VM 시작이 완료되면 왼쪽 상단 모서리를 클릭하여 Notebook 탭으로 전환하여 연습을 위한 Jupyter Notebook에 접근합니다.
때때로 Jupyter Notebook 이 완전히 로드되기까지 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한으로 인해 작업의 유효성 검사를 자동화할 수 없습니다.
학습 중 문제가 발생하면 Labby 에 문의하십시오. 세션 후 피드백을 제공하면 문제를 신속하게 해결해 드리겠습니다.
샘플 데이터 생성
Scikit-learn 의 make_regression() 함수를 사용하여 샘플 데이터를 생성합니다. 학습 샘플 수는 75 개, 테스트 샘플 수는 150 개, 특징 (feature) 수는 500 개로 설정합니다. 또한 n_informative를 50 으로, shuffle를 False 로 설정합니다.
import numpy as np
from sklearn import linear_model
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
n_samples_train, n_samples_test, n_features = 75, 150, 500
X, y, coef = make_regression(
n_samples=n_samples_train + n_samples_test,
n_features=n_features,
n_informative=50,
shuffle=False,
noise=1.0,
coef=True,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, train_size=n_samples_train, test_size=n_samples_test, shuffle=False
)
학습 및 테스트 오류 계산
Scikit-learn 의 Elastic-Net 회귀 모델을 사용하여 학습 및 테스트 오류를 계산합니다. 정규화 매개변수 alpha를 np.logspace()를 사용하여 10^-5 에서 10^1 까지의 범위로 설정합니다. 또한 l1_ratio를 0.7 로, max_iter를 10000 으로 설정합니다.
alphas = np.logspace(-5, 1, 60)
enet = linear_model.ElasticNet(l1_ratio=0.7, max_iter=10000)
train_errors = list()
test_errors = list()
for alpha in alphas:
enet.set_params(alpha=alpha)
enet.fit(X_train, y_train)
train_errors.append(enet.score(X_train, y_train))
test_errors.append(enet.score(X_test, y_test))
i_alpha_optim = np.argmax(test_errors)
alpha_optim = alphas[i_alpha_optim]
print("Optimal regularization parameter : %s" % alpha_optim)
결과 플롯 함수
matplotlib 라이브러리를 사용하여 결과를 플롯합니다. plt.subplot() 함수를 사용하여 두 개의 서브플롯을 생성합니다. 첫 번째 서브플롯에서는 정규화 매개변수에 따른 학습 및 테스트 오류를 플롯하고, 최적의 정규화 매개변수에 해당하는 수직선을 표시합니다. 두 번째 서브플롯에서는 실제 계수와 추정된 계수를 플롯합니다.
import matplotlib.pyplot as plt
plt.subplot(2, 1, 1)
plt.semilogx(alphas, train_errors, label="Train")
plt.semilogx(alphas, test_errors, label="Test")
plt.vlines(
alpha_optim,
plt.ylim()[0],
np.max(test_errors),
color="k",
linewidth=3,
label="Optimum on test",
)
plt.legend(loc="lower right")
plt.ylim([0, 1.2])
plt.xlabel("Regularization parameter")
plt.ylabel("Performance")
## Show estimated coef_ vs true coef
plt.subplot(2, 1, 2)
plt.plot(coef, label="True coef")
plt.plot(coef_, label="Estimated coef")
plt.legend()
plt.subplots_adjust(0.09, 0.04, 0.94, 0.94, 0.26, 0.26)
plt.show()
요약
이 실습에서는 Scikit-learn 의 Elastic-Net 회귀 모델을 사용하여 학습 및 테스트 오류를 계산하고 결과 함수를 플롯하는 방법을 배웠습니다. 또한, 예측 대상 데이터 (테스트 데이터) 에서의 추정기 성능이 학습 데이터에서의 성능과 동일하지 않다는 점을 이해했습니다. make_regression(), linear_model.ElasticNet(), train_test_split(), np.logspace(), 그리고 matplotlib 함수를 사용하여 샘플 데이터를 생성하고, 학습 및 테스트 오류를 계산하며, 결과 함수를 플롯했습니다.