---
title: "Calculate binary cross-entropy with logits in C#"
url: https://recursiveai.org/onemodel/cookbook/calculate-binary-cross-entropy-from-logits/
description: "Calculate binary cross-entropy directly from logits in C# with OneModel. Compare mean and sum reductions and see why the loss needs no separate sigmoid."
version: "1.3.0"
---

# 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.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneModel.Training) · [GitHub](https://github.com/recursive-ai-oss/onemodel-csharp) · [Docs](https://recursiveai.org/onemodel/docs/) · [Download example (.zip)](https://recursiveai.org/onemodel/cookbook/calculate-binary-cross-entropy-from-logits/calculate-binary-cross-entropy-from-logits.zip)

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

```shell
dotnet add package RecursiveAI.OneModel.Training
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
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](https://recursiveai.org/onemodel/cookbook/calculate-binary-cross-entropy-from-logits/calculate-binary-cross-entropy-from-logits.zip) 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.

```csharp
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
```

## Related recipes

- [Differentiate a tensor expression](https://recursiveai.org/onemodel/cookbook/differentiate-tensor-expression/)
- [Calculate CTC loss for padded sequences](https://recursiveai.org/onemodel/cookbook/calculate-ctc-loss-for-padded-sequences/)

## 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](https://recursiveai.org/onemodel/docs/training/) 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.
