# TreeEnsembleRegressor and parallelisation#

The operator TreeEnsembleClassifier describe any tree model (decision tree, random forest, gradient boosting). The runtime is usually implements in C/C++ and uses parallelisation. The notebook studies the impact of the parallelisation.

## Graph#

The following dummy graph shows the time ratio between two runtimes depending on the number of observations in a batch (N) and the number of trees in the forest.

```from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from mlprodict.onnxrt import OnnxInference
from onnxruntime import InferenceSession
from skl2onnx import to_onnx
from mlprodict.onnxrt.validate.validate_benchmark import benchmark_fct
import sklearn
import numpy
from tqdm import tqdm
from sklearn.datasets import make_classification
import matplotlib.pyplot as plt
from mlprodict.plotting.plotting import plot_benchmark_metrics

def plot_metric(metric, ax=None, xlabel="N", ylabel="trees", middle=1.,
transpose=False, shrink=1.0, title=None, figsize=None):
if figsize is not None and ax is None:
_, ax = plt.subplots(1, 1, figsize=figsize)

ax, cbar = plot_benchmark_metrics(
metric, ax=ax, xlabel=xlabel, ylabel=ylabel, middle=middle,
transpose=transpose, cbar_kw={'shrink': shrink})
if title is not None:
ax.set_title(title)
return ax

data = {(1, 1): 0.1, (10, 1): 1, (1, 10): 2,
(10, 10): 100, (100, 1): 100, (100, 10): 1000}

fig, ax = plt.subplots(1, 2, figsize=(10, 4))
plot_metric(data, ax[0], shrink=0.6)
```
```<AxesSubplot: xlabel='N', ylabel='trees'>
```
```plot_metric(data, ax[1], transpose=True)
```
```<AxesSubplot: xlabel='trees', ylabel='N'>
```

## scikit-learn: T trees vs 1 tree#

Let’s do first compare a GradientBoostingClassifier from scikit-learn with 1 tree against multiple trees.

```# In[4]:

ntest = 10000
X, y = make_classification(
n_samples=10000 + ntest, n_features=10, n_informative=5,
n_classes=2, random_state=11)
X_train, X_test, y_train, y_test = X[:-
ntest], X[-ntest:], y[:-ntest], y[-ntest:]
```
```ModelToTest = GradientBoostingClassifier

N = [1, 10, 100, 1000, 10000]
T = [1, 2, 10, 20, 50]

models = {}
for nt in tqdm(T):
rf = ModelToTest(n_estimators=nt, max_depth=7).fit(X_train, y_train)
models[nt] = rf
```
```  0%|          | 0/5 [00:00<?, ?it/s]
20%|##        | 1/5 [00:00<00:00,  5.10it/s]
40%|####      | 2/5 [00:00<00:00,  3.78it/s]
60%|######    | 3/5 [00:02<00:01,  1.18it/s]
80%|########  | 4/5 [00:05<00:01,  1.73s/it]
100%|##########| 5/5 [00:12<00:00,  3.88s/it]
100%|##########| 5/5 [00:12<00:00,  2.56s/it]
```

Benchmark.

```def benchmark(X, fct1, fct2, N, repeat=10, number=20):

def ti(r, n):
if n <= 1:
return 40 * r
if n <= 10:
return 10 * r
if n <= 100:
return 4 * r
if n <= 1000:
return r
return r // 2

with sklearn.config_context(assume_finite=True):
# to warm up the engine
time_kwargs = {n: dict(repeat=10, number=10) for n in N}
benchmark_fct(fct1, X, time_kwargs=time_kwargs, skip_long_test=False)
benchmark_fct(fct2, X, time_kwargs=time_kwargs, skip_long_test=False)
# real measure
time_kwargs = {n: dict(repeat=ti(repeat, n), number=number) for n in N}
res1 = benchmark_fct(
fct1, X, time_kwargs=time_kwargs, skip_long_test=False)
res2 = benchmark_fct(
fct2, X, time_kwargs=time_kwargs, skip_long_test=False)
res = {}
for r in sorted(res1):
r1 = res1[r]
r2 = res2[r]
ratio = r2['ttime'] / r1['ttime']
res[r] = ratio
return res

def tree_benchmark(X, fct1, fct2, T, N, repeat=20, number=10):
bench = {}
for t in tqdm(T):
if callable(X):
x = X(t)
else:
x = X
r = benchmark(x, fct1(t), fct2(t), N, repeat=repeat, number=number)
for n, v in r.items():
bench[n, t] = v
return bench

bench = tree_benchmark(X_test.astype(numpy.float32),
lambda t: models[1].predict,
lambda t: models[t].predict, T, N)

list(bench.items())[:3]
```
```  0%|          | 0/5 [00:00<?, ?it/s]
20%|##        | 1/5 [00:15<01:01, 15.32s/it]
40%|####      | 2/5 [00:30<00:46, 15.39s/it]
60%|######    | 3/5 [00:47<00:31, 15.98s/it]
80%|########  | 4/5 [01:05<00:16, 16.84s/it]
100%|##########| 5/5 [01:28<00:00, 18.93s/it]
100%|##########| 5/5 [01:28<00:00, 17.65s/it]

[((1, 1), 1.0018442661175557), ((10, 1), 1.0014464423320466), ((100, 1), 1.0005459495198301)]
```

