2017-03-19 2 views
1

Scikit에서 K- 평균을 사용하여 클러스터링했습니다. 그런 다음 클러스터 영역을 Scikit example에 따라 플로팅했습니다. 다음으로 각 클러스터에 대해 다시 클러스터링을 했으므로 동일한 플롯에 하위 클러스터의 경계를 표시하고 싶습니다. 이 question이 흥미 롭지 만이 방법을 적용하면 축 범위가 변경되고 새 플롯이 나타납니다.Scikit에서 플롯 클러스터 경계

편집 : 다음 내 함수가 될 때 :

def plot_pca_clusters_races_match(pca_km, reduced_data, pca_data_winner, 
            race1_pca_km, race1_reduced_data, race1_pca_data_winner, race1_nclusters, 
            race2_pca_km, race2_reduced_data, race2_pca_data_winner, race2_nclusters, 
            plt_opt, fig_path, race_approach, n_clusters): 

    """ 
    :param pca_km: K-means trained by PCA data (2 components) 
    :param reduced_data: PCA components 
    :param data_winner: player_id, pca_component1, pca_component2, race_id, winner 
    :param plt_opt: space required to plot cluster area 
    :param fig_path: path to save the plot 
    :param race_approach: 
    :param n_clusters: 
    :return: 
    """ 

    race_id_list = ['Z', 'T', 'P'] 
    # 1- Plot cluster area 
    x_min, x_max = reduced_data[:, 0].min() + plt_opt[0], reduced_data[:, 0].max() + plt_opt[1] 
    y_min, y_max = reduced_data[:, 1].min() + plt_opt[2], reduced_data[:, 1].max() + plt_opt[3] 
    step = abs((abs(x_max) - abs(x_min)))/100 
    xx, yy = np.meshgrid(np.arange(x_min, x_max, step), np.arange(y_min, y_max, step)) 
    Z = pca_km.predict(np.c_[xx.ravel(), yy.ravel()]) 
    Z = Z.reshape(xx.shape) 
    plt.figure(1) 
    plt.clf() 

    # Plot cluster regions 
    plt.imshow(Z, interpolation='nearest', 
       extent=(xx.min(), xx.max(), yy.min(), yy.max()), 
       cmap=plt.cm.Paired, 
       aspect='auto', origin='lower') 

    # 2- Plot cluster members 
    race_ids = list(set(pca_data_winner[:, -3])) 

    # Find race type 
    reduced_data_race1 = pca_data_winner[np.where(pca_data_winner[:, -3] == race_ids[0]), :][0] 

    # Plot race 1 
    plt.plot(reduced_data_race1[:, 2], reduced_data_race1[:, 3], 'k.', markersize=4, color='red', 
      label=race_id_list[int(race_ids[0])]) 

    # Plot race 2 
    # If the race is non-symmetric, change color of the cluster members 
    if len(race_ids) > 1: 
     reduced_data_race2 = pca_data_winner[np.where(pca_data_winner[:, -3] == race_ids[1]), :][0] 
     plt.plot(reduced_data_race2[:, 2], reduced_data_race2[:, 3], 'k.', markersize=4, color='green', 
       label=race_id_list[int(race_ids[1])], hold=True) 

    # 3-Plot cluster centers 
    markers = ['d', 'v', 's', '*', 'h', 'p', 'o'] 
    for cluster in range(0, pca_km.cluster_centers_.shape[0]): 
     plt.scatter(pca_km.cluster_centers_[cluster, 0], pca_km.cluster_centers_[cluster, 1], 
        marker=markers[cluster], s=80, linewidths=1, 
        label='Cluster ' + str(cluster), 
        color='b', zorder=4, hold=True) 
     plt.xlabel('PC 1') 
     plt.ylabel('PC 2') 

    plt.legend(prop={'size':8}) 

    # --------------------------------------------- Plot boundaries of sub-clusters 
    x1_min, x1_max = race1_reduced_data[:, 0].min() + plt_opt[0], race1_reduced_data[:, 0].max() + plt_opt[1] 
    y1_min, y1_max = race1_reduced_data[:, 1].min() + plt_opt[2], race1_reduced_data[:, 1].max() + plt_opt[3] 

    step = abs((abs(x_max) - abs(x_min)))/100 
    xx1, yy1 = np.meshgrid(np.arange(x1_min, x1_max, step), np.arange(y1_min, y1_max, step)) 

    Z1 = race1_pca_km.predict(np.c_[xx1.ravel(), yy1.ravel()]) 
    Z1 = Z1.reshape(xx1.shape) 

    # Plot sub-cluster boundaries 
    plt.contour(Z, extent=(xx.min(), xx.max(), yy.min(), yy.max())) 

첫 번째 줄거리 : 윤곽없이 이 enter image description here

+1

는 당신이 문제를 설명하고 여기에 질문을 잊었다 생각 ;-) – ImportanceOfBeingErnest

+0

가 @ImportanceOfBeingErnest :. DI는 자세한 내용을 추가 할 수 있습니다. – YNr

답변

0

첫 번째 줄거리 : enter image description here

countours 및 스케일링을 추가하려고 후 두 번째 플롯의 왼쪽 하단 모서리에 위치합니다. 윤곽이 경우 단순히 Z 어레이의 행 및 열 인덱스 범위.

하면 하나는 컨투어

plt.contour(Z, extent=(..,..,..,..)) 
정도를 제공 할 필요가 (적당한 크기를 부여하지 않기 때문이다 .

또는 결정하기 위해 몇 가지 X와 Y 배열을 지정 좌표

plt.contour(X,Y,Z) 
+0

그러면 도움을 청합니다. 범위를 찾는 방법은 무엇입니까? 나는'plt.contour (Z, extent = (x_min), xx.max(), yy.min(), yy.max())'와'plt.contour (Z, extent = , x_max, y_min, y_max))'. 결과적으로 첫 번째 음모를 유지하고 음모의 중심에 몇 개의 선을 그립니다. – YNr

+0

범위는 imshow 플롯의 범위와 동일해야합니다. 그래서 네가 한 짓이 옳은 것 같아. – ImportanceOfBeingErnest

+0

자, 두 번째 줄거리도 첫 번째 줄거리를 보여 주지만 하위 클러스터 주위에 윤곽선을 넣어야합니다. – YNr