k means

Solutions on MaxInterview for k means by the best coders in the world

showing results for - "k means"
Juan Manuel
11 Mar 2019
1import tkinter as tk
2from tkinter import filedialog
3import pandas as pd
4from pandas import DataFrame
5import matplotlib.pyplot as plt
6from sklearn.cluster import KMeans
7from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
8
9root= tk.Tk()
10
11canvas1 = tk.Canvas(root, width = 400, height = 300,  relief = 'raised')
12canvas1.pack()
13
14label1 = tk.Label(root, text='k-Means Clustering')
15label1.config(font=('helvetica', 14))
16canvas1.create_window(200, 25, window=label1)
17
18label2 = tk.Label(root, text='Type Number of Clusters:')
19label2.config(font=('helvetica', 8))
20canvas1.create_window(200, 120, window=label2)
21
22entry1 = tk.Entry (root) 
23canvas1.create_window(200, 140, window=entry1)
24
25def getExcel ():
26    
27    global df
28    import_file_path = filedialog.askopenfilename()
29    read_file = pd.read_excel (import_file_path)
30    df = DataFrame(read_file,columns=['x','y'])  
31    
32browseButtonExcel = tk.Button(text=" Import Excel File ", command=getExcel, bg='green', fg='white', font=('helvetica', 10, 'bold'))
33canvas1.create_window(200, 70, window=browseButtonExcel)
34
35def getKMeans ():
36    global df
37    global numberOfClusters
38    numberOfClusters = int(entry1.get())
39    
40    kmeans = KMeans(n_clusters=numberOfClusters).fit(df)
41    centroids = kmeans.cluster_centers_
42    
43    label3 = tk.Label(root, text= centroids)
44    canvas1.create_window(200, 250, window=label3)
45    
46    figure1 = plt.Figure(figsize=(4,3), dpi=100)
47    ax1 = figure1.add_subplot(111)
48    ax1.scatter(df['x'], df['y'], c= kmeans.labels_.astype(float), s=50, alpha=0.5)
49    ax1.scatter(centroids[:, 0], centroids[:, 1], c='red', s=50)
50    scatter1 = FigureCanvasTkAgg(figure1, root) 
51    scatter1.get_tk_widget().pack(side=tk.RIGHT, fill=tk.BOTH)
52    
53processButton = tk.Button(text=' Process k-Means ', command=getKMeans, bg='brown', fg='white', font=('helvetica', 10, 'bold'))
54canvas1.create_window(200, 170, window=processButton)
55
56root.mainloop()
57