Graph.

```plot_metric(bench, title="scikit-learn 1 tree vs scikit-learn T trees\n"
"< 1 means onnxruntime is faster")
```
```<AxesSubplot: title={'center': 'scikit-learn 1 tree vs scikit-learn T trees\n< 1 means onnxruntime is faster'}, xlabel='N', ylabel='trees'>
```

As expected, all ratio on first line are close to 1 since both models are the same. fourth line, second column (T=20, N=10) means an ensemble with 20 trees is slower to compute the predictions of 10 observations in a batch compare to an ensemble with 1 tree.

## scikit-learn against onnxuntime#

```X32 = X_test.astype(numpy.float32)
models_onnx = {t: to_onnx(m, X32[:1]) for t, m in models.items()}

sess_models = {t: InferenceSession(mo.SerializeToString())
for t, mo in models_onnx.items()}
```

Benchmark.

```bench_ort = tree_benchmark(
X_test.astype(numpy.float32),
lambda t: models[t].predict_proba,
lambda t: (lambda x, t_=t, se=sess_models: se[t_].run(None, {'X': x})),
T, N)
bench_ort
```
```  0%|          | 0/5 [00:00<?, ?it/s]
20%|##        | 1/5 [00:11<00:44, 11.09s/it]
40%|####      | 2/5 [00:22<00:33, 11.16s/it]
60%|######    | 3/5 [00:35<00:24, 12.10s/it]
80%|########  | 4/5 [00:50<00:13, 13.28s/it]
100%|##########| 5/5 [01:11<00:00, 16.07s/it]
100%|##########| 5/5 [01:11<00:00, 14.32s/it]

{(1, 1): 0.1030447889448751, (10, 1): 0.11983626828954276, (100, 1): 0.2849465614947357, (1000, 1): 1.5265978719110718, (10000, 1): 4.051449300361436, (1, 2): 0.10331691171319178, (10, 2): 0.12222691829941669, (100, 2): 0.28658602160529106, (1000, 2): 1.4871438263264574, (10000, 2): 3.4329425224870787, (1, 10): 0.1043200640415068, (10, 10): 0.12856865158627054, (100, 10): 0.30388509914495354, (1000, 10): 1.2378997373844385, (10000, 10): 1.9581083868924827, (1, 20): 0.10504009143348779, (10, 20): 0.14321330963099094, (100, 20): 0.2832746152845303, (1000, 20): 0.9325047505624398, (10000, 20): 1.2938357587247205, (1, 50): 0.10545903295791247, (10, 50): 0.19251866811296633, (100, 50): 0.24136619679084317, (1000, 50): 0.6504178604394425, (10000, 50): 0.7626933516300353}
```

Graphs

```plot_metric(bench_ort, title="scikit-learn vs onnxruntime\n < 1 "
"means onnxruntime is faster")
```
```<AxesSubplot: title={'center': 'scikit-learn vs onnxruntime\n < 1 means onnxruntime is faster'}, xlabel='N', ylabel='trees'>
```

We see onnxruntime is fast for small batches, still faster but not that much for big batches.

## ZipMap operator#

ZipMap just creates a new container for the same results. The copy may impact the ratio. Let’s remove it from the equation.

```X32 = X_test.astype(numpy.float32)
models_onnx = {t: to_onnx(m, X32[:1],
options={ModelToTest: {'zipmap': False}})
for t, m in models.items()}

sess_models = {t: InferenceSession(mo.SerializeToString())
for t, mo in models_onnx.items()}
```

Benchmarks.

```bench_ort = tree_benchmark(
X_test.astype(numpy.float32),
lambda t: models[t].predict_proba,
lambda t: (lambda x, t_=t, se=sess_models: se[t_].run(None, {'X': x})),
T, N)

bench_ort
```
```  0%|          | 0/5 [00:00<?, ?it/s]
20%|##        | 1/5 [00:08<00:32,  8.06s/it]
40%|####      | 2/5 [00:16<00:24,  8.19s/it]
60%|######    | 3/5 [00:26<00:18,  9.13s/it]
80%|########  | 4/5 [00:38<00:10, 10.35s/it]
100%|##########| 5/5 [00:56<00:00, 13.07s/it]
100%|##########| 5/5 [00:56<00:00, 11.34s/it]

{(1, 1): 0.08846393421137234, (10, 1): 0.09179761056146678, (100, 1): 0.10485015355360862, (1000, 1): 0.13344552837421222, (10000, 1): 0.20432313826033655, (1, 2): 0.08858137346989862, (10, 2): 0.09261874145041982, (100, 2): 0.10655318713315103, (1000, 2): 0.14310526426028483, (10000, 2): 0.21775632378746504, (1, 10): 0.09015013018210309, (10, 10): 0.10337380994833921, (100, 10): 0.15154810234929414, (1000, 10): 0.32892246569379485, (10000, 10): 0.4967286136991438, (1, 20): 0.09062816853662259, (10, 20): 0.11924697748480335, (100, 20): 0.14712398454987027, (1000, 20): 0.2891537761197627, (10000, 20): 0.41085470771523896, (1, 50): 0.0908418102679915, (10, 50): 0.1526081589047313, (100, 50): 0.14233808006185614, (1000, 50): 0.28002987670613144, (10000, 50): 0.3453506904882594}
```

