我正在尝试在 Iris 数据集上实现 K 最近邻,但在进行预测后,yhat 100% 没有错误,肯定有什么问题,但我不知道它是什么......
我创建了一个名为 class_id 的列,我在其中进行了更改:
- 山楂 = 1.0
- 杂色 = 2.0
- 弗吉尼亚 = 3.0
该列的类型为 float。
获取 X 和 Y
x = df[['sepal length', 'sepal width', 'petal length', 'petal width']].values
type(x) 显示 nparray
y = df['class_id'].values
type(y) 显示 nparray
标准化数据
x = preprocessing.StandardScaler().fit(x).transform(x.astype(float))
创建训练和测试
x_train, x_test, y_train, y_test = train_test_split(x,y,test_size = 0.2, random_state = 42)
检查最佳 K 值:
Ks = 12
for i in range(1,Ks):
k = i
neigh = KNeighborsClassifier(n_neighbors=k).fit(x_train,y_train)
yhat = neigh.predict(x_test)
score = metrics.accuracy_score(y_test,yhat)
print('K: ', k, ' score: ', score, '\n')
结果:
K:1 得分:0.96666666666666667
K:2 得分:1.0
K:3 得分:1.0
K:4 得分:1.0
K:5 得分:1.0
K:6 得分:1.0
K:7 得分:1.0
K:8 得分:1.0
K:9 得分:1.0
K:10 得分:1.0
K:11 得分:1.0
使用 K = 5 打印 y_test 和 yhat
print(yhat)
print(y_test)
结果:
你的帽子:[2。 1. 3. 2. 2. 1. 2. 3. 2. 2. 3. 1. 1. 1. 1. 2. 3. 2. 2. 3. 1. 3. 1. 3. 3.3.3.3.1.1.]
y_测试:[2。 1. 3. 2. 2. 1. 2. 3. 2. 2. 3. 1. 1. 1. 1. 2. 3. 2. 2. 3. 1. 3. 1. 3. 3.3.3.3.1.1.]
所有这些都不应该100%正确,一定有问题
最佳答案
尝试制作一个混淆矩阵。测试测试数据的每个示例,并检查特异性、敏感性、准确性和精密度的指标。
地点:
TN = True Negative
FN = False Negative
FP = False Positive
TP = True Positive
在这里您可以检查特异性和敏感性之间的区别 https://dzone.com/articles/ml-metrics-sensitivity-vs-specificity-difference
这里有一个关于如何使用 sklearn 在 python 中获取混淆矩阵的示例。
还尝试制作 ROC 曲线(可选) https://en.wikipedia.org/wiki/Receiver_operating_characteristic
关于python - Knn 预测在 y_test 上达到 100%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56369481/