Python Kmeans clustering is relatively simple, first requires the import NumPy, from the Sklearn.cluster import Kmeans module:
Import NumPy as NP from Import Kmeans
Then read the TXT file, get the corresponding data and convert it to numpy array:
X == open ('rktj4.txt') for in f: = Re.compile ('\s+') x.append ([Float (Regex.Split (v) [3]), float ( Regex.Split (v) [6= Np.array (X)
Set the number of classes and cluster:
N_clusters = 5= Kmeans (n_clusters). Fit (X)
Full code:
ImportNumPy as NP fromSklearn.clusterImportKmeansImportMatplotlib.pyplot as PltImportReX=[]f= Open ('Rktj4.txt') forVinchF:regex= Re.compile ('\s+') X.append ([Float (Regex.Split (v) [3]), float (Regex.Split (v) [6])) X=Np.array (X) n_clusters= 5CLS=Kmeans (n_clusters). Fit (X) cls.labels_markers= ['^','x','o','*','+'] forIinchRange (n_clusters): members= Cls.labels_ = =i plt.scatter (x[members, 0], x[members,1], s=60, Marker=markers[i], c='b', alpha=0.5) PrintPlt.title ("') plt.show ()
Operation Result:
Python machine Learning (1): Kmeans Clustering