Graphs.

```plot_metric(bench_ort, title="scikit-learn vs onnxruntime (no zipmap)\n < 1 "
"means onnxruntime is faster")

# ZipMap removal significantly improves.
#
# Implementation details for mlprodict runtime
# ++++++++++++++++++++++++++++++++++++++++++++
#
# The runtime implemented in :epkg:`mlprodict` mostly relies on
# two files:
# * `op_tree_ensemble_common_p_agg_.hpp <https://github.com/sdpython/
#   mlprodict/blob/master/mlprodict/onnxrt/ops_cpu/
#   op_tree_ensemble_common_p_agg_.hpp>`_
# * `op_tree_ensemble_common_p_.hpp <https://github.com/sdpython/
#   mlprodict/blob/master/mlprodict/onnxrt/ops_cpu/
#   op_tree_ensemble_common_p_.hpp>`_
#
# The runtime builds a tree structure, computes the output of every
# tree and then agregates them. The implementation distringuishes
# when the batch size contains only 1 observations or many.
# It parallelizes on the following conditions:
# * if the batch size \$N \geqslant N_0\$, it then parallelizes per
#   observation, asuming every one is independant,
# * if the batch size \$N = 1\$ and the number of trees
#   \$T \geqslant T_0\$, it then parallelizes per tree.
#
# scikit-learn against mlprodict, no parallelisation
# ++++++++++++++++++++++++++++++++++++++++++++++++++

oinf_models = {t: OnnxInference(mo, runtime="python_compiled")
for t, mo in models_onnx.items()}
```

Let’s modify the thresholds which trigger the parallelization.

```for _, oinf in oinf_models.items():
oinf.sequence_[0].ops_.rt_.omp_tree_ = 10000000
oinf.sequence_[0].ops_.rt_.omp_N_ = 10000000
```

Benchmarks.

```bench_mlp = tree_benchmark(
X_test.astype(numpy.float32),
lambda t: models[t].predict,
lambda t: (lambda x, t_=t, oi=oinf_models: oi[t_].run({'X': x})),
T, N)
bench_mlp
```
```  0%|          | 0/5 [00:00<?, ?it/s]
20%|##        | 1/5 [00:08<00:33,  8.47s/it]
40%|####      | 2/5 [00:17<00:26,  8.67s/it]
60%|######    | 3/5 [00:29<00:20, 10.32s/it]
80%|########  | 4/5 [00:47<00:13, 13.29s/it]
100%|##########| 5/5 [01:20<00:00, 20.31s/it]
100%|##########| 5/5 [01:20<00:00, 16.03s/it]

{(1, 1): 0.05198315355310949, (10, 1): 0.0547834231766541, (100, 1): 0.07902288195061921, (1000, 1): 0.23960149964306027, (10000, 1): 0.5609082018174909, (1, 2): 0.05247854825111707, (10, 2): 0.05657460099693185, (100, 2): 0.09225147719480122, (1000, 2): 0.3167493840790582, (10000, 2): 0.7050968013903678, (1, 10): 0.05405776479524537, (10, 10): 0.07128247600777964, (100, 10): 0.20561686574830168, (1000, 10): 0.829681359907235, (10000, 10): 1.4478065064123162, (1, 20): 0.0559029742001885, (10, 20): 0.09234777816470552, (100, 20): 0.3696201056223252, (1000, 20): 1.36916232578198, (10000, 20): 2.1016659880343798, (1, 50): 0.05966519095809953, (10, 50): 0.12876711245704198, (100, 50): 0.6178148933679765, (1000, 50): 1.8889630861333193, (10000, 50): 2.466215866479506}
```

Graphs.

```plot_metric(bench_mlp, title="scikit-learn vs mlprodict\n < 1 "
"means mlprodict is faster")
```
```<AxesSubplot: title={'center': 'scikit-learn vs mlprodict\n < 1 means mlprodict is faster'}, xlabel='N', ylabel='trees'>
```

Let’s compare onnxruntime against mlprodict.

```bench_mlp_ort = tree_benchmark(
X_test.astype(numpy.float32),
lambda t: (lambda x, t_=t, se=sess_models: se[t_].run(None, {'X': x})),
lambda t: (lambda x, t_=t, oi=oinf_models: oi[t_].run({'X': x})),
T, N)
bench_mlp_ort
```
```  0%|          | 0/5 [00:00<?, ?it/s]
20%|##        | 1/5 [00:01<00:06,  1.60s/it]
40%|####      | 2/5 [00:03<00:05,  1.75s/it]
60%|######    | 3/5 [00:08<00:06,  3.19s/it]
80%|########  | 4/5 [00:17<00:05,  5.62s/it]
100%|##########| 5/5 [00:38<00:00, 11.16s/it]
100%|##########| 5/5 [00:38<00:00,  7.73s/it]

