Recursive AI

Calculate binary cross-entropy with logits in C#

OneModel is a free, open-source neural-network library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Pass raw scores and 0 or 1 targets to BceWithLogits. No sigmoid step is needed.

Terminal
dotnet add package RecursiveAI.OneModel.Training

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OneModel.Tensors;
using RecursiveAI.OneModel.Training;
 
using var scope = new ActivationScope();
var shape = Shape.Create(3);
using var logits = Tensor.FromSpan<float>(
    [-2, 0, 2], shape);
using var targets = Tensor.FromSpan<float>(
    [0, 1, 1], shape);
using var mean = Losses.BceWithLogits(
    logits, targets);
using var sum = Losses.BceWithLogits(
    logits, targets, mean: false);
Console.WriteLine(FormattableString.Invariant(
    $"Mean: {mean.Data<float>()[0]:F6}"));
Console.WriteLine(FormattableString.Invariant(
    $"Sum:  {sum.Data<float>()[0]:F6}"));

Prints:

Text
Mean: 0.315668
Sum:  0.947003

The ActivationScope returns the loss calculation’s temporary tensors to the pool when the scope ends. The sum adds the three element losses; the mean divides that total by three. If the Float32 logits and targets don’t have the same shape, BceWithLogits throws TensorShapeException.

Paste the code above into Program.cs of a new dotnet new console project and dotnet run, or unzip the example and dotnet run.

Variations

Score a confident but wrong prediction. Add this to the example. A logit of -100 is strongly against class 1, so a target of 1 incurs a large loss.

C#
using var wrongLogit = Tensor.Scalar(-100f);
using var positive = Tensor.Scalar(1f);
using var penalty = Losses.BceWithLogits(
    wrongLogit, positive);
Console.WriteLine(penalty.Data<float>()[0]);
Text
100

The short answer

Call Losses.BceWithLogits(logits, targets) with equally shaped Float32 tensors. Supply the raw output of the model head and targets of 0 or 1; the API also accepts fractional targets in [0, 1]. It returns the mean loss as a scalar. Pass mean: false for the sum. Don’t apply sigmoid before this call.

How is binary cross-entropy calculated from logits?

For logit x and target t, OneModel’s loss computes softplus(x) − x × t per element. This is the logarithmic penalty for a Bernoulli prediction: for target 1 it penalizes low probability of 1, and for target 0 it penalizes high probability of 1. At logit 0, the implied probability is one half, so the loss is about 0.693147 for either target. In the example, -2 against 0 and 2 against 1 each give about 0.126928; the middle prediction contributes the larger penalty.

Do you apply sigmoid before binary cross-entropy with logits?

No. This API works from the same raw score that a sigmoid would turn into a probability. Computing the loss directly avoids taking the logarithm of a probability that a separate sigmoid step rounded to 0 or 1. Applying sigmoid first would make the loss treat a probability like 0.5 as a new logit, which no longer represents an even chance. Keep logits for this loss and use sigmoid separately if you need probabilities for display or decisions.

What’s the difference between mean and sum reduction?

A reduction combines all element losses into one number. mean: true, the default, divides the sum by the total element count, not just the batch size. In a [batch, labels] tensor that includes every label position for every example. Use mean for a per-element average and sum when you need a total, such as when accumulating losses and dividing by the combined element count yourself. If you compare two batches with different element counts, their sums alone don’t tell you which had the larger average error.

All onemodel recipes