首页 > 解决方案 > 为算法遗传聚类创建图例

问题描述

我正在使用遗传算法优化构建一个集群,但在为集群图创建图例时遇到问题。这是我的代码。请帮我。

c1 = numpy.array([X[:, 0], X[:, 1]]).T
c2 = numpy.array([G[:, 0], G[:, 1]]).T
c3 = numpy.array([H[:, 0], H[:, 1]]).T

data = numpy.concatenate((c1, c2, c3), axis=0)

我已经标记了这个情节

matplotlib.pyplot.scatter(X[:, 0], X[:, 1], label="cluster 0")
    matplotlib.pyplot.scatter(G[:, 0], G[:, 1], label="cluster 1")
    matplotlib.pyplot.scatter(H[:, 0], H[:, 1], label="cluster 2")
    matplotlib.pyplot.title("Optimal Clustering")
    plt.legend()
    matplotlib.pyplot.show()

在此处输入图像描述

def cluster_data(solution, solution_idx):
    global num_clusters, feature_vector_length, data
    cluster_centers = []
    all_clusters_dists = []
    clusters = []
    clusters_sum_dist = []

    for clust_idx in range(num_clusters):
        cluster_centers.append(solution[feature_vector_length*clust_idx:feature_vector_length*(clust_idx+1)])
        cluster_center_dists = euclidean_distance(data, cluster_centers[clust_idx])
        all_clusters_dists.append(numpy.array(cluster_center_dists))

    cluster_centers = numpy.array(cluster_centers)
    all_clusters_dists = numpy.array(all_clusters_dists)

    cluster_indices = numpy.argmin(all_clusters_dists, axis=0)
    for clust_idx in range(num_clusters):
        clusters.append(numpy.where(cluster_indices == clust_idx)[0])
        if len(clusters[clust_idx]) == 0:
            clusters_sum_dist.append(0)
        else:
            clusters_sum_dist.append(numpy.sum(all_clusters_dists[clust_idx, clusters[clust_idx]]))

    clusters_sum_dist = numpy.array(clusters_sum_dist)

    return cluster_centers, all_clusters_dists, cluster_indices, clusters, clusters_sum_dist

num_clusters = 3
feature_vector_length = data.shape[1]
num_genes = num_clusters * feature_vector_length

ga_instance = pygad.GA(num_generations=1000,
                       sol_per_pop=10,
                       init_range_low=0,
                       init_range_high=20,
                       num_parents_mating=5,
                       keep_parents=2,
                       num_genes=num_genes,
                       fitness_func=fitness_func,
                       suppress_warnings=True)

ga_instance.run()

best_solution, best_solution_fitness, best_solution_idx = ga_instance.best_solution()
print("Best solution is {bs}".format(bs=best_solution))
print("Fitness of the best solution is {bsf}".format(bsf=best_solution_fitness))
print("Best solution found after {gen} generations".format(gen=ga_instance.best_solution_generation))

cluster_centers, all_clusters_dists, cluster_indices, clusters, clusters_sum_dist = cluster_data(best_solution, best_solution_idx)

对于这个情节,能不能像上面那样从一开始就标注的情节图例显示?

for cluster_idx in range(num_clusters):
    cluster_x = data[clusters[cluster_idx], 0]
    cluster_y = data[clusters[cluster_idx], 1]
    matplotlib.pyplot.scatter(cluster_x, cluster_y)
    matplotlib.pyplot.scatter(cluster_centers[cluster_idx, 0], cluster_centers[cluster_idx, 1], marker="s", s=100)
matplotlib.pyplot.title("Clustering using PyGAD")
matplotlib.pyplot.show()

在此处输入图像描述

我很困惑,因为对于这个绘图显示,cluster_xcluster_y数据是分开的。如何根据形成的集群以及集群中心创建图例?

先感谢您。

标签: pythonmatplotlibplotcluster-analysisscatter-plot

解决方案


通过添加label=到大多数 matplotlib 函数,将生成一个图例条目。图例将由plt.legend().

新的图例处理程序允许将条目组合成元组。这是一个例子:

from matplotlib import pyplot as plt
from sklearn.datasets import make_blobs  # to get some test data
from matplotlib.legend_handler import HandlerTuple

num_clusters = 5
data, cluster, cluster_centers = make_blobs(n_samples=100, centers=num_clusters, n_features=2, return_centers=True)
for cluster_idx in range(num_clusters):
    cluster_x = data[cluster == cluster_idx, 0]
    cluster_y = data[cluster == cluster_idx, 1]
    plt.scatter(cluster_x, cluster_y, label=f'Cluster {cluster_idx}')
    plt.scatter(cluster_centers[cluster_idx, 0], cluster_centers[cluster_idx, 1],
                marker='s', s=100,
                label=f'Center {cluster_idx}')
handles, labels = plt.gca().get_legend_handles_labels()
handles = [tuple(handles[i:i + 2]) for i in range(0, len(handles), 2)]
labels = [labels[i] for i in range(0, len(labels), 2)]

plt.legend(handles=handles, labels=labels, handler_map={tuple: HandlerTuple(None)})
plt.show()

带有组合条目的图例

另一种可能性是将图例显示为两列:

handles, labels = plt.gca().get_legend_handles_labels()
handles = [handles[i] for i in range(0, len(handles), 2)]+[handles[i] for i in range(1, len(handles), 2)]
labels = [labels[i] for i in range(0, len(labels), 2)] + [labels[i] for i in range(1, len(labels), 2)]
plt.legend(handles=handles, labels=labels, ncol=2)

有两列的图例


推荐阅读