fromNumPyImport* fromRandomImport_instImportNumPy as NPImportMatplotlib.pyplot as Pltdeffilemat (filename): File= open (filename,"R") contain=file.readlines () Count=len (contain) features= Zeros ((count, Len (Contain[0].split (','))-1)) Labels=[] Index=0 forLinesinchContain:line=Lines.strip () ListForm= Line.split (",") Features[index:]= Listform[0:len (listform)-1] Labels.append (listform[-1]) Index+ = 1returnlabels, features" "Initialize Cluster center, randomly take 3 sample points" "definitcentroids (DataSet, K):#Initialize K centroid, random fetch #take K vectors as the initial center vector in the dataset return_inst.sample (DataSet, K)" "the distance between sample points and each cluster center" "defOushi (Point1, Point2): Distance= Np.sqrt (Np.sum (Np.square (Point1-Point2))) returnDistance" "calculate a sample center point" "defGetmean (clusterdict): Centerset=list () forKeyinchClusterdict.keys (): Centerset.append (Np.mean (Np.array (Clusterdict[key)), Axis=0))#average of samples in a cluster returnCenterset#returns a list of cluster centers" "Clustering" "defcluster (DataSet, Centerset): Clusterdict=dict () forIteminchDataset:flag=0 mindistance= Float ("inf") forIinchRange (len (centerset)): Distance=Oushi (item, centerset[i])ifDistance <mindistance:mindistance=Distance Flag= I#Class I ifFlag not inchClusterdict.keys (): Clusterdict[flag]=list () clusterdict[flag].append (item)returnclusterdict" "The squared error is calculated based on the square of the Euclidean distance between the sample point in the cluster and the center point of the cluster ." "defGete (clusterdic): Sum= 0.0 forKeyinchClusterdic.keys (): Distance= 0.0centerdistance=Np.mean (Clusterdic[key]) forIteminchClusterdic[key]: Dis=Np.square (Oushi (item, centerdistance)) distance+=dis sum+=DistancereturnsumdefShowcluster (Centerset, clusterdict):#Show Clustering ResultsColorMark= ['or','ob','og','OK','Oy','ow']#different cluster classes are labeled ' or '--' o ' represents the circle, ' R ' for Red, ' B ': BlueCentroidmark = ['Dr','DB','DG','DK','Dy','DW']#centroid markers above ' d ' represent the prism forKeyinchClusterdict.keys (): Plt.plot (centerset[key][0], centerset[key][1], Centroidmark[key], markersize=12)#Quality Heart Point forIteminchClusterdict[key]: Plt.plot (item[0], item[1], Colormark[key])#points under a cluster classplt.show ()if __name__=='__main__': DataLabels, DataSet= Filemat ("TestData.txt") Firstcenterset= Initcentroids (List (DataSet), 4) Print('The initial cluster centers are:', Firstcenterset) clusterdict=cluster (DataSet, firstcenterset) Newe=Gete (clusterdict) OldE=-0.0001Print("------------------------------------The 1th iteration------------------------------------") forKeyinchClusterdict.keys (): Buff=list () forIinchRange (len (clusterdict[key)): Buff.append (List (clusterdict[key][i]))Print(Key,' -', Buff) Newcenterset=list () forIinchRange (len (firstcenterset)): Newcenterset.append (List (firstcenterset[i) )Print('k mean vector:', Newcenterset)Print('average mean square error:', Newe) showcluster (Firstcenterset, clusterdict) d= 2 whileABS (Newe-olde)! = 0:#iteration ends when two consecutive cluster results are less than 0.0001Centerset = Getmean (clusterdict)#get a new centroidclusterdict = Cluster (DataSet, Centerset)#New Clustering ResultsOldE =Newe Newe=Gete (clusterdict)Print('-------------------------------------------The first%d iterations-------------------------------------------'%d) forKeyinchClusterdict.keys (): Buff=list () forIinchRange (len (clusterdict[key)): Buff.append (List (clusterdict[key][i]))Print(Key,' -', Buff) Newcenterset=list () forIinchRange (len (firstcenterset)): Newcenterset.append (List (firstcenterset[i) )Print('k mean vector:', Newcenterset)Print('average mean square error:', Newe) showcluster (Centerset, clusterdict) d+ = 1
K-means algorithm Python implementation