1 분 소요

원본 사이트: https://scikit-learn.org/stable/auto_examples/linear_model/plot_ols_3d.html


희소성 예시: 첫번째와 두번째 특성으로만 학습하기

다음은 diabetes 데이터 세트의 첫번째와 두번째 특성으로 학습하고 그래프로 표현한 것입니다. 두번째 특성은 전체 모델에서 강한 관계를 갖지만, 첫번째 특성에 비해서는 타겟값 y에 많은 것을 제공하지 않음을 보여줍니다.

image.png

image.png

image.png

# Code source: Gaël Varoquaux
# Modified for documentation by Jaques Grobler
# License: BSD 3 clause

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

from sklearn import datasets, linear_model

X, y = datasets.load_diabetes(return_X_y=True)
indices = (0, 1)    # 첫번째 특성과 두번째 특성을 가져오기 위한 인덱스들

X_train = X[:-20, indices]
X_test = X[-20:, indices]
y_train = y[:-20]
y_test = y[-20:]

ols = linear_model.LinearRegression()
ols.fit(X_train, y_train)


print('첫번째 특성의 계수:', ols.coef_[0])
print('두번째 특성의 계수:', ols.coef_[1])
# #############################################################################
def plot_figs(fig_num, elev, azim, X_train, clf):

    """ 그래프 출력

    매개변수
    -----------
    fig_num : int
      그래프 번호
    elev : float
      elevation의 약자/ zplane의 각도
    azim : float
      azimuth angle의 약자/ x, y plane의 각도
    X_train : {array-like}, shape = [n_samples, n_features]
      n_samples개의 샘플과 n_features개의 특성으로 이루어진 훈련 데이터
    clf : estimator 객체
      학습을 완료한 estimator 객체
    """
    fig = plt.figure(fig_num, figsize=(4, 3))
    plt.clf()   # Clear the current figure
    ax = Axes3D(fig, elev=elev, azim=azim)

    ax.scatter(X_train[:, 0], X_train[:, 1], y_train, c="k", marker="+")
    ax.plot_surface(
        np.array([[-0.1, -0.1], [0.15, 0.15]]),
        np.array([[-0.1, 0.15], [-0.1, 0.15]]),
        clf.predict(
            np.array([[-0.1, -0.1, 0.15, 0.15], [-0.1, 0.15, -0.1, 0.15]]).T
        ).reshape((2, 2)),
        alpha=0.5,
    )
    ax.set_xlabel("X_1")
    ax.set_ylabel("X_2")
    ax.set_zlabel("Y")
    ax.w_xaxis.set_ticklabels([])
    ax.w_yaxis.set_ticklabels([])
    ax.w_zaxis.set_ticklabels([])


# 다른 시야에서 세 가지 다른 그림 생성
elev = 43.5
azim = -110
plot_figs(1, elev, azim, X_train, ols)

elev = -0.5
azim = 0 
plot_figs(2, elev, azim, X_train, ols)

elev = -0.5
azim = 90
plot_figs(3, elev, azim, X_train, ols)

plt.show()
첫번째 특성의 계수: 305.05479720788964
두번째 특성의 계수: 10.449349163460269
<Figure size 288x216 with 1 Axes>
<Figure size 288x216 with 1 Axes>
<Figure size 288x216 with 1 Axes>

ⓒ 2007 - 2021, scikit-learn developers (BSD License). Show this page source

댓글남기기