pythoncolorsdata-miningsilhouette

Having the same color for a silhouette plot and for a PCA plot


My aim is to plot a silhouette graph next to a PCA reduction graph. My idea was that for the sake of comprehension, I'd like having the same colors on both graphs. For now, I am getting that :

enter image description here

the problem I am facing is that on the first plot, I am plotting each silhouette after the other and I have a kind of a list of colors, whereas for the second plot, everything is plot at the same time.

So I don't have any idea how I could switch from one mode to the other.

Here is the code, it should be a working example.

def silhouette_PCA(data, model, n):
    reduced_data = sklearn.decomposition.PCA(n_components=2).fit_transform(data)
    model.fit(reduced_data)

    fig, (ax1, ax2) = plt.subplots(1, 2)
    fig.set_size_inches(18, 7)

    sample_silhouette_values = sklearn.metrics.silhouette_samples(reduced_data, model.fit_predict(reduced_data)  )

    y_lower = 10
    for i in range(n):
        ith_cluster_silhouette_values = sample_silhouette_values[ model.fit_predict(reduced_data) == i]
        ith_cluster_silhouette_values.sort()
        size_cluster_i = ith_cluster_silhouette_values.shape[0]
        y_upper = y_lower + size_cluster_i
        ############################### first color
        color = plt.cm.nipy_spectral(float(i) / n)
        ax1.fill_betweenx(np.arange(y_lower, y_upper),
                          0, ith_cluster_silhouette_values,
                          facecolor=color, edgecolor=color, alpha=0.7)

        y_lower = y_upper + 10 

#########################################################################################
    h = .02

    x_min, x_max = reduced_data[:, 0].min() - 1, reduced_data[:, 0].max() + 1
    y_min, y_max = reduced_data[:, 1].min() - 1, reduced_data[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

    Z = model.predict(np.c_[xx.ravel(), yy.ravel()])

    Z = Z.reshape(xx.shape)
    ax2.imshow(Z, interpolation='nearest',
              extent=(xx.min(), xx.max(), yy.min(), yy.max()),
               ############################# here the 2nd Color
              cmap=plt.cm.Paired,
              aspect='auto', origin='lower')
    ax2.plot(reduced_data[:, 0], reduced_data[:, 1], 'k.', markersize=2)


    plt.show()


model = sklearn.cluster.KMeans(n_clusters = 3)
data = feat_matrix
silhouette_PCA(data,model,3)

thank you.


Solution

  • I ve done that, and it works fine :

    def silhouette_PCA(data, model, n):
        reduced_data = sklearn.decomposition.PCA(n_components=2).fit_transform(data)
        model.fit(reduced_data)
    
        fig, (ax1, ax2) = plt.subplots(1, 2)
        fig.set_size_inches(18, 7)
    
        sample_silhouette_values = sklearn.metrics.silhouette_samples(reduced_data, model.fit_predict(reduced_data)  )
    
        y_lower = 10
        for i in range(n):
            ith_cluster_silhouette_values = sample_silhouette_values[ model.fit_predict(reduced_data) == i]
            ith_cluster_silhouette_values.sort()
            size_cluster_i = ith_cluster_silhouette_values.shape[0]
            y_upper = y_lower + size_cluster_i
            ############################### first color
            color = plt.cm.nipy_spectral(float(i) / n)
            ax1.fill_betweenx(np.arange(y_lower, y_upper),
                              0, ith_cluster_silhouette_values,
                              facecolor=color, edgecolor=color, alpha=0.7)
    
            y_lower = y_upper + 10 
    
        list = []
        for i in range(n):
          list = np.append(list , plt.cm.nipy_spectral(float(i) / n)    )
        list = np.reshape(list,  (n,4) )
        cmap = mpl.colors.ListedColormap(list)
        bounds= range(n)
        norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
    #########################################################################################
        h = .02
    
        x_min, x_max = reduced_data[:, 0].min() - 1, reduced_data[:, 0].max() + 1
        y_min, y_max = reduced_data[:, 1].min() - 1, reduced_data[:, 1].max() + 1
        xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    
        Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
        Z = Z.reshape(xx.shape)
        ax2.imshow(Z, interpolation='nearest',
                  extent=(xx.min(), xx.max(), yy.min(), yy.max()),
                   ############################# here the 2nd Color
                  cmap= cmap, #plt.cm.Paired,
                  aspect='auto', origin='lower')
        ax2.plot(reduced_data[:, 0], reduced_data[:, 1], 'k.', markersize=2)
    
    
        plt.show()
    
    
    model = sklearn.cluster.KMeans(n_clusters = 7)
    data = feat_matrix
    silhouette_PCA(data,model,7)
    

    enter image description here

    enter image description here