Convert a pipeline with a LightGBM regressor#

The discrepancies observed when using float and TreeEnsemble operator (see Issues when switching to float) explains why the converter for LGBMRegressor may introduce significant discrepancies even when it is used with float tensors.

Library lightgbm is implemented with double. A random forest regressor with multiple trees computes its prediction by adding the prediction of every tree. After being converting into ONNX, this summation becomes \left[\sum\right]_{i=1}^F float(T_i(x)), where F is the number of trees in the forest, T_i(x) the output of tree i and \left[\sum\right] a float addition. The discrepancy can be expressed as D(x) = |\left[\sum\right]_{i=1}^F float(T_i(x)) -
\sum_{i=1}^F T_i(x)|. This grows with the number of trees in the forest.

To reduce the impact, an option was added to split the node TreeEnsembleRegressor into multiple ones and to do a summation with double this time. If we assume the node if split into a nodes, the discrepancies then become D'(x) = |\sum_{k=1}^a \left[\sum\right]_{i=1}^{F/a}
float(T_{ak + i}(x)) - \sum_{i=1}^F T_i(x)|.

Train a LGBMRegressor#

from distutils.version import StrictVersion
import warnings
import timeit
import numpy
from pandas import DataFrame
# import matplotlib.pyplot as plt
from tqdm import tqdm
from lightgbm import LGBMRegressor
from onnxruntime import InferenceSession
from skl2onnx import to_onnx, update_registered_converter
from skl2onnx.common.shape_calculator import calculate_linear_regressor_output_shapes  # noqa
from onnxmltools import __version__ as oml_version
from onnxmltools.convert.lightgbm.operator_converters.LightGbm import convert_lightgbm  # noqa


N = 1000
X = numpy.random.randn(N, 20)
y = (numpy.random.randn(N) +
     numpy.random.randn(N) * 100 * numpy.random.randint(0, 1, 1000))

reg = LGBMRegressor(n_estimators=1000)
reg.fit(X, y)
LGBMRegressor(n_estimators=1000)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.


Register the converter for LGBMClassifier#

The converter is implemented in onnxmltools: onnxmltools…LightGbm.py. and the shape calculator: onnxmltools…Regressor.py.

def skl2onnx_convert_lightgbm(scope, operator, container):
    options = scope.get_options(operator.raw_operator)
    if 'split' in options:
        if StrictVersion(oml_version) < StrictVersion('1.9.2'):
            warnings.warn(
                "Option split was released in version 1.9.2 but %s is "
                "installed. It will be ignored." % oml_version)
        operator.split = options['split']
    else:
        operator.split = None
    convert_lightgbm(scope, operator, container)


update_registered_converter(
    LGBMRegressor, 'LightGbmLGBMRegressor',
    calculate_linear_regressor_output_shapes,
    skl2onnx_convert_lightgbm,
    options={'split': None})

Convert#

We convert the same model following the two scenarios, one single TreeEnsembleRegressor node, or more. split parameter is the number of trees per node TreeEnsembleRegressor.

model_onnx = to_onnx(reg, X[:1].astype(numpy.float32),
                     target_opset={'': 14, 'ai.onnx.ml': 2})
model_onnx_split = to_onnx(reg, X[:1].astype(numpy.float32),
                           target_opset={'': 14, 'ai.onnx.ml': 2},
                           options={'split': 100})

Out:

somewhere/workspace/onnxcustom/onnxcustom_UT_39_std/_doc/examples/plot_gexternal_lightgbm_reg.py:78: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead.
  if StrictVersion(oml_version) < StrictVersion('1.9.2'):

Discrepancies#

sess = InferenceSession(model_onnx.SerializeToString(),
                        providers=['CPUExecutionProvider'])
sess_split = InferenceSession(model_onnx_split.SerializeToString(),
                              providers=['CPUExecutionProvider'])

X32 = X.astype(numpy.float32)
expected = reg.predict(X32)
got = sess.run(None, {'X': X32})[0].ravel()
got_split = sess_split.run(None, {'X': X32})[0].ravel()

