---
title: "Run an XGBoost ONNX classifier in C#"
url: https://recursiveai.org/onemodel/cookbook/run-xgboost-onnx-classifier/
description: "Run an onnxmltools XGBoost classifier export in C#, read its int64 labels by name, and index the float32 probability tensor by row and class."
version: "1.5.0"
---

# Run an XGBoost ONNX classifier in C#

**OneModel** is a free, open-source .NET library from Recursive AI for running ONNX models, including scikit-learn pipelines and XGBoost and LightGBM models. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneModel) · [GitHub](https://github.com/recursive-ai-oss/onemodel-csharp) · [Docs](https://recursiveai.org/onemodel/docs/) · [Download example (.zip)](https://recursiveai.org/onemodel/cookbook/run-xgboost-onnx-classifier/run-xgboost-onnx-classifier.zip)

Get a class ID and probabilities from `booster.onnx` (in the zip).

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

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

```csharp
using RecursiveAI.OneModel;
using var model = Model.Load("booster.onnx");
float[] row = [-1, -1, 0, 0, 0, 0];
var labels = model.Run<float, long>(
    row, [1, 6], "label");
var scores = model.Run<float, float>(
    row, [1, 6], "probabilities");
Console.WriteLine($"Class {labels[0]}");
foreach (float score in scores)
    Console.WriteLine(FormattableString
        .Invariant($"{score:F4}"));
```

[The example](https://recursiveai.org/onemodel/cookbook/run-xgboost-onnx-classifier/run-xgboost-onnx-classifier.zip) is the full program below: unzip it and `dotnet run`. To run only the code above, paste it into `Program.cs` of a new `dotnet new console` project, add the package, copy `booster.onnx` from the zip into the project folder, and run `dotnet run`.

Prints:

```text
Class 0
0.8714
0.0914
0.0373
```

## Full program

The synthetic classifier takes six float32 features. The program passes `[-1, -1, 0, 0, 0, 0]` and `[1, 1, 0, 0, 0, 0]` as a single batch. It reads the second dimension of the probability tensor to find how many values belong to each row.

```csharp
using RecursiveAI.OneModel;
using System.Globalization;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
using var model = Model.Load("booster.onnx");
float[] rows = [-1, -1, 0, 0, 0, 0,
                 1,  1, 0, 0, 0, 0];
var labels = model.Run<float, long>(rows, [2, 6], "label");
var scores = model.Run<float, float>(rows, [2, 6], "probabilities", out var shape);
int classes = shape[1];
Console.WriteLine($"Probabilities: {shape[0]} rows × {classes} classes");
for (int row = 0; row < labels.Length; row++)
{
    Console.WriteLine($"Row {row + 1}: class {labels[row]}");
    for (int column = 0; column < classes; column++)
        Console.WriteLine($"  class {column}: {scores[row * classes + column]:F4}");
}
```

`dotnet run` prints:

```text
Probabilities: 2 rows × 3 classes
Row 1: class 0
  class 0: 0.8714
  class 1: 0.0914
  class 2: 0.0373
Row 2: class 2
  class 0: 0.0605
  class 1: 0.0971
  class 2: 0.8423
```

An output name that isn’t in `model.Session.Outputs` throws `SessionException`; use the names in your export.

## Variations

Append this to the snippet at the top to predict again with the first feature missing:

```csharp
Console.WriteLine("With feature 1 missing:");
row[0] = float.NaN;
var missing = model.Run<float, long>(
    row, [1, 6], "label");
Console.WriteLine($"Class {missing[0]}");
```

Prints:

```text
With feature 1 missing:
Class 1
```

Using XGBoost 3.4.1 and onnxmltools 1.16.0, export a fitted `XGBClassifier` named `booster` with six float32 features per row. Install `packaging` in the Python environment as well.

```python
from onnxmltools import convert_xgboost, save_model
from onnxmltools.convert.common.data_types import FloatTensorType

inputs = [("input", FloatTensorType([None, 6]))]
export = convert_xgboost(booster, initial_types=inputs, target_opset=15)
save_model(export, "booster.onnx")
```

## Related recipes

[Run a scikit-learn random forest with ONNX in C#](https://recursiveai.org/onemodel/cookbook/run-scikit-learn-onnx-classifier/) · [Run a LightGBM ONNX regressor in C#](https://recursiveai.org/onemodel/cookbook/run-lightgbm-onnx-regressor/)

---

## The short answer

Load the `.onnx` export with `Model.Load`. Read `label` as `long[]` and `probabilities` as `float[]`. In this export both are tensors: the labels contain one integer per row, while the probabilities have shape `[rows, classes]`. The full program uses the returned shape to find each row’s probabilities in the flat C# array.

## How do I convert an XGBoost model to ONNX format?

Start with the fitted `XGBClassifier` in Python and pass it to `onnxmltools.convert_xgboost`, declaring your input with `FloatTensorType` and the model’s feature count. A native XGBoost model file isn’t itself an ONNX graph. The zip already contains the result of export, so the C# project needs neither Python nor the original XGBoost model file.

The [OneModel tree-model guide](https://recursiveai.org/onemodel/docs/guide-tree-models/) describes standalone classifier exports. If you trained with named columns, keep that column order when building the input tensor in .NET. The graph sees numbers at feature positions. Changing two feature positions can change a prediction even though the array still has the right length. If preprocessing happened before fitting the booster, supply the resulting features, not the unprocessed values.

## How do I read XGBoost classifier probabilities from ONNX?

The `onnxmltools` XGBoost export doesn’t add ZipMap. The named numeric overload with `out` shape reads its two-dimensional float32 tensor. Use `row * classes + column` to pick one probability. The fixture was trained on the integer classes `0`, `1`, and `2` in that order, so the program can use the column index as the class ID. If your application encoded categories into integers, carry the mapping from those integers to your own labels separately. Read the predicted ID from `label` rather than relying on rounded printed probabilities to pick a winner.

Check the output names and shapes when replacing the file. `[1, 6]` describes one row of six input features. It does not say how many classes the model has. For a batch, the same six feature positions repeat for every row; the output shape tells you how many probability columns repeat for each row.

For features that were missing at training time, the exported trees can follow their learned missing-value branches. Use `float.NaN` for a missing float feature when that is how your model was trained; a zero is an ordinary value and can take a different branch. The variation shows the changed prediction for this particular row and model.
