# 封装函数来进行knn试探性运算 def knn_score(k,X,y): # 构造算法对象 knn = KNeighborsClassifier(n_neighbors = k) scores = [] train_scores = [] for i in range(100): # 拆分 X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=1) # 训练 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() # 调参 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]利用这段代码调用tkinter库实现界面
时间: 2024-03-03 19:51:25 浏览: 56
可以使用`tkinter`库来创建一个窗口界面,然后在界面上添加按钮,当按钮被点击时,调用`knn_score()`函数进行试探性运算并将结果显示在界面上。
以下是一个简单的示例代码:
```python
import tkinter as tk
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
import numpy as np
def knn_score(k,X,y):
# 构造算法对象
knn = KNeighborsClassifier(n_neighbors = k)
scores = []
train_scores = []
for i in range(100):
# 拆分
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=1)
# 训练
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()
# 创建窗口
root = tk.Tk()
root.title("KNN试探性运算")
# 添加标签
label1 = tk.Label(root, text="KNN试探性运算", font=("Arial", 16))
label1.pack()
# 添加按钮
button1 = tk.Button(root, text="运算", font=("Arial", 12))
button1.pack()
# 添加文本框
text1 = tk.Text(root, width=50, height=10)
text1.pack()
# 绑定按钮事件
def button_click():
X = # 定义特征矩阵
y = # 定义目标变量
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]
# 将结果显示在文本框中
text1.delete(1.0, tk.END)
text1.insert(tk.END, str(result_dict))
button1.config(command=button_click)
# 运行窗口
root.mainloop()
```
注意:此示例代码中的`X`和`y`需要根据实际情况进行定义。
阅读全文