---
title: "Run a scikit-learn random forest with ONNX in C#"
url: https://recursiveai.org/onemodel/cookbook/run-scikit-learn-onnx-classifier/
description: "Load a scikit-learn RandomForestClassifier in C# and read its string labels and ZipMap class probabilities by name with OneModel."
version: "1.5.0"
---

# Run a scikit-learn random forest with ONNX 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-scikit-learn-onnx-classifier/run-scikit-learn-onnx-classifier.zip)

Read a label and its probability from `forest.onnx` (in the zip). `skl2onnx` exports probabilities as a dictionary keyed by class name (ZipMap).

```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("forest.onnx");
float[] row = [-1, -1, 0, 0, 0, 0];
var label = model.RunStrings<float>(
    row, [1, 6], "output_label")[0];
var map = model.RunStringMaps<float>(
    row, [1, 6], "output_probability")[0];
Console.WriteLine(FormattableString.Invariant(
    $"{label}: {map[label]:F4}"));
```

[The example](https://recursiveai.org/onemodel/cookbook/run-scikit-learn-onnx-classifier/run-scikit-learn-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 `forest.onnx` from the zip into the project folder, and run `dotnet run`.

Prints:

```text
setosa: 0.8318
```

## Full program

The zip’s synthetic forest takes six float32 features in order. The program sends two rows, `[-1, -1, 0, 0, 0, 0]` and `[1, 1, 0, 0, 0, 0]`, and prints every probability with its class name.

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

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
using var model = Model.Load("forest.onnx");
float[] rows = [-1, -1, 0, 0, 0, 0,
                 1,  1, 0, 0, 0, 0];
var labels = model.RunStrings<float>(rows, [2, 6], "output_label");
var maps = model.RunStringMaps<float>(rows, [2, 6], "output_probability");
for (int row = 0; row < labels.Length; row++)
{
    Console.WriteLine($"Row {row + 1}: {labels[row]}");
    foreach (var (label, probability) in maps[row])
        Console.WriteLine($"  {label}: {probability:F4}");
}
```

`dotnet run` prints:

```text
Row 1: setosa
  setosa: 0.8318
  versicolor: 0.1682
  virginica: 0.0000
Row 2: virginica
  setosa: 0.0000
  versicolor: 0.1225
  virginica: 0.8775
```

Using a numeric tensor accessor for either of these outputs throws `SessionException`; the error names the accessor to use.

## Variations

Read the output names and kinds when you swap in another export:

```csharp
using RecursiveAI.OneModel;
using var model = Model.Load("forest.onnx");
foreach (var output in model.Session.Outputs)
    Console.WriteLine($"{output.Name}: {output.Kind}");
```

Prints:

```text
output_label: StringTensor
output_probability: SequenceOfMaps
```

Using scikit-learn 1.9.1 and skl2onnx 1.20.0, export a fitted `RandomForestClassifier` with string labels. `X_train` is its float32 training matrix.

```python
from pathlib import Path
from skl2onnx import to_onnx

export = to_onnx(forest, X_train[:1])
Path("forest.onnx").write_bytes(export.SerializeToString())
```

## Related recipes

[Run an XGBoost ONNX classifier in C#](https://recursiveai.org/onemodel/cookbook/run-xgboost-onnx-classifier/) · [Run a LightGBM ONNX regressor in C#](https://recursiveai.org/onemodel/cookbook/run-lightgbm-onnx-regressor/)

---

## The short answer

Use `Model.Load` to open the `.onnx` file exported by `skl2onnx`. Call `RunStrings<float>` for the string labels and `RunStringMaps<float>` for the ZipMap probabilities. Pass each output’s graph name, not the class name. The class name is a key in the returned dictionary, so `map[label]` gives you the probability for the class the model predicted.

## How do I convert a scikit-learn random forest to ONNX?

Export the fitted `RandomForestClassifier` with `skl2onnx.to_onnx`, supplying a sample input row with the feature count and type you plan to use at inference. The [tree-model guide](https://recursiveai.org/onemodel/docs/guide-tree-models/) shows the default export path. The example file uses float32 with six features and retains ZipMap, the default. Python is needed for the export, not for the C# program.

If the forest was trained on already transformed data, pass features in that transformed form. An exported pipeline is a different graph: from OneModel 1.5.0 a pipeline with a scaler, one-hot encoder, `LabelEncoder` or text step in front of the forest runs as it is, with one named input per column; the [scikit-learn pipelines guide](https://recursiveai.org/onemodel/docs/guide-sklearn-pipelines/) shows how to pass them. The [operator reference](https://recursiveai.org/onemodel/docs/ops-ml/) lists what the runtime accepts.

## How do I get class probabilities from a random forest ONNX model?

With ZipMap, `maps[0]` is the first sample’s probability dictionary, not the probability of class zero. The full program reads it alongside `labels[0]` and prints each key and value. Its flower names are just labels assigned to synthetic rows, not predictions about real flowers. Use the actual strings returned from the model, including their original case, rather than translating a guessed column number to a class.

The [skl2onnx ZipMap documentation](https://onnx.ai/sklearn-onnx/auto_examples/plot_convert_zipmap.html) also describes exporting probabilities as a plain tensor. If you disabled ZipMap, use the numeric `Run<float, float>` overload, and preserve the exported class order when interpreting columns. If ZipMap is present but the keys are integer classes rather than strings, use `RunInt64Maps<float>` instead. `SequenceOfMaps` tells you that the output is a map sequence; you still need to know whether the exporter used string or integer keys.
