【发布时间】:2021-03-26 13:18:01
【问题描述】:
对于一个计算机科学项目,我必须实施 Lloyds-Algorithm,这似乎工作得很好。我想可视化迭代。这也有点用了:
import numpy
import matplotlib.pyplot as plt
# Variables to test
centroids = [[[2, 3],[6, 7]],
[[1, 2],[7, 8]]]
nearest_centroid_of_samples = [[0, 0, 1, 1, 0],
[0, 1, 1 , 1, 0]]
quant_error = [2.123,1.789]
# Actual code
i=0
for c,ncos, qe in zip(centroids, nearest_centroid_of_samples, quant_error):
# My x and y values
xx = [0, 4, 3, 8, 2]
yy = [1, 3, 9, 5, 2]
title = "Iteration Nr.%d" % (i)
plt.title(title)
# A text I would like to appear
text = "Quantisierungsfehler: %f" % (qe)
plt.text(12.5, 3.5, text)
# Adding my clusters to the plot, ncos encodes the color
plt.scatter(xx, yy, c=ncos, marker='o', alpha=1)
# Here I'm adding my centroids (the middle of each cluster) to the plot
for pos in c:
plt.scatter(pos[0], pos[1], c="red", marker="+")
i = i+1
plt.pause(0.25)
plt.show()
这基本上已经给了我想要的东西。只有一个小问题:似乎每次迭代都在前一个迭代之上。这对我的数据来说没问题,因为它们完美匹配,你看不到这一点。但是质心的红色标记有点出问题了,并且保持一点可见 - 更糟糕的是,我要添加的文本有一个更长的十进制数字,这变得不可读。
我需要如何绘制这个,它绘制了所有新的东西,但仍然在同一个图中?
最好的问候
杜甫
根据建议编辑了一些具有代表性的值。这些不代表劳埃德算法的结果,但仍应显示我的问题出在哪里。
【问题讨论】:
标签: python numpy matplotlib k-means