如何用精度公式验证预测(k-NN-模型)?

How to verify the prediction (k-NN-model) with accuracy-formula?

我需要完成代码并创建一个函数来计算我的模型使用测试数据与预测数据相比的准确性。预测模式已在另一个代码中解决。

我必须给出的输入是精度公式。公式见图(Here, Accuracy-formula)公式。

我当前的代码和令我震惊的地方是准确度公式:

acc = ((1/predictions) * ((np.sum(predictions == y_test[:]))))

return acc


k = 25
 
accuracy = calculate_accuracy(X_train, y_train, X_test, y_test, k)

print("Accuracy of the model is {:.3f}.".format(accuracy))"

而我应该比较“预测”与“y_test”,计算公式为:正确预测数除以预测数。但我现在知道如何在代码中实现它了。

使用分类器分数来确定准确性。它应该符合你的功能。该模型准确率为 98%

import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt
import seaborn as sns

from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.metrics import roc_curve
from sklearn.model_selection import cross_val_score
from collections import Counter
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
X=iris.data
y=iris.target

df=pd.DataFrame(X,columns=iris.feature_names)
print(df.head(5))
 knn = KNeighborsClassifier(algorithm='auto',
                         leaf_size=30,
                         metric='minkowski',
                         metric_params=None,
                         n_jobs=1,
                         n_neighbors=25,
                         p=1,
                         weights='uniform')

X_train, X_test, y_train, y_test= train_test_split(X,y,test_size=0.3, random_state=21, stratify=y)

knn.fit(X_train,y_train)
train_accuracy = knn.score(X_train, y_train)

plt.title('k-NN: Varying Number of Neighbors')
plt.plot(neighbors, test_accuracy, label = 'Testing Accuracy')
plt.plot(neighbors, train_accuracy, label = 'Training Accuracy')
plt.legend()
plt.xlabel('Number of Neighbors')
plt.ylabel('Accuracy')
plt.show()

y_pred=knn.predict(X_test)

print(confusion_matrix(y_test,y_pred))
print(classification_report(y_test,y_pred))

print("Manual Accuracy",sum(y_pred==y_test)/len(y_test))