K-means algorithm Python implementation

Source: Internet
Author: User

 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.