분류를 위한 특징 이산화

Beginner

This tutorial is from open-source community. Access the source code

소개

머신 러닝에서 특징 이산화는 데이터 세트에서 연속 변수의 수를 줄이는 방법으로, 이를 나타내기 위해 구간이나 간격을 만드는 것입니다. 이 방법은 연속 변수의 수가 많고 알고리즘을 분석하기 쉽도록 단순화해야 하는 경우에 유용할 수 있습니다. 이 실험실에서는 합성 분류 데이터 세트에서 특징 이산화를 보여줄 것입니다.

VM 팁

VM 시작이 완료되면 왼쪽 상단 모서리를 클릭하여 연습을 위해 Jupyter Notebook에 접근할 수 있는 Notebook 탭으로 전환하십시오.

때때로 Jupyter Notebook 이 완전히 로드되기까지 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한으로 인해 작업의 유효성 검사를 자동화할 수 없습니다.

학습 중 문제가 발생하면 Labby 에 문의하십시오. 세션 후 피드백을 제공하면 문제를 신속하게 해결해 드리겠습니다.

라이브러리 가져오기

이 단계에서는 실험에 필요한 라이브러리를 가져옵니다. 머신 러닝 작업에는 scikit-learn 라이브러리, 수학 연산에는 numpy 라이브러리, 데이터 시각화에는 matplotlib 라이브러리를 사용합니다.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_moons, make_circles, make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import KBinsDiscretizer
from sklearn.svm import SVC, LinearSVC
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.utils._testing import ignore_warnings
from sklearn.exceptions import ConvergenceWarning

데이터 준비

이 단계에서는 특징 이산화를 위한 합성 분류 데이터 세트를 준비합니다. scikit-learn 라이브러리를 사용하여 세 가지 다른 데이터 세트 (달 모양, 동심원, 선형적으로 분리 가능한 데이터) 를 생성합니다.

h = 0.02  ## 메쉬의 단계 크기

n_samples = 100
datasets = [
    make_moons(n_samples=n_samples, noise=0.2, random_state=0),
    make_circles(n_samples=n_samples, noise=0.2, factor=0.5, random_state=1),
    make_classification(
        n_samples=n_samples,
        n_features=2,
        n_redundant=0,
        n_informative=2,
        random_state=2,
        n_clusters_per_class=1,
    ),
]

분류기 및 매개변수 정의

이 단계에서는 특징 이산화 과정에 사용할 분류기와 매개변수를 정의합니다. 로지스틱 회귀, 선형 서포트 벡터 머신 (SVM), 그래디언트 부스팅 분류기, 그리고 방사 기저 함수 커널을 사용하는 SVM 을 포함하는 분류기 목록을 생성합니다. 또한, GridSearchCV 알고리즘에 사용할 각 분류기의 매개변수 집합을 정의합니다.

## (estimator, param_grid) 목록, 여기서 param_grid 는 GridSearchCV 에서 사용됩니다.
## 이 예제의 매개변수 공간은 실행 시간을 줄이기 위해 좁은 범위로 제한되어 있습니다.
## 실제 사용 사례에서는 알고리즘에 대한 더 넓은 검색 공간을 사용해야 합니다.
classifiers = [
    (
        make_pipeline(StandardScaler(), LogisticRegression(random_state=0)),
        {"logisticregression__C": np.logspace(-1, 1, 3)},
    ),
    (
        make_pipeline(StandardScaler(), LinearSVC(random_state=0, dual="auto")),
        {"linearsvc__C": np.logspace(-1, 1, 3)},
    ),
    (
        make_pipeline(
            StandardScaler(),
            KBinsDiscretizer(encode="onehot"),
            LogisticRegression(random_state=0),
        ),
        {
            "kbinsdiscretizer__n_bins": np.arange(5, 8),
            "logisticregression__C": np.logspace(-1, 1, 3),
        },
    ),
    (
        make_pipeline(
            StandardScaler(),
            KBinsDiscretizer(encode="onehot"),
            LinearSVC(random_state=0, dual="auto"),
        ),
        {
            "kbinsdiscretizer__n_bins": np.arange(5, 8),
            "linearsvc__C": np.logspace(-1, 1, 3),
        },
    ),
    (
        make_pipeline(
            StandardScaler(), GradientBoostingClassifier(n_estimators=5, random_state=0)
        ),
        {"gradientboostingclassifier__learning_rate": np.logspace(-2, 0, 5)},
    ),
    (
        make_pipeline(StandardScaler(), SVC(random_state=0)),
        {"svc__C": np.logspace(-1, 1, 3)},
    ),
]

names = [get_name(e).replace("StandardScaler + ", "") for e, _ in classifiers]

데이터 시각화

이 단계에서는 특징 이산화 전에 합성 분류 데이터 세트를 시각화합니다. 각 데이터 세트에 대한 학습 및 테스트 데이터 포인트를 플롯합니다.