{(1, 1): 0.6143651099446117, (10, 1): 0.6218061405487766, (100, 1): 0.7799555949440162, (1000, 1): 1.8837500389146695, (10000, 1): 3.0319154031485573, (1, 2): 0.6116186750319663, (10, 2): 0.6281370043607717, (100, 2): 0.8932951573943733, (1000, 2): 2.3239747393612733, (10000, 2): 3.5040828715441354, (1, 10): 0.624637891342021, (10, 10): 0.7126322424587537, (100, 10): 1.4152603462629014, (1000, 10): 2.6163590290230823, (10000, 10): 3.030063496110499, (1, 20): 0.6441167122537531, (10, 20): 0.8193957005168055, (100, 20): 2.6522740442266874, (1000, 20): 4.859560440246389, (10000, 20): 5.254984678139046, (1, 50): 0.6735849351395267, (10, 50): 0.8861302962798404, (100, 50): 4.435570540632529, (1000, 50): 6.857201233125692, (10000, 50): 7.20809932383733}
```

Graphs.

```plot_metric(bench_mlp_ort, title="onnxruntime vs mlprodict\n < 1 means "
"mlprodict is faster\nno parallelisation")
```
```<AxesSubplot: title={'center': 'onnxruntime vs mlprodict\n < 1 means mlprodict is faster\nno parallelisation'}, xlabel='N', ylabel='trees'>
```

This implementation is faster except for high number of trees or high number of observations. Let’s add parallelisation for trees and observations.

```for _, oinf in oinf_models.items():
oinf.sequence_[0].ops_.rt_.omp_tree_ = 2
oinf.sequence_[0].ops_.rt_.omp_N_ = 2

bench_mlp_para = tree_benchmark(
X_test.astype(numpy.float32),
lambda t: models[t].predict,
lambda t: (lambda x, t_=t, oi=oinf_models: oi[t_].run({'X': x})),
T, N)

bench_mlp_para
```
```  0%|          | 0/5 [00:00<?, ?it/s]
20%|##        | 1/5 [00:08<00:34,  8.51s/it]
40%|####      | 2/5 [00:17<00:25,  8.65s/it]
60%|######    | 3/5 [00:27<00:18,  9.27s/it]
80%|########  | 4/5 [00:39<00:10, 10.25s/it]
100%|##########| 5/5 [00:56<00:00, 12.70s/it]
100%|##########| 5/5 [00:56<00:00, 11.21s/it]

{(1, 1): 0.05262877171701955, (10, 1): 0.06261506288853547, (100, 1): 0.0896774319393679, (1000, 1): 0.27925126038741754, (10000, 1): 0.633924261416109, (1, 2): 0.052826150897270045, (10, 2): 0.06381918334519496, (100, 2): 0.09655793076321, (1000, 2): 0.31896230421797894, (10000, 2): 0.6824609059555903, (1, 10): 0.07232693779692399, (10, 10): 0.07375836274671133, (100, 10): 0.09066409966477441, (1000, 10): 0.16681574090279944, (10000, 10): 0.26102944032033204, (1, 20): 0.06738080138399669, (10, 20): 0.07278313374201534, (100, 20): 0.08923711678844076, (1000, 20): 0.16482939536364302, (10000, 20): 0.22964263539862673, (1, 50): 0.06616780944319253, (10, 50): 0.06939366053532935, (100, 50): 0.09034679664347073, (1000, 50): 0.17244280967800873, (10000, 50): 0.2204456635763934}
```

Graphs.

```plot_metric(bench_mlp_para, title="scikit-learn vs mlprodict\n < 1 means "
"mlprodict is faster\nparallelisation")
```
```<AxesSubplot: title={'center': 'scikit-learn vs mlprodict\n < 1 means mlprodict is faster\nparallelisation'}, xlabel='N', ylabel='trees'>
```

Parallelisation does improve the computation time when N is big. Let’s compare with and without parallelisation.

```bench_para = {}
for k, v in bench_mlp.items():
bench_para[k] = bench_mlp_para[k] / v

plot_metric(bench_para, title="mlprodict vs mlprodict parallelized\n < 1 "
"means parallelisation is faster")
```
```<AxesSubplot: title={'center': 'mlprodict vs mlprodict parallelized\n < 1 means parallelisation is faster'}, xlabel='N', ylabel='trees'>
```

Parallelisation per trees does not seem to be efficient. Let’s confirm with a proper benchmark as the previous merges results from two benchmarks.

```for _, oinf in oinf_models.items():
oinf.sequence_[0].ops_.rt_.omp_tree_ = 1000000
oinf.sequence_[0].ops_.rt_.omp_N_ = 1000000

oinf_models_para = {t: OnnxInference(mo, runtime="python_compiled")
for t, mo in models_onnx.items()}

for _, oinf in oinf_models_para.items():
oinf.sequence_[0].ops_.rt_.omp_tree_ = 2
oinf.sequence_[0].ops_.rt_.omp_N_ = 2

bench_mlp_para = tree_benchmark(
X_test.astype(numpy.float32),
lambda t: (lambda x, t_=t, oi=oinf_models: oi[t_].run({'X': x})),
lambda t: (lambda x, t_=t, oi=oinf_models_para: oi[t_].run({'X': x})),
T, N, repeat=20, number=20)

bench_mlp_para
```
```  0%|          | 0/5 [00:00<?, ?it/s]
20%|##        | 1/5 [00:03<00:12,  3.16s/it]
40%|####      | 2/5 [00:06<00:10,  3.53s/it]
60%|######    | 3/5 [00:13<00:10,  5.08s/it]
80%|########  | 4/5 [00:27<00:08,  8.40s/it]
100%|##########| 5/5 [00:58<00:00, 16.49s/it]
100%|##########| 5/5 [00:58<00:00, 11.64s/it]

