基于 KNN 预测计算 TN、TP、FP、FN

Calculating TN,TP,FP,FN based on KNN predictions

我正在构建一个 KNN 分类器来预测某条记录是否为 red/green。模型本身看起来不错,但我在 for 循环中计算 tn、fn、tp、fp 时遇到问题。基本上每个循环,我需要比较 ndarray pred_k ("y_hat") 和静态 ndarray Y_test ("y_actual.) Thoughts?

X = df [["f1","f2", "f3", "f4"]]. values
Y = df [["color"]]. values.ravel()

scaler = StandardScaler (). fit (X)
X = scaler . transform (X)

X_train ,X_test , Y_train , Y_test = train_test_split (X,Y, test_size =0.5 , random_state =0)
error_rate = []

for k in [3 , 5, 7, 9, 11]:
    knn_classifier = KNeighborsClassifier ( n_neighbors =k)
    knn_classifier . fit ( X_train , Y_train )
    pred_k = knn_classifier . predict ( X_test )
    error_rate . append (np. mean ( pred_k != Y_test ))

你可以使用sklearn的混淆矩阵。

from sklearn.metrics import confusion_matrix
tn, fp, fn, tp = confusion_matrix(Y_test, pred_k).ravel()