ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [파이썬] 결정경계 그래프 그리기
    Python 2021. 1. 11. 03:29
    반응형

    머신러닝 모델을 만들어 사용하다 보면 분류가 어떻게 되었는지 그래프로 보고 싶을 때 어떻게 하는지 알아보겠습니다.

     

    2D 평면에 나타낼 것이기 때문에 데이터의 차원도 2인 경우만 다루도록 하겠습니다.

     

    먼저 전체 코드와 결과그래프를 본 뒤 자세한 설명을 하겠습니다.

     

    from matplotlib.colors import ListedColormap
    
    def plot_decision_regions(X, y, classifier, resolution=0.02):
        
        # 마커와 컬러맵을 설정합니다
        markers = ('s', 'x', 'o', '^', 'v')
        colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
        cmap = ListedColormap(colors[:len(np.unique(y))])
        
        # 결정 경계를 그립니다.
        x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
        x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
        xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
                              np.arange(x2_min, x2_max, resolution))
        Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
        Z = Z.reshape(xx1.shape)
        plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)
        plt.xlim(xx1.min(), xx1.max())
        plt.ylim(xx2.min(), xx2.max())
        
        # 샘플의 산점도를 그립니다
        for idx, cl in enumerate(np.unique(y)):
            plt.scatter(x=X[y == cl, 0],
                       y=X[y == cl, 1],
                       alpha=0.8,
                       c=colors[idx],
                       marker=markers[idx],
                       label=cl,
                       edgecolor='black')
            
    plot_decision_regions(X_test_std, y_test, classifier=svm_model)

    결정경계 그래프

    결과를 먼저 보면 클래스에 따라 점의 모양이 다르게 나타나 있으며 결정 경계에 따라 바탕색이 다르게 나타나 있습니다. 이 모델 같은 경우 정확도가 70퍼센트가 채 되지 않기 때문에 틀린 부분이 꽤 보이네요

     


    메서드의 파라미터와 같은 상세한 부분은 documetation을 참고해주세요!

    matplotlib.org/3.3.3/contents.html

     

    Overview — Matplotlib 3.3.3 documentation

     

    matplotlib.org


     

    def plot_decision_regions(X, y, classifier, resolution=0.02):
        
        # 마커와 컬러맵을 설정합니다
        markers = ('s', 'x', 'o', '^', 'v')
        colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
        cmap = ListedColormap(colors[:len(np.unique(y))])

    함수의 파라미터 중 X는 특징데이터를 나타내고 y는 라벨, classifier는 사용된 분류기이고 resolution은 신경 쓰지 않으셔도 됩니다. 저 같은 경우 [[ 255 2982] [ -1811 4352] [ 924 7067] [ -6263 7474] [ 2904 6964] [ 558 15126] [ -1 -2598] [ -8708 4583]] 과 같은 X데이터를 사용했고 y는 [0 1 2 1 2 3 5 1 ...] 를 사용했습니다. np.array이구요

    분류기는 svm 모델을 활용했습니다.

     

    makers는 점이 표시될 모양을 나타내고 colors는 경계의 바탕색을 나타내기 위함입니다. ListedColormap 객체는 contourf 메서드에 cmap 파라미터에 전달해주기 위해 선언되었습니다.

     

    # 결정 경계를 그립니다.
        x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
        x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
        xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
                              np.arange(x2_min, x2_max, resolution))
        Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
        Z = Z.reshape(xx1.shape)
        plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)
        plt.xlim(xx1.min(), xx1.max())
        plt.ylim(xx2.min(), xx2.max())

    데이터의 범위 한정해 주는 작업입니다. 위에서 말한 X데이터를 표준화해서 사용했기에 실제 그래프에서는 -4 ~4 정도의 범위를 지니고 있는데요 이러한 범위에서 그래프를 그리는 작업입니다.

     

    # 샘플의 산점도를 그립니다
        for idx, cl in enumerate(np.unique(y)):
            plt.scatter(x=X[y == cl, 0],
                       y=X[y == cl, 1],
                       alpha=0.8,
                       c=colors[idx],
                       marker=markers[idx],
                       label=cl,
                       edgecolor='black')

    바탕색을 칠한 그래프에 점을 찍는 작업입니다. 앞서 선언한 변수들을 전달해주면 됩니다.

     

     

     

    이 글은 머신러닝 교과서 with 파이썬, 사이킷런, 텐서플로(세바스찬 라시카,바히드 미자리리)의 내용을 참고했습니다.
    반응형

    댓글

Designed by Tistory.