{(1, 1): 0.9984626754568104, (10, 1): 1.1644397253560852, (100, 1): 1.242588026763474, (1000, 1): 1.376483396036672, (10000, 1): 1.3773144633033299, (1, 2): 0.9945126837177396, (10, 2): 1.1604804766709793, (100, 2): 1.1983049811852293, (1000, 2): 1.2603105552114977, (10000, 2): 1.2470650309748652, (1, 10): 1.2569860457697557, (10, 10): 1.044658597472122, (100, 10): 0.4341538967054369, (1000, 10): 0.1994146504234537, (10000, 10): 0.1771659138195141, (1, 20): 1.2043960285598638, (10, 20): 0.7817926673417291, (100, 20): 0.23820929199366908, (1000, 20): 0.11600254474136365, (10000, 20): 0.10503533832549039, (1, 50): 1.154509069803967, (10, 50): 0.5616249517985925, (100, 50): 0.14477257635913174, (1000, 50): 0.09290637889429042, (10000, 50): 0.08724722537235917}
```

Graph.

```plot_metric(bench_mlp_para, title="mlprodict vs mlprodict parallelized\n < 1 "
"means parallelisation is faster\nsame baseline")
```
```<AxesSubplot: title={'center': 'mlprodict vs mlprodict parallelized\n < 1 means parallelisation is faster\nsame baseline'}, xlabel='N', ylabel='trees'>
```

It should be run on different machines. On the current one, parallelisation per trees (when N=1) does not seem to help. Parallelisation for a small number of observations does not seem to help either. So we need to find some threshold.

## Parallelisation per trees#

Let’s study the parallelisation per tree. We need to train new models.

```# In[33]:

N2 = [1, 10]
T2 = [1, 2, 10, 50, 100, 150, 200, 300, 400, 500]

models2 = {}
for nt in tqdm(T2):
rf = ModelToTest(n_estimators=nt, max_depth=7).fit(X_train, y_train)
models2[nt] = rf
```
```  0%|          | 0/10 [00:00<?, ?it/s]
10%|#         | 1/10 [00:00<00:01,  6.34it/s]
20%|##        | 2/10 [00:00<00:01,  4.02it/s]
30%|###       | 3/10 [00:02<00:05,  1.19it/s]
40%|####      | 4/10 [00:09<00:21,  3.54s/it]
50%|#####     | 5/10 [00:24<00:38,  7.77s/it]
60%|######    | 6/10 [00:47<00:51, 12.93s/it]
70%|#######   | 7/10 [01:18<00:56, 18.67s/it]
80%|########  | 8/10 [02:04<00:54, 27.26s/it]
90%|######### | 9/10 [03:04<00:37, 37.78s/it]
100%|##########| 10/10 [04:21<00:00, 49.62s/it]
100%|##########| 10/10 [04:21<00:00, 26.11s/it]
```

Conversion to ONNX.

```X32 = X_test.astype(numpy.float32)
models2_onnx = {t: to_onnx(m, X32[:1]) for t, m in models2.items()}

oinf_models2 = {t: OnnxInference(mo, runtime="python_compiled")
for t, mo in models2_onnx.items()}
for _, oinf in oinf_models2.items():
oinf.sequence_[0].ops_.rt_.omp_tree_ = 1000000
oinf.sequence_[0].ops_.rt_.omp_N_ = 1000000

oinf_models2_para = {t: OnnxInference(
mo, runtime="python_compiled") for t, mo in models2_onnx.items()}
for _, oinf in oinf_models2_para.items():
oinf.sequence_[0].ops_.rt_.omp_tree_ = 2
oinf.sequence_[0].ops_.rt_.omp_N_ = 100
```

And benchmark.

```# In[36]:

bench_mlp_tree = tree_benchmark(
X_test.astype(numpy.float32),
lambda t: (lambda x, t_=t, oi=oinf_models2: oi[t_].run({'X': x})),
lambda t: (lambda x, t_=t, oi=oinf_models2_para: oi[t_].run({'X': x})),
T2, N2, repeat=20, number=20)
bench_mlp_tree
```
```  0%|          | 0/10 [00:00<?, ?it/s]
10%|#         | 1/10 [00:01<00:17,  1.91s/it]
20%|##        | 2/10 [00:03<00:15,  1.92s/it]
30%|###       | 3/10 [00:06<00:14,  2.05s/it]
40%|####      | 4/10 [00:08<00:13,  2.26s/it]
50%|#####     | 5/10 [00:11<00:12,  2.57s/it]
60%|######    | 6/10 [00:15<00:12,  3.03s/it]
70%|#######   | 7/10 [00:20<00:11,  3.69s/it]
80%|########  | 8/10 [00:29<00:10,  5.24s/it]
90%|######### | 9/10 [00:46<00:09,  9.06s/it]
100%|##########| 10/10 [01:11<00:00, 13.83s/it]
100%|##########| 10/10 [01:11<00:00,  7.12s/it]

