Calculate accuracy in Binary classification

Hi
I have a NN binary classifier, and the last layer is sigmoid, I use BCEloss
this is my accuracy calculation:

def get_evaluation(y_true, y_prob, list_metrics, epoch):
    # accuracy = accuracy_score(y_true, y_prob)
    y_prob = np.array(y_prob)
    y_prob = np.where(y_prob <= 0.5, 0, y_prob)
    y_prob = np.where(y_prob > 0.5, 1, y_prob)

    accuracy = metrics.accuracy_score(y_true, y_prob)
    return accuracy

is this the correct way to calculate accuracy?

tnx

It seems good to me.

You can use conditional indexing to make it even shorther.

def get_accuracy(y_true, y_prob):
    accuracy = metrics.accuracy_score(y_true, y_prob > 0.5)
    return accuracy

If you want to work with Pytorch tensors, the same functionality can be achieved with the following code:

def get_accuracy(y_true, y_prob):
    assert y_true.ndim == 1 and y_true.size() == y_prob.size()
    y_prob = y_prob > 0.5
    return (y_true == y_prob).sum().item() / y_true.size(0)
4 Likes