import tkinter as tk
from tkinter import filedialog
import pandas as pd
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

# GUI界面
root = tk.Tk()
root.title('数据预处理和模型训练')
root.geometry('400x400')

# 文件选择函数
def select_file():
    filepath = filedialog.askopenfilename()
    file_entry.delete(0, tk.END)
    file_entry.insert(0, filepath)

# 数据读取和预处理函数
def process_data():
    # 读入数据集
    filepath = file_entry.get()
    df = pd.read_csv(filepath)
    
    # 数据清洗
    df.dropna(inplace=True)
    
    # 数据标准化
    scaler = StandardScaler()
    scaled_data = scaler.fit_transform(df)
    
    # 输出预处理后的数据
    output_text.delete('1.0', tk.END)
    output_text.insert(tk.END, str(scaled_data))
    
    # 将数据分为特征和标签
    X = scaled_data[:, :-1]
    y = scaled_data[:, -1]
    
    # 划分训练集和测试集
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
    
    # 训练线性回归模型
    model = LinearRegression()
    model.fit(X_train, y_train)
    
    # 在测试集上评估模型
    y_pred = model.predict(X_test)
    r2 = r2_score(y_test, y_pred)
    result_text.delete('1.0', tk.END)
    result_text.insert(tk.END, '模型评估结果:R2 Score = {:.4f}'.format(r2))

# 文件选择按钮和输入框
file_label = tk.Label(root, text='请选择数据文件:')
file_label.pack()
file_entry = tk.Entry(root, width=30)
file_entry.pack()
file_button = tk.Button(root, text='选择', command=select_file)
file_button.pack()

# 数据处理按钮和输出框
process_button = tk.Button(root, text='处理数据', command=process_data)
process_button.pack()
output_label = tk.Label(root, text='预处理后的数据:')
output_label.pack()
output_text = tk.Text(root, width=50, height=10)
output_text.pack()

# 模型训练和评估界面
result_label = tk.Label(root, text='模型训练和评估')
result_label.pack()
result_text = tk.Text(root, width=50, height=2)
result_text.pack()

root.mainloop()

该代码使用了线性回归模型进行训练。

原文地址: https://www.cveoy.top/t/topic/ojPk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录