{(1, 1): 1.003081275360401, (10, 1): 1.000658501699929, (1, 2): 0.9968699368195661, (10, 2): 0.9988064565811583, (1, 10): 1.1829275904298304, (10, 10): 1.0349844385485898, (1, 50): 1.0821600367161248, (10, 50): 0.5819526102198955, (1, 100): 1.0157115968765902, (10, 100): 0.4162708272880375, (1, 150): 0.9637368719046104, (10, 150): 0.2660720735204099, (1, 200): 0.8963859832297318, (10, 200): 0.16987649394187276, (1, 300): 0.5482037447140938, (10, 300): 0.10298880507571737, (1, 400): 0.22731652616242887, (10, 400): 0.06203647244402213, (1, 500): 0.17316662301552901, (10, 500): 0.05731070193390606}
```

Graph.

```plot_metric(
bench_mlp_tree, transpose=True, figsize=(10, 3), shrink=0.5,
title="mlprodict vs mlprodict parallelized\n < 1 means parallelisation "
"is faster")
```
```<AxesSubplot: title={'center': 'mlprodict vs mlprodict parallelized\n < 1 means parallelisation is faster'}, xlabel='trees', ylabel='N'>
```

The parallelisation starts to be below 1 after 400 trees. For 10 observations, there is no parallelisation neither by trees nor by observations. Ratios are close to 1. The gain obviously depends on the tree depth. You can try with a different max depth and the number of trees parallelisation becomes interesting depending on the tree depth.

## Multi-Class DecisionTreeClassifier#

Same experiment when the number of tree is 1 but then we change the number of classes.

```ModelToTest = DecisionTreeClassifier

C = [2, 5, 10, 15, 20, 30, 40, 50]
N = [1, 10, 100, 1000, 10000]
trees = {}
for cl in tqdm(C):

ntest = 10000
X, y = make_classification(
n_samples=10000 + ntest, n_features=12, n_informative=8,
n_classes=cl, random_state=11)
X_train, X_test, y_train, y_test = (
X[:-ntest], X[-ntest:], y[:-ntest], y[-ntest:])

dt = ModelToTest(max_depth=7).fit(X_train, y_train)

X32 = X_test.astype(numpy.float32)
monnx = to_onnx(dt, X32[:1])
oinf = OnnxInference(monnx)
oinf.sequence_[0].ops_.rt_.omp_N_ = 1000000
trees[cl] = dict(model=dt, X_test=X_test, X32=X32, monnx=monnx, oinf=oinf)

bench_dt = tree_benchmark(lambda cl: trees[cl]['X32'],
lambda cl: trees[cl]['model'].predict_proba,
lambda cl: (
lambda x, c=cl: trees[c]['oinf'].run({'X': x})),
C, N)

bench_dt
```
```  0%|          | 0/8 [00:00<?, ?it/s]
12%|#2        | 1/8 [00:00<00:02,  3.50it/s]
25%|##5       | 2/8 [00:00<00:01,  3.37it/s]
38%|###7      | 3/8 [00:00<00:01,  3.16it/s]
50%|#####     | 4/8 [00:01<00:01,  2.97it/s]
62%|######2   | 5/8 [00:01<00:01,  2.78it/s]
75%|#######5  | 6/8 [00:02<00:00,  2.50it/s]
88%|########7 | 7/8 [00:02<00:00,  2.23it/s]
100%|##########| 8/8 [00:03<00:00,  2.01it/s]
100%|##########| 8/8 [00:03<00:00,  2.40it/s]

0%|          | 0/8 [00:00<?, ?it/s]
12%|#2        | 1/8 [00:04<00:30,  4.41s/it]
25%|##5       | 2/8 [00:09<00:27,  4.58s/it]
38%|###7      | 3/8 [00:14<00:23,  4.80s/it]
50%|#####     | 4/8 [00:19<00:20,  5.04s/it]
62%|######2   | 5/8 [00:25<00:15,  5.26s/it]
75%|#######5  | 6/8 [00:31<00:11,  5.60s/it]
88%|########7 | 7/8 [00:38<00:05,  5.99s/it]
100%|##########| 8/8 [00:45<00:00,  6.42s/it]
100%|##########| 8/8 [00:45<00:00,  5.70s/it]

{(1, 2): 0.4954938139942434, (10, 2): 0.49259317667474983, (100, 2): 0.5127550390173959, (1000, 2): 0.6470411405798803, (10000, 2): 0.8453054956016409, (1, 5): 0.49386374467448657, (10, 5): 0.4882635453096263, (100, 5): 0.5182891033954902, (1000, 5): 0.6618008997582557, (10000, 5): 0.8780461520869585, (1, 10): 0.49220959208029463, (10, 10): 0.4941936132007702, (100, 10): 0.5209875715277589, (1000, 10): 0.6549550042986821, (10000, 10): 0.8124351623134997, (1, 15): 0.49437885952887983, (10, 15): 0.48038173506801335, (100, 15): 0.513407265314255, (1000, 15): 0.6465440138972831, (10000, 15): 0.7929438332720651, (1, 20): 0.4916883499094841, (10, 20): 0.48390729734239313, (100, 20): 0.5180548987896599, (1000, 20): 0.6208537890450846, (10000, 20): 0.7560568791416905, (1, 30): 0.4940294275052107, (10, 30): 0.4962220519100089, (100, 30): 0.5087414489679823, (1000, 30): 0.5991698113772762, (10000, 30): 0.7179998337732831, (1, 40): 0.49137693877925437, (10, 40): 0.4897940199113591, (100, 40): 0.5201759323560475, (1000, 40): 0.5971089983217561, (10000, 40): 0.7169862857006544, (1, 50): 0.4912720791362528, (10, 50): 0.48907047152898386, (100, 50): 0.5163893971665846, (1000, 50): 0.5976039343328952, (10000, 50): 0.7197201153867309}
```

Graph.

```plot_metric(bench_dt, ylabel="classes", transpose=True, shrink=0.75,
title="scikit-learn vs mlprodict (DecisionTreeClassifier) \n"
"< 1 means mlprodict is faster\n no parallelisation")
```
```<AxesSubplot: title={'center': 'scikit-learn vs mlprodict (DecisionTreeClassifier) \n< 1 means mlprodict is faster\n no parallelisation'}, xlabel='classes', ylabel='N'>
```

## Multi-class LogisticRegression#

```ModelToTest = LogisticRegression

