from sklearn.neighbors import KNeighborsClassifier k_score = [] k_range = range(1,228) for k in range(1,228): knn = KNeighborsClassifier(n_neighbors=k) knn.fit(X_train,y_train) k_score.append([k,knn.score(X_test,y_test)]) print(k, k_score) k_score = np.array(k_score) k_score = pd.DataFrame(k_score,columns=['Value of K for KNN','Score']) ax = sns.lineplot(data=k_score,x="Value of K for KNN", y="Score",)。改写这段代码
时间: 2024-02-06 20:10:52 浏览: 165
KNN(K-Nearest Neighbors)算法详细介绍及使用示例
以下是改写后的代码,主要对输出进行了优化,使用了f-string格式化字符串,并将k_score转换为pandas DataFrame后使用了seaborn绘制折线图:
```
import pandas as pd
import numpy as np
import seaborn as sns
from sklearn.neighbors import KNeighborsClassifier
k_score = []
for k in range(1, 228):
knn = KNeighborsClassifier(n_neighbors=k)
knn.fit(X_train, y_train)
score = knn.score(X_test, y_test)
k_score.append([k, score])
print(f"K={k}, Score={score:.4f}")
k_score = pd.DataFrame(k_score, columns=['Value of K for KNN', 'Score'])
sns.lineplot(data=k_score, x="Value of K for KNN", y="Score")
```
阅读全文