릿지(Ridge) 모델
- L2 규제를 활용한 선형 회귀 모델이다
- $Error=MSE+\alpha w^2$
Steps
학습
from sklearn.linear_model import Ridge
# 알파값이 커질 수록 큰 규제
alphas = [100, 10, 1, 0.1, 0.01, 0.001, 0.0001]
# 알파별로 학습시키기
for alpha in alphas:
ridge = Ridge(alpha=alpha)
ridge.fit(x_train, y_train)
pred = ridge.predict(x_test)
mse_eval('Ridge(alpha={})'.format(alpha), pred, y_test) # mse_eval 함수는 자체적으로 만듦
features별로 coefficients 확인
- .coef_ 활용
x_train.columns
ridge.coef_
coefficients 시각화 해보자
def plot_coef(columns, coef):
coef_df = pd.DataFrame(list(zip(columns, coef)))
coef_df.columns=['feature', 'coef']
coef_df = coef_df.sort_values('coef', ascending=False).reset_index(drop=True)
fig, ax = plt.subplots(figsize=(9, 7))
ax.barh(np.arange(len(coef_df)), coef_df['coef'])
idx = np.arange(len(coef_df))
ax.set_yticks(idx)
ax.set_yticklabels(coef_df['feature'])
fig.tight_layout()
plt.show()
plot_coef(x_train.columns, ridge.coef_)
alpha값 별로 coef 확인
- alpha가 100일 때
ridge_100 = Ridge(alpha=100)
ridge_100.fit(x_train, y_train)
ridge_pred_100 = ridge_100.predict(x_test)
plot_coef(x_train.columns, ridge_100.coef_)
- alpha가 0.001일 때
ridge_001 = Ridge(alpha=0.001)
ridge_001.fit(x_train, y_train)
ridge_pred_001 = ridge_001.predict(x_test)
plot_coef(x_train.columns, ridge_001.coef_)
- 학습 데이터셋이 적을수록 강한 규제를 주는게 좋은 방식이다. 가지고 있는 데이터셋에 과하게 적합할수록 예측력이 떨어지는 위험이 더 크기 때문이다