C = [2, 5, 10, 15, 20]
N = [1, 10, 100, 1000, 10000]

models = {}
for cl in tqdm(C):

ntest = 10000
X, y = make_classification(
n_samples=10000 + ntest, n_features=10, n_informative=6,
n_classes=cl, random_state=11)
X_train, X_test, y_train, y_test = (
X[:-ntest], X[-ntest:], y[:-ntest], y[-ntest:])

model = ModelToTest().fit(X_train, y_train)

X32 = X_test.astype(numpy.float32)
monnx = to_onnx(model, X32[:1])
oinf = OnnxInference(monnx)
models[cl] = dict(model=model, X_test=X_test,
X32=X32, monnx=monnx, oinf=oinf)

bench_lr = tree_benchmark(lambda cl: models[cl]['X32'],
lambda cl: models[cl]['model'].predict_proba,
lambda cl: (
lambda x, c=cl: trees[c]['oinf'].run({'X': x})),
C, N)
bench_lr
```
```  0%|          | 0/5 [00:00<?, ?it/s]
20%|##        | 1/5 [00:00<00:00,  8.36it/s]
40%|####      | 2/5 [00:00<00:00,  3.76it/s]
60%|######    | 3/5 [00:00<00:00,  3.15it/s]
80%|########  | 4/5 [00:01<00:00,  2.25it/s]
100%|##########| 5/5 [00:02<00:00,  1.79it/s]
100%|##########| 5/5 [00:02<00:00,  2.20it/s]

0%|          | 0/5 [00:00<?, ?it/s]
20%|##        | 1/5 [00:05<00:20,  5.06s/it]
40%|####      | 2/5 [00:12<00:18,  6.21s/it]
60%|######    | 3/5 [00:20<00:14,  7.14s/it]
80%|########  | 4/5 [00:29<00:08,  8.02s/it]
100%|##########| 5/5 [00:40<00:00,  8.95s/it]
100%|##########| 5/5 [00:40<00:00,  8.06s/it]

{(1, 2): 0.37445252359922154, (10, 2): 0.38669654046824664, (100, 2): 0.41154059832527184, (1000, 2): 0.607050749373826, (10000, 2): 0.993225327504672, (1, 5): 0.31340251434088956, (10, 5): 0.30482104988113023, (100, 5): 0.30292334201281607, (1000, 5): 0.30642252225362976, (10000, 5): 0.33680995475945064, (1, 10): 0.31091792713786887, (10, 10): 0.29999777009391654, (100, 10): 0.28604335043100687, (1000, 10): 0.2546367720548566, (10000, 10): 0.25083252671458955, (1, 15): 0.3105178303746872, (10, 15): 0.291526491498129, (100, 15): 0.27181691824027365, (1000, 15): 0.22565629206376295, (10000, 15): 0.22416855682626002, (1, 20): 0.3059931053133127, (10, 20): 0.28892229977946354, (100, 20): 0.2565958204235456, (1000, 20): 0.201310586096221, (10000, 20): 0.19311212218702406}
```

Graph.

```plot_metric(bench_lr, ylabel="classes",
title="scikit-learn vs mlprodict (LogisticRegression) \n"
"< 1 means mlprodict is faster\n no parallelisation")
```
```<AxesSubplot: title={'center': 'scikit-learn vs mlprodict (LogisticRegression) \n< 1 means mlprodict is faster\n no parallelisation'}, xlabel='N', ylabel='classes'>
```

## Decision Tree and number of features#

```ModelToTest = DecisionTreeClassifier

NF = [2, 10, 20, 40, 50, 70, 100, 200, 500, 1000]
N = [1, 10, 100, 1000, 10000, 50000]
trees_nf = {}

for nf in tqdm(NF):
ntest = 10000
X, y = make_classification(
n_samples=10000 + ntest, n_features=nf, n_informative=nf // 2 + 1,
n_redundant=0, n_repeated=0,
n_classes=2, random_state=11)
X_train, X_test, y_train, y_test = (
X[:-ntest], X[-ntest:], y[:-ntest], y[-ntest:])

dt = ModelToTest(max_depth=7).fit(X_train, y_train)

