如何打印kmeans集群python

数据挖掘 Python
2022-02-10 08:37:28

数据集有 3 个特征。集群的数量是两个。

我正在弄清楚如何使用散点图打印具有 3 个特征列并使用 kmeans 聚集成 2 个集群的数据的集群。

训练数据为数据框格式,数据为活动数据集:

X =  pd.concat([train_data['start'], train_data['end'], train_data  ['duration']], axis=1)  
kmeans.fit(X)  
Y_pred = kmeans.predict(X)  
plt.scatter(X.iloc[:,0], X.iloc[:,1], c=Y_pred, cmap=plt.cm.Paired)  
plt.legend()  
plt.title('train data')  
plt.show()  
getting following output:

在此处输入图像描述

2个回答

代码不言自明...

    from sklearn.cluster import KMeans
    from sklearn.datasets.samples_generator import make_blobs
    np.random.seed(0)
    centers = [[1, 1], [-1, -1]]
    n_clusters = len(centers)
    X, labels_true = make_blobs(n_samples=3000, 
                                centers=centers, 
                                cluster_std=0.5)

def plot_cluster_data(X, c=[1]*X.shape[0], mu=None):
    fig = plt.figure(figsize=(8, 8))
    ax = fig.add_subplot(1, 1, 1)
    if len(np.unique(c)) == 1:
        ax.plot(X[:,0], X[:,1], 'o')
    else:
        ix = np.where(c==1)
        ax.plot(X[ix,0], X[ix,1], 'o', 
                markerfacecolor='red')
        ax.plot(mu[0,0], mu[0,1], 'o', 
                markerfacecolor='red', 
                markersize=12)
        ix = np.where(c==0)
        ax.plot(X[ix,0], X[ix,1], 'o', 
                markerfacecolor='green')
        ax.plot(mu[1,0], mu[1,1], 'o', 
                markerfacecolor='green', 
                markersize=12)
    if not mu is None:
        ax.plot(mu[0,0], mu[0,1], 'o', 
                markerfacecolor='red', 
                markersize=12)
        ax.plot(mu[1,0], mu[1,1], 'o', 
                markerfacecolor='green', 
                markersize=12)        
    plt.show()

plot_cluster_data(X)

在此处输入图像描述

clst = KMeans(n_clusters=2, random_state=2342)
clst.fit(X)
mu = clst.cluster_centers_
plot_cluster_data(X, mu = mu)

在此处输入图像描述

3D 绘图

3 个特征表明您的数据是 3 维的。因此,您可以使用 3D 绘图。以下代码将绘制 3 维数据。x是一个以 3 个特征为列的 numpy 矩阵,行是实例。然后y是您从 k-means 获得的集群标签。

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from numpy import where

# Plots 2 features, with an output, shows the decision boundary
def plot3D(x, y):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    pos = where(y == 1)
    neg = where(y == 0)

    color = ['r', 'b', 'y', 'k', 'g', 'c', 'm']

    for i in range(30):
        ax.scatter(x[i, 0], x[i, 1],x[i, 2], marker='o', c=color[int(y[i])-1])
    #ax.scatter(x[:,1], x[:,2], y)
    ax.set_xlabel('X Label')
    ax.set_ylabel('Y Label')
    ax.set_zlabel('Z Label')

    axes = plt.axis()
    plt.show()

plot3D(X, cluster_labels)

这将为您提供以下情节

在此处输入图像描述

二维绘图

或者,您可以将数据投影到二维中。您可以通过折叠三个维度中的任何一个来天真地做到这一点。例如,这将只显示前 2 个特征,第三个将投影到第一个和第二个特征的平面上。

plt.scatter(X[:,0], X[:,1], c=cluster_labels)
plt.show()

您还可以绘制第二个和第三个特征,其中第一个特征投影为

plt.scatter(X[:,1], X[:,2], c=cluster_labels)
plt.show()

天真地投影数据可能会导致问题,因此您可以使用特征嵌入方法。在这里,我将给出 4 种不同方法的示例:Isomap、MDS、谱嵌入和 TSNE(我最喜欢的)。

这是我可以访问的连续数据,但您可以轻松地对集群数据执行相同操作。只需设置标签y作为你确定的集群。

from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.manifold import TSNE, SpectralEmbedding, Isomap, MDS

boston = load_boston()
X = boston.data
Y = boston.target

X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.33, shuffle= True)

# Embed the features into 2 features using TSNE
X_embedded_iso  = Isomap(n_components=2).fit_transform(X)
X_embedded_mds  = MDS(n_components=2, max_iter=100, n_init=1).fit_transform(X)
X_embedded_tsne = TSNE(n_components=2).fit_transform(X)
X_embedded_spec = SpectralEmbedding(n_components=2).fit_transform(X)

print('Description of the dataset: \n')

print('Input shape : ', X_train.shape)
print('Target shape: ', y_train.shape)

print('Embed the features into 2 features using Spectral Embedding: ', X_embedded_spec.shape)
print('Embed the features into 2 features using TSNE: ', X_embedded_tsne.shape)

fig = plt.figure(figsize=(12,5),facecolor='w')
plt.subplot(1, 2, 1)
plt.scatter(X_embedded_iso[:,0], X_embedded_iso[:,1], c = Y, cmap = 'hot')
plt.title('2D embedding using Isomap \n The color of the points is the price')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.colorbar()
plt.tight_layout()

plt.subplot(1, 2, 2)
plt.scatter(X_embedded_mds[:,0], X_embedded_mds[:,1], c = Y, cmap = 'hot')
plt.title('2D embedding using MDS \n The color of the points is the price')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.colorbar()
plt.show()
plt.tight_layout()

fig = plt.figure(figsize=(12,5),facecolor='w')
plt.subplot(1, 2, 1)
plt.scatter(X_embedded_spec[:,0], X_embedded_spec[:,1], c = Y, cmap = 'hot')
plt.title('2D embedding using Spectral Embedding \n The color of the points is the price')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.colorbar()
plt.tight_layout()

plt.subplot(1, 2, 2)
plt.scatter(X_embedded_tsne[:,0], X_embedded_tsne[:,1], c = Y, cmap = 'hot')
plt.title('2D embedding using TSNE \n The color of the points is the price')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.colorbar()
plt.show()
plt.tight_layout()

在此处输入图像描述

在此处输入图像描述