卡住python

时间:2017-08-30 19:30:48

标签: python matplotlib machine-learning k-means

我在实施k手段时遇到了麻烦。具体来说,我无法绘制不同颜色的点,绿色表示一个簇,红色表示另一个簇。我的代码在逻辑上是有道理的,我只需要有人指出为什么matplotlib没有绘制点。

from matplotlib import pyplot as plt
import random, math


def plotRandomCentroid(maxx, minx, maxy, miny): # Function to create a random centroid
    return [random.uniform(minx, maxx), random.uniform(miny, maxy)]


x = [4.4, 3.2, 4.6, 4, 4.1, 2.9, 2.9] # Weight data
y = [31, 19, 32, 25, 29, 17, 11] # Height data

plt.title("Big Dogs and Small Dogs")
plt.ylabel("Height (cm)")
plt.xlabel("Weight (kg)")


k = 2 # Centroid data
centroid1 = [plotRandomCentroid(max(x), min(x), max(y), min(y))]
centroid2 = [plotRandomCentroid(max(x), min(x), max(y), min(y))]


plt.scatter(centroid1[0][0], centroid1[0][1], color = "maroon") # Scatters centroids
plt.scatter(centroid2[0][0], centroid1[0][1], color = "green")


for j in xrange(1): # Updating centroid positions
    cent1hyp = math.sqrt(centroid1[0][0]**2 + centroid1[0][1]**2)
    cent2hyp = math.sqrt(centroid2[0][0]**2 + centroid2[0][1]**2)
    for i in xrange(len(x)):
        pointx = x[i-1]
        pointy = y[i-1]
        pointhyp = math.sqrt(pointx**2 + pointy**2)
        cent1dis = cent1hyp - pointhyp
        cent2dis = cent2hyp - pointhyp
        if abs(cent1dis) < abs(cent2dis):
            plt.plot(pointx, pointy, color = "lime")
        else:
            plt.plot(pointx, pointy, color = "red")


plt.show()

我现在要引导您完成我的代码。首先,我导入我的库并创建一个在我的数据范围内创建质心的函数。接下来,我将数据包含在x和y列表中,并为图形创建一些标签。然后我决定我想要多少个集群(我还没有找到变量&#39; k&#39;然后我可能会删除它)并在&#39; centroid1&#39;中生成一个质心。和&#39; centroid2&#39;。在此之后,我绘制了它们。质心有一个较深的绿色和红色,现在我试图用更浅的颜色绘制每个数据点。对于x在xrange中的主要内容&#39;循环将重复直到收敛。 &#39; cent1hyp&#39;和&#39; cent2hyp&#39;计算出质心的斜边,或者换句话说是距离点(0,0)的距离。接下来,我遍历数据,每个数据点都会出现以下代码。我创建了变量&#39; pointx&#39;和尖锐的&#39;临时保存每个点的x和y坐标。然后我计算了点的斜边,或者坐标(0,0)与毕达哥拉斯定理的距离。如果你和我在一起,你应该知道我现在对我的数据点,质心1和2有斜边。为了确定这个点应该是哪个聚类,我重新安排了毕达哥拉斯定理来解决这个问题。基于hypotenuses的数据点和质心之间的距离。现在......这里出了问题...我写了一个if-else语句来绘制浅绿色或浅红色的点,这取决于哪个质心更接近。当我运行我的代码时,只绘制了质心。救命!希望我已经给你足够的细节来帮助我。如果你不喜欢我的问题,请问我这件事而不是投票我的问题,因为这只是懒惰和可怜。我的声誉很低,所以一个糟糕的问题会对我的帐户产生重大影响。感谢

0 个答案:

没有答案