X32 = X_test.astype(numpy.float32)
monnx = to_onnx(dt, X32[:1])
oinf = OnnxInference(monnx)
oinf.sequence_[0].ops_.rt_.omp_N_ = 1000000
trees_nf[nf] = dict(model=dt, X_test=X_test,
X32=X32, monnx=monnx, oinf=oinf)

bench_dt_nf = tree_benchmark(
lambda nf: trees_nf[nf]['X32'],
lambda nf: trees_nf[nf]['model'].predict_proba,
lambda nf: (lambda x, c=nf: trees_nf[c]['oinf'].run({'X': x})), NF, N)
bench_dt_nf
```
```  0%|          | 0/10 [00:00<?, ?it/s]
20%|##        | 2/10 [00:00<00:01,  5.76it/s]
30%|###       | 3/10 [00:00<00:01,  3.52it/s]
40%|####      | 4/10 [00:01<00:02,  2.04it/s]
50%|#####     | 5/10 [00:02<00:03,  1.47it/s]
60%|######    | 6/10 [00:04<00:03,  1.08it/s]
70%|#######   | 7/10 [00:06<00:03,  1.27s/it]
80%|########  | 8/10 [00:10<00:04,  2.13s/it]
90%|######### | 9/10 [00:20<00:04,  4.63s/it]
100%|##########| 10/10 [00:41<00:00,  9.59s/it]
100%|##########| 10/10 [00:41<00:00,  4.10s/it]

0%|          | 0/10 [00:00<?, ?it/s]
10%|#         | 1/10 [00:07<01:07,  7.45s/it]
20%|##        | 2/10 [00:14<01:00,  7.50s/it]
30%|###       | 3/10 [00:22<00:53,  7.61s/it]
40%|####      | 4/10 [00:30<00:46,  7.72s/it]
50%|#####     | 5/10 [00:38<00:39,  7.82s/it]
60%|######    | 6/10 [00:46<00:31,  7.92s/it]
70%|#######   | 7/10 [00:55<00:24,  8.12s/it]
80%|########  | 8/10 [01:05<00:17,  8.95s/it]
90%|######### | 9/10 [01:21<00:10, 10.97s/it]
100%|##########| 10/10 [01:38<00:00, 12.98s/it]
100%|##########| 10/10 [01:38<00:00,  9.89s/it]

{(1, 2): 0.4896841501176273, (10, 2): 0.4888454401971804, (100, 2): 0.5131810893441255, (1000, 2): 0.6585346248590813, (10000, 2): 0.8736819471789613, (50000, 2): 0.9334582169654029, (1, 10): 0.4915019901213789, (10, 10): 0.48698072501552275, (100, 10): 0.5022208836436101, (1000, 10): 0.6511218467446952, (10000, 10): 0.8516657055543, (50000, 10): 0.9435406633118996, (1, 20): 0.4910993330824837, (10, 20): 0.48139594240507116, (100, 20): 0.49742513184403975, (1000, 20): 0.6385464306551805, (10000, 20): 0.8872343144480817, (50000, 20): 0.949627208583517, (1, 40): 0.49195783163346246, (10, 40): 0.48801275608797384, (100, 40): 0.5094033047526462, (1000, 40): 0.618931559854185, (10000, 40): 0.8805070005082319, (50000, 40): 0.9378458169571052, (1, 50): 0.4919402979828092, (10, 50): 0.4871566105412592, (100, 50): 0.5049670677173849, (1000, 50): 0.617345102867907, (10000, 50): 0.9015761370248575, (50000, 50): 0.9628279954093936, (1, 70): 0.4932732090646449, (10, 70): 0.4799090473142645, (100, 70): 0.5020359256169352, (1000, 70): 0.5823861276338875, (10000, 70): 0.8960540632191236, (50000, 70): 0.953114191418301, (1, 100): 0.49194774770580013, (10, 100): 0.4833173147683657, (100, 100): 0.5095202737948104, (1000, 100): 0.5355188242773441, (10000, 100): 0.8962070663569088, (50000, 100): 0.9491727528715674, (1, 200): 0.49191489510236525, (10, 200): 0.48648561433428444, (100, 200): 0.4910573744496424, (1000, 200): 0.5883259659625643, (10000, 200): 0.9112316219713957, (50000, 200): 0.9377477859726718, (1, 500): 0.48702304046431755, (10, 500): 0.48172075143063164, (100, 500): 0.488897090401364, (1000, 500): 0.7857517430291648, (10000, 500): 1.0532404946770288, (50000, 500): 1.0881838605037624, (1, 1000): 0.48981286047086997, (10, 1000): 0.48354916599586595, (100, 1000): 0.4721074740528367, (1000, 1000): 0.8279299858957623, (10000, 1000): 1.1058430842309033, (50000, 1000): 1.1460992483893526}
```

Graph.

```plot_metric(
bench_dt_nf, ylabel="number of features", transpose=True, figsize=(10, 4),
title="scikit-learn vs mlprodict (DecisionTreeClassifier) \n"
"< 1 means mlprodict is faster\n no parallelisation")
```
```<AxesSubplot: title={'center': 'scikit-learn vs mlprodict (DecisionTreeClassifier) \n< 1 means mlprodict is faster\n no parallelisation'}, xlabel='number of features', ylabel='N'>
```

Total running time of the script: ( 17 minutes 51.866 seconds)

Gallery generated by Sphinx-Gallery