不使用 sklearn 计算机器学习模型的准确性

Miz*_*ory 2 python machine-learning scikit-learn

我正在尝试使用以下函数计算我创建的模型的准确性:

def accuracy(y_true, y_pred):
    accuracy = np.mean(y_pred == y_true)
    return accuracy
Run Code Online (Sandbox Code Playgroud)

有时它显示的准确性正确,有时则不正确。有人可以解释一下如何修复该函数以使其显示与 sklearn precision_score 相同的精度吗?这是我从我的方法中得到的结果的示例。

y_true
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]

y_pred
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]

KNN classification accuracy:  0.0
KNN classification accuracy sklearn:  0.9428571428571428
Run Code Online (Sandbox Code Playgroud)

Ant*_*uis 5

使用 numpy 您可以执行以下操作:

import numpy as np
acc = np.sum(np.equal(y_true, y_pred)) / len(y_true)
Run Code Online (Sandbox Code Playgroud)