torch.nn.BCELoss()

BCELoss is a binary cross entropy function. The official examples are as follows:

You put in a tensor of 1×3 for probability, and through the activation function Sigmoid, you calculate the cross entropy with Target.

    #Official Example
    m = nn.Sigmoid()
    loss = nn.BCELoss()
    input = torch.randn(3, requires_grad=True)
    target = torch.empty(3).random_(2)
    print("input:",input,"\n","target:",target)
    output = loss(m(input), target)
    print(output)
    output.backward()
Copy the code

My own implementation of the function looks like this:

def myBCE(predict,label): Loss = 0 loss = 0 loss = 0 m = predict. Size (dim = 0) Loss = -torch. Sum (label * torch. Log (predict) + (one-label) * torch. Log (one-predict)) / m return lossCopy the code
    #My Implement
    my_output = myBCE(m(input),target)
    print(my_output)
Copy the code

The final calculation results of both are as follows:

You can see that BCELoss is exactly the same.