---
title: "Run StandardScaler and Ridge regression with ONNX in C#"
url: https://recursiveai.org/onemodel/cookbook/run-onnx-standardscaler-ridge-regression/
description: "Run StandardScaler and Ridge regression together in one ONNX graph with C#. Pass raw float features and read the predictions without scaling them twice."
version: "1.5.0"
---

# Run StandardScaler and Ridge regression 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-onnx-standardscaler-ridge-regression/run-onnx-standardscaler-ridge-regression.zip)

`ridge.onnx` (in the zip) scales raw features before predicting. Pass unscaled values. [See how it was made](#how-do-i-convert-a-fitted-scikit-learn-pipeline-to-onnx).

```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 static System.FormattableString;
using var model = Model.Load("ridge.onnx");
float[] predictions = model.Run([3f, 1200f]);
Console.WriteLine(
    Invariant($"{predictions[0]:F2}"));
```

Unzip [the example](https://recursiveai.org/onemodel/cookbook/run-onnx-standardscaler-ridge-regression/run-onnx-standardscaler-ridge-regression.zip) and run `dotnet run`, or create a new `dotnet new console` project, add the package, paste the snippet into `Program.cs`, copy `ridge.onnx` from the zip next to `Program.cs`, and run `dotnet run`.

Prints:

```text
44.30
```

## The full program

```csharp
using RecursiveAI.OneModel;

using var model = Model.Load("ridge.onnx");
using var inputs = new ModelInputs();
inputs.Add<float>("X", [3f, 1200f]);
using var result = model.Run(inputs);
float prediction = result.Floats("variable")[0];
Console.WriteLine(
    FormattableString.Invariant(
        $"{prediction:F2}"));
```

`dotnet run` prints:

```text
44.30
```

The full program sends one row with two raw features in training order: `3` (room count) and `1200` (area in square feet). It uses the graph’s input name `X` and reads the float prediction from `variable`. The training targets are synthetic scores, not prices.

If the input length doesn’t fit the declared width of two features, OneModel throws `SessionException` instead of returning a prediction.

## Variations

Score two rows in one call. In the snippet at the top, replace everything after `Model.Load` with:

```csharp
float[] predictions = model.Run(
    [3f, 1200f, 4f, 1500f],
    shape: [2, 2]);
foreach (float value in predictions)
    Console.WriteLine(Invariant($"{value:F2}"));
```

```text
44.30
55.92
```

To inspect your own export, replace `"ridge.onnx"` with your model’s path. [OneModel’s pipeline guide](https://recursiveai.org/onemodel/docs/guide-sklearn-pipelines/#export) explains how to inspect input and output names and kinds. Use the listed names in your `Add` and output calls.

```csharp
using RecursiveAI.OneModel;

using var model = Model.Load("ridge.onnx");
foreach (var input in model.Session.Inputs)
    Console.WriteLine(
        $"In: {input.Name} ({input.Kind})");
foreach (var output in model.Session.Outputs)
    Console.WriteLine(
        $"Out: {output.Name} ({output.Kind})");
```

## Related recipes

- [Read scikit-learn SVC class probabilities from ONNX](https://recursiveai.org/onemodel/cookbook/read-svc-class-probabilities-from-onnx/)
- [Use named inputs and outputs in an ONNX model](https://recursiveai.org/onemodel/cookbook/named-inputs-and-outputs/)

## The short answer

Export the fitted `StandardScaler` and `Ridge` as one scikit-learn pipeline. At inference, load the result once with `Model.Load`, pass one or more rows of raw `float` values to `Run`, and read one prediction per row. The ONNX graph applies the fitted scaler on every run; there’s no need to copy the training means or standard deviations into C#.

## Why standardize data before Ridge regression?

[Ridge](https://scikit-learn.org/1.8/modules/generated/sklearn.linear_model.Ridge.html) penalizes the sum of squared coefficient values. Feature units affect the coefficients: a column measured in square feet can span hundreds, while a room count varies by only a few. [StandardScaler](https://scikit-learn.org/1.8/modules/generated/sklearn.preprocessing.StandardScaler.html) centers and scales each feature using statistics from the training data so those raw units don’t determine the relative weight of the penalty.

At prediction time you want those same statistics, not new ones computed on the rows you’re trying to score. The graph contains what the scaler learned at fit time. If you standardize the rows before sending them, the graph scales them again. Column order also matters: swapping area and room count still supplies two numbers, so shape checking won’t catch that mistake.

## How do I convert a fitted scikit-learn pipeline to ONNX?

Pass the whole fitted pipeline to [`skl2onnx.to_onnx`](https://onnx.ai/sklearn-onnx/auto_tutorial/plot_abegin_convert_pipeline.html), not only the `Ridge` step. The sample row `X[:1]` tells the exporter the feature count and type. The resulting input `X` is a float32 matrix of shape `[N, 2]`, where `N` is the number of rows. For this export, ONNX’s `Scaler` standardizes the two feature columns. `LinearRegressor` then uses the scaled values to make one numeric prediction per row, a `[N, 1]` float tensor named `variable`.

The script fits both steps on synthetic data and exports them together. Save it as `export.py` or use the copy in the zip. To rebuild `ridge.onnx`, run these commands in a Python environment from the folder containing the script. The C# program uses the supplied model and doesn’t need Python.

```shell
python -m pip install scikit-learn==1.8.0
python -m pip install skl2onnx==1.20.0
python -m pip install onnx==1.23.2
python export.py
```

```python
import numpy as np
import onnx
from sklearn.linear_model import Ridge
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import (
    StandardScaler,
)
from skl2onnx import to_onnx

X = np.array([
    [1, 800], [2, 1300], [3, 1000],
    [4, 1600], [5, 1400],
], dtype=np.float32)
y = np.array(
    [24, 43, 38, 60, 59], dtype=np.float32,
)
pipeline = make_pipeline(
    StandardScaler(), Ridge(alpha=1.0),
)
pipeline.fit(X, y)
model = to_onnx(
    pipeline, X[:1], target_opset=20,
)
onnx.save(model, "ridge.onnx")
```
