다중 레이블 문서 분류

Beginner

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

소개

이 실험은 scikit-learn 을 사용하여 다중 레이블 문서 분류 문제를 보여줍니다. 데이터셋은 다음 과정을 기반으로 무작위로 생성됩니다.

  • 레이블 수 선택: n ~ Poisson(n_labels)
  • N 번 반복하여 클래스 c 선택: c ~ Multinomial(theta)
  • 문서 길이 선택: k ~ Poisson(length)
  • K 번 반복하여 단어 w 선택: w ~ Multinomial(theta_c)

이 과정에서 거부 샘플링 (rejection sampling) 을 사용하여 n 이 2 보다 크고 문서 길이가 0 이 되지 않도록 합니다. 마찬가지로 이미 선택된 클래스는 거부됩니다. 두 클래스 모두에 할당된 문서는 두 가지 색상의 원으로 둘러싸여 표시됩니다.

VM 팁

VM 시작이 완료되면 왼쪽 상단 모서리를 클릭하여 Notebook 탭으로 전환하여 연습을 위한 Jupyter Notebook에 접근합니다.

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

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

라이브러리 가져오기

이 단계에서는 필요한 라이브러리를 가져옵니다: numpy, matplotlib, make_multilabel_classification 함수는 sklearn.datasets에서 가져오고, OneVsRestClassifierSVCsklearn.multiclass에서, PCACCAsklearn.decomposition에서 가져옵니다.

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_multilabel_classification
from sklearn.multiclass import OneVsRestClassifier
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from sklearn.cross_decomposition import CCA

플롯 함수 정의

이 단계에서는 plot_hyperplaneplot_subfigure 함수를 정의합니다. plot_hyperplane 함수는 분리 초평면을 얻는 데 사용되고, plot_subfigure 함수는 서브플롯을 그리는 데 사용됩니다.

def plot_hyperplane(clf, min_x, max_x, linestyle, label):
    ## 분리 초평면을 구합니다.
    w = clf.coef_[0]
    a = -w[0] / w[1]
    xx = np.linspace(min_x - 5, max_x + 5)  ## 선의 길이를 충분히 길게 합니다.
    yy = a * xx - (clf.intercept_[0]) / w[1]
    plt.plot(xx, yy, linestyle, label=label)


def plot_subfigure(X, Y, subplot, title, transform):
    if transform == "pca":
        X = PCA(n_components=2).fit_transform(X)
    elif transform == "cca":
        X = CCA(n_components=2).fit(X, Y).transform(X)
    else:
        raise ValueError

    min_x = np.min(X[:, 0])
    max_x = np.max(X[:, 0])

    min_y = np.min(X[:, 1])
    max_y = np.max(X[:, 1])

    classif = OneVsRestClassifier(SVC(kernel="linear"))
    classif.fit(X, Y)

    plt.subplot(2, 2, subplot)
    plt.title(title)

    zero_class = np.where(Y[:, 0])
    one_class = np.where(Y[:, 1])
    plt.scatter(X[:, 0], X[:, 1], s=40, c="gray", edgecolors=(0, 0, 0))
    plt.scatter(
        X[zero_class, 0],
        X[zero_class, 1],
        s=160,
        edgecolors="b",
        facecolors="none",
        linewidths=2,
        label="Class 1",
    )
    plt.scatter(
        X[one_class, 0],
        X[one_class, 1],
        s=80,
        edgecolors="orange",
        facecolors="none",
        linewidths=2,
        label="Class 2",
    )

    plot_hyperplane(
        classif.estimators_[0], min_x, max_x, "k--", "Boundary\nfor class 1"
    )
    plot_hyperplane(
        classif.estimators_[1], min_x, max_x, "k-.", "Boundary\nfor class 2"
    )
    plt.xticks(())
    plt.yticks(())

    plt.xlim(min_x - 0.5 * max_x, max_x + 0.5 * max_x)
    plt.ylim(min_y - 0.5 * max_y, max_y + 0.5 * max_y)
    if subplot == 2:
        plt.xlabel("첫 번째 주성분")
        plt.ylabel("두 번째 주성분")
        plt.legend(loc="upper left")

데이터셋 생성

이 단계에서는 sklearn.datasetsmake_multilabel_classification 함수를 사용하여 데이터셋을 생성합니다.

X, Y = make_multilabel_classification(
    n_classes=2, n_labels=1, allow_unlabeled=True, random_state=1
)

서브플롯 플롯

이 단계에서는 plot_subfigure 함수를 사용하여 서브플롯을 그립니다.

plt.figure(figsize=(8, 6))

plot_subfigure(X, Y, 1, "레이블 없는 샘플 포함 + CCA", "cca")
plot_subfigure(X, Y, 2, "레이블 없는 샘플 포함 + PCA", "pca")

X, Y = make_multilabel_classification(
    n_classes=2, n_labels=1, allow_unlabeled=False, random_state=1
)

plot_subfigure(X, Y, 3, "레이블 없는 샘플 제외 + CCA", "cca")
plot_subfigure(X, Y, 4, "레이블 없는 샘플 제외 + PCA", "pca")

plt.subplots_adjust(0.04, 0.02, 0.97, 0.94, 0.09, 0.2)
plt.show()

요약

이 실험에서는 scikit-learn 을 사용하여 다중 레이블 문서 분류 문제를 보여주었습니다. make_multilabel_classification 함수를 사용하여 데이터셋을 생성하고 plot_subfigure 함수를 사용하여 서브플롯을 그렸습니다.