fig, axes = plt.subplots(
    nrows=len(datasets), ncols=len(classifiers) + 1, figsize=(21, 9)
)

cm_piyg = plt.cm.PiYG
cm_bright = ListedColormap(["#b30065", "#178000"])

## 데이터 세트 반복
for ds_cnt, (X, y) in enumerate(datasets):
    print(f"\ndataset {ds_cnt}\n---------")

    ## 학습 및 테스트 부분으로 분할
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.5, random_state=42
    )

    ## 배경색을 위한 그리드 생성
    x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
    y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

    ## 먼저 데이터 세트를 플롯합니다.
    ax = axes[ds_cnt, 0]
    if ds_cnt == 0:
        ax.set_title("입력 데이터")
    ## 학습 데이터 포인트를 플롯합니다.
    ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright, edgecolors="k")
    ## 그리고 테스트 데이터 포인트를 플롯합니다.
    ax.scatter(
        X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright, alpha=0.6, edgecolors="k"
    )
    ax.set_xlim(xx.min(), xx.max())
    ax.set_ylim(yy.min(), yy.max())
    ax.set_xticks(())
    ax.set_yticks(())

특징 이산화 구현

이 단계에서는 scikit-learn 의 KBinsDiscretizer 클래스를 사용하여 데이터 세트에 특징 이산화를 구현합니다. 이는 특징을 일련의 구간으로 나누고 이산화된 값을 원 - 핫 인코딩하여 특징을 이산화합니다. 그런 다음 데이터를 선형 분류기에 맞추고 성능을 평가합니다.

## 분류기 반복
for est_idx, (name, (estimator, param_grid)) in enumerate(zip(names, classifiers)):
    ax = axes[ds_cnt, est_idx + 1]

    clf = GridSearchCV(estimator=estimator, param_grid=param_grid)
    with ignore_warnings(category=ConvergenceWarning):
        clf.fit(X_train, y_train)
    score = clf.score(X_test, y_test)
    print(f"{name}: {score:.2f}")

    ## 결정 경계를 플롯합니다. 이를 위해 메쉬 [x_min, x_max] * [y_min, y_max] 의 각 점에 색상을 할당합니다.
    if hasattr(clf, "decision_function"):
        Z = clf.decision_function(np.column_stack([xx.ravel(), yy.ravel()]))
    else:
        Z = clf.predict_proba(np.column_stack([xx.ravel(), yy.ravel()]))[:, 1]

    ## 결과를 색상 플롯에 넣습니다.
    Z = Z.reshape(xx.shape)
    ax.contourf(xx, yy, Z, cmap=cm_piyg, alpha=0.8)

    ## 학습 데이터 포인트를 플롯합니다.
    ax.scatter(
        X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright, edgecolors="k"
    )
    ## 그리고 테스트 데이터 포인트를 플롯합니다.
    ax.scatter(
        X_test[:, 0],
        X_test[:, 1],
        c=y_test,
        cmap=cm_bright,
        edgecolors="k",
        alpha=0.6,
    )
    ax.set_xlim(xx.min(), xx.max())
    ax.set_ylim(yy.min(), yy.max())
    ax.set_xticks(())
    ax.set_yticks(())

    if ds_cnt == 0:
        ax.set_title(name.replace(" + ", "\n"))
    ax.text(
        0.95,
        0.06,
        (f"{score:.2f}").lstrip("0"),
        size=15,
        bbox=dict(boxstyle="round", alpha=0.8, facecolor="white"),
        transform=ax.transAxes,
        horizontalalignment="right",
    )

결과 시각화

이 단계에서는 특징 이산화 과정의 결과를 시각화합니다. 각 분류기와 데이터 세트에 대한 테스트 세트의 분류 정확도를 플롯합니다.

plt.tight_layout()

## 그림 위에 제목 추가
plt.subplots_adjust(top=0.90)
suptitles = [
    "선형 분류기",
    "특징 이산화 및 선형 분류기",
    "비선형 분류기",
]
for i, suptitle in zip([1, 3, 5], suptitles):
    ax = axes[0, i]
    ax.text(
        1.05,
        1.25,
        suptitle,
        transform=ax.transAxes,
        horizontalalignment="center",
        size="x-large",
    )
plt.show()

요약

이 실험에서는 scikit-learn 을 사용하여 합성 분류 데이터 세트에 대한 특징 이산화를 보여주었습니다. 데이터를 준비하고, 분류기와 매개변수를 정의하고, 특징 이산화를 구현하고, 결과를 시각화했습니다. 이러한 전처리 기법은 데이터 세트의 복잡성을 줄이고 선형 분류기의 성능을 향상시키는 데 유용할 수 있습니다. 그러나 과적합을 방지하기 위해 다른 기법과 함께 사용하는 것이 중요하며 주의해서 사용해야 합니다.