disp = numpy.abs(got - expected).sum()
disp_split = numpy.abs(got_split - expected).sum()

print("sum of discrepancies 1 node", disp)
print("sum of discrepancies split node",
      disp_split, "ratio:", disp / disp_split)

Out:

sum of discrepancies 1 node 0.00022609177254211696
sum of discrepancies split node 4.432580278624374e-05 ratio: 5.1006808299089235

The sum of the discrepancies were reduced 4, 5 times. The maximum is much better too.

disc = numpy.abs(got - expected).max()
disc_split = numpy.abs(got_split - expected).max()

print("max discrepancies 1 node", disc)
print("max discrepancies split node", disc_split, "ratio:", disc / disc_split)

Out:

max discrepancies 1 node 2.9158061529699353e-06
max discrepancies split node 3.1684623991168337e-07 ratio: 9.20259035986249

Processing time#

The processing time is slower but not much.

print("processing time no split",
      timeit.timeit(
          lambda: sess.run(None, {'X': X32})[0], number=150))
print("processing time split",
      timeit.timeit(
          lambda: sess_split.run(None, {'X': X32})[0], number=150))

Out:

processing time no split 5.291990412981249
processing time split 5.242012705013622

Split influence#

Let’s see how the sum of the discrepancies moves against the parameter split.

res = []
for i in tqdm(list(range(20, 170, 20)) + [200, 300, 400, 500]):
    model_onnx_split = to_onnx(reg, X[:1].astype(numpy.float32),
                               target_opset={'': 14, 'ai.onnx.ml': 2},
                               options={'split': i})
    sess_split = InferenceSession(model_onnx_split.SerializeToString(),
                                  providers=['CPUExecutionProvider'])
    got_split = sess_split.run(None, {'X': X32})[0].ravel()
    disc_split = numpy.abs(got_split - expected).max()
    res.append(dict(split=i, disc=disc_split))

df = DataFrame(res).set_index('split')
df["baseline"] = disc
print(df)

Out:

  0%|          | 0/12 [00:00<?, ?it/s]somewhere/workspace/onnxcustom/onnxcustom_UT_39_std/_doc/examples/plot_gexternal_lightgbm_reg.py:78: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead.
  if StrictVersion(oml_version) < StrictVersion('1.9.2'):

  8%|8         | 1/12 [00:18<03:27, 18.90s/it]
 17%|#6        | 2/12 [00:37<03:06, 18.63s/it]
 25%|##5       | 3/12 [00:54<02:42, 18.09s/it]
 33%|###3      | 4/12 [01:12<02:22, 17.81s/it]
 42%|####1     | 5/12 [01:29<02:03, 17.59s/it]
 50%|#####     | 6/12 [01:47<01:46, 17.71s/it]
 58%|#####8    | 7/12 [02:04<01:27, 17.49s/it]
 67%|######6   | 8/12 [02:21<01:09, 17.37s/it]
 75%|#######5  | 9/12 [02:39<00:52, 17.50s/it]
 83%|########3 | 10/12 [02:56<00:34, 17.34s/it]
 92%|#########1| 11/12 [03:13<00:17, 17.25s/it]
100%|##########| 12/12 [03:30<00:00, 17.14s/it]
100%|##########| 12/12 [03:30<00:00, 17.51s/it]
               disc  baseline
split
20     2.074905e-07  0.000003
40     2.240620e-07  0.000003
60     2.670632e-07  0.000003
80     3.222273e-07  0.000003
100    3.168462e-07  0.000003
120    4.587358e-07  0.000003
140    5.352417e-07  0.000003
160    4.587358e-07  0.000003
200    5.096276e-07  0.000003
300    8.698656e-07  0.000003
400    8.033990e-07  0.000003
500    1.001935e-06  0.000003

Graph.

ax = df.plot(title="Sum of discrepancies against split\n"
                   "split = number of tree per node")

# plt.show()
Sum of discrepancies against split split = number of tree per node

Total running time of the script: ( 7 minutes 42.183 seconds)

Gallery generated by Sphinx-Gallery