函数 chart() 中的 result_dict 变量没有被赋值,如何实现
时间: 2024-03-10 10:46:20 浏览: 57
要实现在函数 `chart()` 中使用 `result_dict` 变量,需要在函数 `button_click()` 中生成 `result_dict` 并将其传递给函数 `chart()`。可以将 `result_dict` 定义为全局变量,并在 `button_click()` 函数中赋值,然后在 `chart()` 函数中使用即可。
以下是修改后的代码示例:
```
import tkinter as tk
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
seeds = pd.read_csv("seed2.csv", sep='\t', header=None)
X = seeds.iloc[:, :7].copy()
y = seeds.iloc[:, -1].copy()
global result_dict
def knn_score(k, X, y):
# 构造算法对象
knn = KNeighborsClassifier(n_neighbors=k)
scores = []
train_scores = []
random = NIrandom_state.get()
global test_size
for i in range(100):
# 拆分
if random_state != "":
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test, random_state=random)
else:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test)
# 训练
knn.fit(X_train, y_train)
# 评价模型
scores.append(knn.score(X_test, y_test))
# 经验评分
train_scores.append(knn.score(X_train, y_train))
return np.array(scores).mean(), np.array(train_scores).mean()
def root4():
root4 = tk.Toplevel()
# 建立顶层控件wind
root4.geometry("800x600")
# 设置窗口大小
root4.title("测试集与训练集划分")
# 设置窗口标题
label1 = tk.Label(root4, text="测试集与训练集划分", font=("Arial", 16))
label1.pack()
global NIrandom_state, NItest_size
NIrandom_state = tk.IntVar()
tk.Label(root4, text="random_state:").place(x=50, y=50)
tk.Entry(root4, textvariable=NIrandom_state).place(x=190, y=50)
NItest_size = tk.DoubleVar()
tk.Label(root4, text="用于测试的数据集比例:").place(x=50, y=110)
tk.Entry(root4, textvariable=NItest_size).place(x=190, y=110)
# 添加按钮
global button1, button2
button1 = tk.Button(root4, text="运算", font=("Arial", 12), command=button_click)
button1.place(x=50, y=150)
button2 = tk.Button(root4, text="图表展示", font=("Arial", 12), command=chart)
button2.place(x=200, y=150)
# 添加文本框
global text1
text1 = tk.Text(root4, width=50, height=10)
text1.place(x=50, y=200)
def button_click():
global test, random, result_dict
random = int(NIrandom_state.get())
test = float(NItest_size.get())
result_dict = {}
k_list = [1, 3, 5, 7, 9, 11]
for k in k_list:
score, train_score = knn_score(k, X, y)
result_dict[k] = [score, train_score]
result = pd.DataFrame(result_dict).T.copy()
result.columns = ['Test', 'Train']
text = tk.Text(root4)
text.place(x=100, y=220)
text.insert("end", str(X_train))
text.insert("end", str(X_test))
text.insert("end", str(y_train))
text.insert("end", str(y_test))
text1.delete(1.0, tk.END)
text1.insert(tk.END, str(result))
def chart():
root5 = tk.Toplevel()
root5.title("结果图形")
fig = Figure()
ax = fig.add_subplot(111)
k_list = [1, 3, 5, 7, 9, 11]
global result_dict
result = pd.DataFrame(result_dict).T.copy()
result.columns = ['Test', 'Train']
result.plot(kind='line', ax=ax)
ax.set_xticks(k_list)
canvas = FigureCanvasTkAgg(fig, master=root5)
canvas.get_tk_widget().pack()
canvas.draw()
root4()
```
在这个修改后的代码中,`result_dict` 变量定义为全局变量,并在 `button_click()` 函数中生成和赋值,然后在 `chart()` 函数中使用。在 `chart()` 函数中,将 `result_dict` 转换为 `DataFrame` 对象,并通过 `plot` 方法将结果绘制在 `Figure` 对象上。最后,将 `FigureCanvasTkAgg` 对象插入到 `Toplevel` 窗口中,就可以显示结果图形了。
阅读全文