数据预处理与可视化工具 - Python Tkinter 实现
import tkinter as tk
from tkinter import messagebox
from PIL import Image, ImageTk
import pandas as pd
import numpy as np
from tkinter import *
from tkinter import filedialog
from sklearn import preprocessing
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn import metrics
import matplotlib.pyplot as plt
from pyecharts.charts import Pie
from pyecharts.charts import Bar
from sklearn.ensemble import RandomForestClassifier
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg as FigureCanvas
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
root = Tk()#创建一个窗口
root.title('数据预处理与可视化')#给窗口命名
root.geometry('3000x2000')#设置窗口的大小
lb1 =Label(root, text='导入数据集')#root是主体,text是内容
lb1.place(relx=0.1, rely=0.1, relwidth=0.8, relheight=0.1)#设置位置
#数据集的导入
def openfile():#打开文件并显示
filepath = filedialog.askopenfilename() #获得选择好的文件,单个文件
imgtype=['.csv']#规定读取的文件类型
return filepath
def duru(txt):
txt=pd.read_csv(txt)
txt=txt.describe()
text = Text(root)
text.place(rely=0.6, relheight=0.4)
text.insert(END, txt)
btn1 =Button(root,text='导入csv数据集',command=lambda:duru(openfile()))
btn1.place(relx=0.6, rely=0.2, relwidth=0.3, relheight=0.1)
#数据预处理
c=True
def jiance():
t=data.isnull().any()
global c
global yu1
if c==True:
c=False
yu1=Label(root,text=t)
yu1.pack(side='bottom',expand=True)
else:
yu1.pack_forget()
c=True
def tianchong():
global a
global yu2
a1=data.fillna(data.mean())
a=a1.fillna(method='bfill')
global c
if c==True:
c=False
yu2=Label(root,text=a)
yu2.pack(side='bottom',expand=True)
else:
yu2.pack_forget()
c=True
def biaozhun():
my_zscore=preprocessing.StandardScaler()
a[['LoanAmount']]=my_zscore.fit_transform(a[['LoanAmount']])
global c
global yu3
if c==True:
c=False
yu3=Label(root,text=a)
yu3.pack(side='bottom',expand=True)
else:
yu3.pack_forget()
c=True
def bianma():
#特征编码
onehot=pd.get_dummies((a[['Gender']]),prefix='Gender')
global c
global yu4
if c==True:
c=False
yu4=Label(root,text=onehot)
yu4.pack(side='bottom',expand=True)
else:
yu4.pack_forget()
c=True
btn3 = Button(root, text='缺失值检测', command=lambda:jiance())
btn3.place(relx=0.6, rely=0.4, relwidth=0.3, relheight=0.1)
btn4 = Button(root, text='缺失值填充', command=lambda:tianchong())
btn4.place(relx=0.6, rely=0.5, relwidth=0.3, relheight=0.1)
btn5 = Button(root, text='标准化', command=lambda:biaozhun())
btn5.place(relx=0.6, rely=0.6, relwidth=0.3, relheight=0.1)
btn6 = Button(root, text='特征编码', command=lambda:bianma())
btn6.place(relx=0.6, rely=0.7, relwidth=0.3, relheight=0.1)
#数据可视化
class DataPreprocessor:
def __init__(self, master):
self.master = master
self.data = None
self.X_train = None
self.X_test = None
self.y_train = None
self.y_test = None
self.clf = None
# 窗口布局
self.load_data_button = tk.Button(master, text='导入数据', command=self.load_data)
self.load_data_button.place(relx=0.1, rely=0.2, relwidth=0.3, relheight=0.1)
self.train_button = tk.Button(master, text='训练模型', command=self.train_model)
self.train_button.place(relx=0.4, rely=0.2, relwidth=0.3, relheight=0.1)
self.plot_type = tk.StringVar() # 创建一个变量,用于存储当前选中的图像类型
self.plot_type.set('请选择图像类型') # 设置默认值
self.plot_menu = tk.OptionMenu(master, self.plot_type, '直方图', '饼图', '箱线图')
self.plot_menu.configure(width=20)
self.plot_menu.place(relx=0.6, rely=0.3, relwidth=0.3, relheight=0.1)
self.plot_button = tk.Button(master, text='绘制图像', command=self.plot)
self.plot_button.place(relx=0.6, rely=0.8, relwidth=0.3, relheight=0.1)
def plot(self):
plot_type = self.plot_type.get()
if plot_type == '请选择图像类型':
tk.messagebox.showwarning(title='Warning', message='请选择图像类型!')
return
elif plot_type == '直方图':
self.histogram()
elif plot_type == '饼图':
self.pie_chart()
elif plot_type == '箱线图':
self.box_plot()
def load_data(self):
# 加载数据集,这里使用 Pandas 库中的 read_csv() 方法
filename = filedialog.askopenfilename(initialdir='./data', title='Select file', filetypes=(('CSV files', '*.csv'),))
if not filename:
return
self.data = pd.read_csv(filename)
tk.messagebox.showinfo(title='Info', message=f'成功导入 {self.data.shape[0]} 条数据!')
# 划分训练集和测试集
self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(self.data.iloc[:, :-1], self.data.iloc[:, -1], test_size=0.3)
tk.messagebox.showinfo(title='Info', message=f'成功划分训练集和测试集!')
def histogram(self):
# 检查是否已经完成数据导入、划分训练集和测试集、训练模型等操作
if not hasattr(self, 'X_train') or not hasattr(self, 'X_test') or not hasattr(self, 'y_train') or not hasattr(self, 'y_test') or not self.clf:
tk.messagebox.showwarning(title='Warning', message='请先导入数据集并划分训练集和测试集,再训练模型!')
return
# 绘制直方图
fig, ax = plt.subplots()
ax.hist(self.X_train.iloc[:, 0], bins=20)
ax.set_xlabel('Feature 1')
ax.set_ylabel('Count')
ax.set_title('Histogram')
histogram_window = tk.Toplevel(self.master)
canvas = FigureCanvasTkAgg(fig, master=histogram_window)
canvas.draw()
canvas.get_tk_widget().pack()
toolbar = NavigationToolbar2Tk(canvas, histogram_window)
toolbar.update()
canvas.get_tk_widget().pack()
def pie_chart(self):
if not hasattr(self, 'X_train') or not hasattr(self, 'X_test') or not hasattr(self, 'y_train') or not hasattr(self, 'y_test') or not self.clf:
tk.messagebox.showwarning(title='Warning', message='请先导入数据集并划分训练集和测试集,再训练模型!')
return
counts = self.data['species'].value_counts()
# 创建饼状图
self.fig = Figure(figsize=(5, 4), dpi=100)
self.fig.add_subplot(111).pie(counts, labels=counts.index, autopct='%1.1f%%')
# 在窗口中显示饼状图
self.canvas = FigureCanvasTkAgg(self.fig, master=self.master)
self.canvas.draw()
self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
def box_plot(self):
# 检查是否已经完成数据导入、划分训练集和测试集、训练模型等操作
if not hasattr(self, 'X_train') or not hasattr(self, 'X_test') or not hasattr(self, 'y_train') or not hasattr(self, 'y_test') or not self.clf:
tk.messagebox.showwarning(title='Warning', message='请先导入数据集并划分训练集和测试集,再训练模型!')
return
# 绘制箱线图,用于展示特征的分布情况
fig, ax = plt.subplots()
box_data = pd.concat([self.X_train, self.X_test], axis=1)
box_data.columns = [f'Feature {i}' for i in range(1, box_data.shape[1]+1)]
box_data.plot(kind='box', ax=ax)
ax.set_title('Box plot')
box_window = tk.Toplevel(self.master)
canvas = FigureCanvasTkAgg(fig, master=box_window)
canvas.draw()
canvas.get_tk_widget().pack()
toolbar = NavigationToolbar2Tk(canvas, box_window)
toolbar.update()
canvas.get_tk_widget().pack()
def train_model(self):
# 检查是否已经完成数据导入、划分训练集和测试集等操作
if not hasattr(self, 'X_train') or not hasattr(self, 'X_test') or not hasattr(self, 'y_train') or not hasattr(self, 'y_test'):
tk.messagebox.showwarning(title='Warning', message='请先导入数据集并划分训练集和测试集!')
return
# 训练模型,这里使用 scikit-learn 库中的 RandomForestClassifier() 方法
self.clf = RandomForestClassifier(n_estimators=10, max_depth=5)
self.clf.fit(self.X_train, self.y_train)
tk.messagebox.showinfo(title='Info', message='成功训练模型!')
if __name__ == '__main__':
root = tk.Tk()
root.geometry('600x400')
app = DataPreprocessor(root)
root.mainloop()
原文地址: https://www.cveoy.top/t/topic/ooPp 著作权归作者所有。请勿转载和采集!