【问题标题】:Why is the graph changing on every run为什么每次运行时图表都会发生变化
【发布时间】:2021-03-30 04:50:32
【问题描述】:

那里。所以我建立了一个 Kmean 集群程序;但是,每次我运行程序时,情节都会发生变化。我不知道为什么会这样,如果有人可以提供帮助,将不胜感激。

import numpy as np
import matplotlib.pyplot as plt
import random
def cal_centroids(clusters, cluster_array,k):
    new_centroids= []
    for c in range(k):
        x= 0
        y=0
        count=0
        for i in range(len(clusters)):
            if clusters[i]==c:
                x+=cluster_array[i][0]
                y+=cluster_array[i][1]
                count+=1
        x/=count
        y/=count
        new_centroids.append([x,y])
    return new_centroids
def assign_clusters(centroids,cluster_array):
    clusters=[]
    for i in range(cluster_array.shape[0]):
        distances=[]
        for centroid in centroids:
            distances.append(calc_distance(centroid,cluster_array[i]))
        cluster=[z for z, val in enumerate(distances) if val==min(distances)]
        clusters.append(cluster[0])
    return clusters
def calc_distance(x1,x2):
    return (sum((x1-x2)**2))**0.5

#from here 主要是存储数据、初始化质心和为数据分配集群标签

def kmean(data,no_clusters,iterations): 
    s= random.sample(range(data.shape[0]),no_clusters)
    centroids= []
    for i in s:
        centroids.append(data[i,:])
    clusters= assign_clusters(centroids,data)
    initial_centroids= [i for i in centroids]
    for i in range(0,iterations):
        centroids= cal_centroids(clusters,data,no_clusters)
        cluster= assign_clusters(centroids,data)
    dict_centroids= {}
    for i in range(no_clusters):
        dict_centroids[i]=[]
    for i in range(no_clusters):
        for j in range(data.shape[0]):
            if(clusters[j]==i):
                dict_centroids[i].append(data[j,:])
    return dict_centroids,centroids,clusters

def extract_file(file_name):
    file = open(file_name,'r')
    lines = [list(map(int, line.strip("\n").split(","))) for line in file]
    x= np.array(lines)
    return x
data= extract_file("backyard.txt")
dict_centroids,centroids,clusters= kmean(data,2,8)
x= data[:,0]
y= data[:,1]
fig=plt.figure()
scatter= plt.scatter(x,y,c=clusters,s=40)
for i,j in centroids:
    plt.scatter(i,j,s=50,c='red',marker= '+')
plt.xlabel("Vitamin C")
plt.ylabel("GLA")
plt.title("File backyard 2 groups Displayed")
fig.show()

后院名单是这样的:

40,40
10,10
200,200
230,231
40,43 
15,45 
220,190

【问题讨论】:

    标签: python arrays graph cluster-computing


    【解决方案1】:

    我还没有运行您的代码,但是,如果每次运行时图形都发生变化,则无需担心。 K-means 是一种使用随机开始的算法(我假设您在代码中使用这一行:s= random.sample(range(data.shape[0]),no_clusters))。不能保证 K-means 会收敛到全局最小值,但它会根据随机开始收敛到局部最小值。 您可以尝试通过使用 NumPy 设置随机种子来修复随机开始:numpy.random.seed(42)

    【讨论】:

      猜你喜欢
      • 2021-02-11
      • 2021-09-16
      • 2016-05-24
      • 1970-01-01
      • 2012-05-18
      • 1970-01-01
      • 2016-06-12
      • 1970-01-01
      • 2022-08-04
      相关资源
      最近更新 更多