Recursive AI

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.

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

Terminal
dotnet add package RecursiveAI.OneModel

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

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

C#
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:

C#
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")

Run a scikit-learn random forest with ONNX in C# · Run a LightGBM ONNX regressor in C#


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

All onemodel recipes