Note
Click here to download the full example code
Benchmark Random Forests, Tree Ensemble, Multi-Classification#
The script compares different implementations for the operator TreeEnsembleRegressor for a multi-regression. It replicates the benchmark Benchmark Random Forests, Tree Ensemble, (AoS and SoA) for multi-classification.
Import#
import warnings
from time import perf_counter as time
from multiprocessing import cpu_count
import numpy
from numpy.random import rand
from numpy.testing import assert_almost_equal
import pandas
import matplotlib.pyplot as plt
from sklearn import config_context
from sklearn.ensemble import RandomForestClassifier
from sklearn.utils._testing import ignore_warnings
from skl2onnx import convert_sklearn
from skl2onnx.common.data_types import FloatTensorType
from onnxruntime import InferenceSession
from mlprodict.onnxrt import OnnxInference
Available optimisation on this machine.
from mlprodict.testing.experimental_c_impl.experimental_c import code_optimisation
print(code_optimisation())
Out:
AVX-omp=8
Versions#
def version():
from datetime import datetime
import sklearn
import numpy
import onnx
import onnxruntime
import skl2onnx
import mlprodict
df = pandas.DataFrame([
{"name": "date", "version": str(datetime.now())},
{"name": "numpy", "version": numpy.__version__},
{"name": "scikit-learn", "version": sklearn.__version__},
{"name": "onnx", "version": onnx.__version__},
{"name": "onnxruntime", "version": onnxruntime.__version__},
{"name": "skl2onnx", "version": skl2onnx.__version__},
{"name": "mlprodict", "version": mlprodict.__version__},
])
return df
version()
Implementations to benchmark#
def fcts_model(X, y, max_depth, n_estimators, n_jobs):
"RandomForestClassifier."
rf = RandomForestClassifier(max_depth=max_depth, n_estimators=n_estimators,
n_jobs=n_jobs)
rf.fit(X, y)
initial_types = [('X', FloatTensorType([None, X.shape[1]]))]
onx = convert_sklearn(rf, initial_types=initial_types,
options={id(rf): {'zipmap': False}})
sess = InferenceSession(onx.SerializeToString())
outputs = [o.name for o in sess.get_outputs()]
oinf = OnnxInference(onx, runtime="python")
oinf.sequence_[0].ops_._init(numpy.float32, 1)
name = outputs[1]
oinf2 = OnnxInference(onx, runtime="python")
oinf2.sequence_[0].ops_._init(numpy.float32, 2)
oinf3 = OnnxInference(onx, runtime="python")
oinf3.sequence_[0].ops_._init(numpy.float32, 3)
def predict_skl_predict(X, model=rf):
return rf.predict_proba(X)
def predict_onnxrt_predict(X, sess=sess):
return sess.run(outputs[:1], {'X': X})[0]
def predict_onnx_inference(X, oinf=oinf):
return oinf.run({'X': X})[name]
def predict_onnx_inference2(X, oinf2=oinf2):
return oinf2.run({'X': X})[name]
def predict_onnx_inference3(X, oinf3=oinf3):
return oinf3.run({'X': X})[name]
return {'predict': (
predict_skl_predict, predict_onnxrt_predict,
predict_onnx_inference, predict_onnx_inference2,
predict_onnx_inference3)}
Benchmarks#
def allow_configuration(**kwargs):
return True
def bench(n_obs, n_features, max_depths, n_estimatorss, n_jobss,
methods, repeat=10, verbose=False):
res = []
for nfeat in n_features:
ntrain = 50000
X_train = numpy.empty((ntrain, nfeat)).astype(numpy.float32)
X_train[:, :] = rand(ntrain, nfeat)[:, :]
eps = rand(ntrain) - 0.5
y_train_f = X_train.sum(axis=1) + eps
y_train = (y_train_f > 12).astype(numpy.int64)
y_train[y_train_f > 15] = 2
y_train[y_train_f < 10] = 3
for n_jobs in n_jobss:
for max_depth in max_depths:
for n_estimators in n_estimatorss:
fcts = fcts_model(X_train, y_train,
max_depth, n_estimators, n_jobs)
for n in n_obs:
for method in methods:
fct1, fct2, fct3, fct4, fct5 = fcts[method]
if not allow_configuration(
n=n, nfeat=nfeat, max_depth=max_depth,
n_estimator=n_estimators, n_jobs=n_jobs,
method=method):
continue
obs = dict(n_obs=n, nfeat=nfeat,
max_depth=max_depth,
n_estimators=n_estimators,
method=method,
n_jobs=n_jobs)
# creates different inputs to avoid caching
Xs = []
for r in range(repeat):
x = numpy.empty((n, nfeat))
x[:, :] = rand(n, nfeat)[:, :]
Xs.append(x.astype(numpy.float32))
# measures the baseline
with config_context(assume_finite=True):
st = time()
repeated = 0
for X in Xs:
p1 = fct1(X)
repeated += 1
if time() - st >= 1:
break # stops if longer than a second
end = time()
obs["time_skl"] = (end - st) / repeated
# measures the new implementation
st = time()
r2 = 0
for X in Xs:
p2 = fct2(X)
r2 += 1
if r2 >= repeated:
break
end = time()
obs["time_ort"] = (end - st) / r2
# measures the other new implementation
st = time()
r2 = 0
for X in Xs:
p2 = fct3(X)
r2 += 1
if r2 >= repeated:
break
end = time()
obs["time_mlprodict"] = (end - st) / r2
# measures the other new implementation 2
st = time()
r2 = 0
for X in Xs:
p2 = fct4(X)
r2 += 1
if r2 >= repeated:
break
end = time()
obs["time_mlprodict2"] = (end - st) / r2
# measures the other new implementation 3
st = time()
r2 = 0
for X in Xs:
p2 = fct5(X)
r2 += 1
if r2 >= repeated:
break
end = time()
obs["time_mlprodict3"] = (end - st) / r2
# final
res.append(obs)
if verbose and (len(res) % 1 == 0 or n >= 10000):
print("bench", len(res), ":", obs)
# checks that both produce the same outputs
if n <= 10000:
if len(p1.shape) == 1 and len(p2.shape) == 2:
p2 = p2.ravel()
try:
assert_almost_equal(
p1.ravel(), p2.ravel(), decimal=5)
except AssertionError as e:
warnings.warn(str(e))
return res
Graphs#
def plot_rf_models(dfr):
def autolabel(ax, rects):
for rect in rects:
height = rect.get_height()
ax.annotate('%1.1fx' % height,
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom',
fontsize=8)
engines = [_.split('_')[-1] for _ in dfr.columns if _.startswith("time_")]
engines = [_ for _ in engines if _ != 'skl']
for engine in engines:
dfr["speedup_%s" % engine] = dfr["time_skl"] / dfr["time_%s" % engine]
print(dfr.tail().T)
ncols = 4
fig, axs = plt.subplots(len(engines), ncols, figsize=(
14, 4 * len(engines)), sharey=True)
row = 0
for row, engine in enumerate(engines):
pos = 0
name = "RandomForestClassifier - %s" % engine
for max_depth in sorted(set(dfr.max_depth)):
for nf in sorted(set(dfr.nfeat)):
for est in sorted(set(dfr.n_estimators)):
for n_jobs in sorted(set(dfr.n_jobs)):
sub = dfr[(dfr.max_depth == max_depth) &
(dfr.nfeat == nf) &
(dfr.n_estimators == est) &
(dfr.n_jobs == n_jobs)]
ax = axs[row, pos]
labels = sub.n_obs
means = sub["speedup_%s" % engine]
x = numpy.arange(len(labels))
width = 0.90
rects1 = ax.bar(x, means, width, label='Speedup')
if pos == 0:
ax.set_yscale('log')
ax.set_ylim([0.1, max(dfr["speedup_%s" % engine])])
if pos == 0:
ax.set_ylabel('Speedup')
ax.set_title(
'%s\ndepth %d - %d features\n %d estimators '
'%d jobs' % (name, max_depth, nf, est, n_jobs))
if row == len(engines) - 1:
ax.set_xlabel('batch size')
ax.set_xticks(x)
ax.set_xticklabels(labels)
autolabel(ax, rects1)
for tick in ax.xaxis.get_major_ticks():
tick.label.set_fontsize(8)
for tick in ax.yaxis.get_major_ticks():
tick.label.set_fontsize(8)
pos += 1
fig.tight_layout()
return fig, ax
Run benchs#
@ignore_warnings(category=FutureWarning)
def run_bench(repeat=100, verbose=False):
n_obs = [1, 10, 100, 1000, 10000]
methods = ['predict']
n_features = [30]
max_depths = [6, 8, 10, 12]
n_estimatorss = [100]
n_jobss = [cpu_count()]
start = time()
results = bench(n_obs, n_features, max_depths, n_estimatorss, n_jobss,
methods, repeat=repeat, verbose=verbose)
end = time()
results_df = pandas.DataFrame(results)
print("Total time = %0.3f sec cpu=%d\n" % (end - start, cpu_count()))
# plot the results
return results_df
name = "plot_random_forest_cls_multi"
df = run_bench(verbose=True)
df.to_csv("%s.csv" % name, index=False)
df.to_excel("%s.xlsx" % name, index=False)
fig, ax = plot_rf_models(df)
fig.savefig("%s.png" % name)
plt.show()

Out:
bench 1 : {'n_obs': 1, 'nfeat': 30, 'max_depth': 6, 'n_estimators': 100, 'method': 'predict', 'n_jobs': 8, 'time_skl': 0.06354205818752234, 'time_ort': 0.00012871431272287737, 'time_mlprodict': 0.00294123906223831, 'time_mlprodict2': 0.00010131712497241097, 'time_mlprodict3': 7.568731280116481e-05}
bench 2 : {'n_obs': 10, 'nfeat': 30, 'max_depth': 6, 'n_estimators': 100, 'method': 'predict', 'n_jobs': 8, 'time_skl': 0.0645933948126185, 'time_ort': 0.0005140403122823045, 'time_mlprodict': 0.000538195062745217, 'time_mlprodict2': 0.00042390312501083827, 'time_mlprodict3': 0.000350292687471665}
bench 3 : {'n_obs': 100, 'nfeat': 30, 'max_depth': 6, 'n_estimators': 100, 'method': 'predict', 'n_jobs': 8, 'time_skl': 0.07300797035713913, 'time_ort': 0.0006493797856299872, 'time_mlprodict': 0.004251855571575496, 'time_mlprodict2': 0.002303869071121361, 'time_mlprodict3': 0.00023620978598566062}
bench 4 : {'n_obs': 1000, 'nfeat': 30, 'max_depth': 6, 'n_estimators': 100, 'method': 'predict', 'n_jobs': 8, 'time_skl': 0.12150082655555, 'time_ort': 0.003188682778272778, 'time_mlprodict': 0.014704503000151211, 'time_mlprodict2': 0.013718607666507725, 'time_mlprodict3': 0.001574249333417457}
bench 5 : {'n_obs': 10000, 'nfeat': 30, 'max_depth': 6, 'n_estimators': 100, 'method': 'predict', 'n_jobs': 8, 'time_skl': 0.14917438385704632, 'time_ort': 0.029229423285869416, 'time_mlprodict': 0.09533169114313621, 'time_mlprodict2': 0.08892240999973312, 'time_mlprodict3': 0.014768169428862166}
bench 6 : {'n_obs': 1, 'nfeat': 30, 'max_depth': 8, 'n_estimators': 100, 'method': 'predict', 'n_jobs': 8, 'time_skl': 0.06329377881274922, 'time_ort': 0.00012457806269594585, 'time_mlprodict': 0.0034964814999511873, 'time_mlprodict2': 0.0001381798124384659, 'time_mlprodict3': 8.424787483818363e-05}
bench 7 : {'n_obs': 10, 'nfeat': 30, 'max_depth': 8, 'n_estimators': 100, 'method': 'predict', 'n_jobs': 8, 'time_skl': 0.06227006700004602, 'time_ort': 0.0007976788825437645, 'time_mlprodict': 0.0008084052353618009, 'time_mlprodict2': 0.0007888353528174133, 'time_mlprodict3': 0.0007936095297576257}
bench 8 : {'n_obs': 100, 'nfeat': 30, 'max_depth': 8, 'n_estimators': 100, 'method': 'predict', 'n_jobs': 8, 'time_skl': 0.07467367892864527, 'time_ort': 0.001290559571706191, 'time_mlprodict': 0.0047430925712563165, 'time_mlprodict2': 0.0016066134999813844, 'time_mlprodict3': 0.0005106947142589238}
bench 9 : {'n_obs': 1000, 'nfeat': 30, 'max_depth': 8, 'n_estimators': 100, 'method': 'predict', 'n_jobs': 8, 'time_skl': 0.1145002697780405, 'time_ort': 0.004566760777379386, 'time_mlprodict': 0.015476821777863532, 'time_mlprodict2': 0.012105793111711845, 'time_mlprodict3': 0.002302260666814012}
bench 10 : {'n_obs': 10000, 'nfeat': 30, 'max_depth': 8, 'n_estimators': 100, 'method': 'predict', 'n_jobs': 8, 'time_skl': 0.15006543171434064, 'time_ort': 0.045116901142007136, 'time_mlprodict': 0.12711229671445576, 'time_mlprodict2': 0.11950761928580635, 'time_mlprodict3': 0.01897591757109954}
bench 11 : {'n_obs': 1, 'nfeat': 30, 'max_depth': 10, 'n_estimators': 100, 'method': 'predict', 'n_jobs': 8, 'time_skl': 0.06181529752939241, 'time_ort': 0.00015903129422119544, 'time_mlprodict': 0.0030822223527459704, 'time_mlprodict2': 0.0001879986474009724, 'time_mlprodict3': 9.217435281778522e-05}
bench 12 : {'n_obs': 10, 'nfeat': 30, 'max_depth': 10, 'n_estimators': 100, 'method': 'predict', 'n_jobs': 8, 'time_skl': 0.06701892919954844, 'time_ort': 0.0010383266000038324, 'time_mlprodict': 0.000994429133425001, 'time_mlprodict2': 0.0011610766664186182, 'time_mlprodict3': 0.0007278798667054313}
bench 13 : {'n_obs': 100, 'nfeat': 30, 'max_depth': 10, 'n_estimators': 100, 'method': 'predict', 'n_jobs': 8, 'time_skl': 0.08357718015423206, 'time_ort': 0.001646990691929554, 'time_mlprodict': 0.00477017930769272, 'time_mlprodict2': 0.002103537615487137, 'time_mlprodict3': 0.0008332406152756169}
bench 14 : {'n_obs': 1000, 'nfeat': 30, 'max_depth': 10, 'n_estimators': 100, 'method': 'predict', 'n_jobs': 8, 'time_skl': 0.12019978111089182, 'time_ort': 0.006828377444536373, 'time_mlprodict': 0.019459850666559458, 'time_mlprodict2': 0.01877456666665643, 'time_mlprodict3': 0.003468514333589054}
bench 15 : {'n_obs': 10000, 'nfeat': 30, 'max_depth': 10, 'n_estimators': 100, 'method': 'predict', 'n_jobs': 8, 'time_skl': 0.14767822928531263, 'time_ort': 0.04853249728642238, 'time_mlprodict': 0.1678714985713928, 'time_mlprodict2': 0.1810835467144248, 'time_mlprodict3': 0.02522408600011009}
bench 16 : {'n_obs': 1, 'nfeat': 30, 'max_depth': 12, 'n_estimators': 100, 'method': 'predict', 'n_jobs': 8, 'time_skl': 0.06460072037498321, 'time_ort': 0.00011892062502738554, 'time_mlprodict': 0.0031357383127215144, 'time_mlprodict2': 0.0002215833746959106, 'time_mlprodict3': 9.782643746802933e-05}
bench 17 : {'n_obs': 10, 'nfeat': 30, 'max_depth': 12, 'n_estimators': 100, 'method': 'predict', 'n_jobs': 8, 'time_skl': 0.07174957899977537, 'time_ort': 0.001167197214402092, 'time_mlprodict': 0.0011831978569846666, 'time_mlprodict2': 0.0013940542859407806, 'time_mlprodict3': 0.00033083371402296634}
bench 18 : {'n_obs': 100, 'nfeat': 30, 'max_depth': 12, 'n_estimators': 100, 'method': 'predict', 'n_jobs': 8, 'time_skl': 0.08903703141671333, 'time_ort': 0.0019349925836043742, 'time_mlprodict': 0.005166244249873368, 'time_mlprodict2': 0.0027020139162535393, 'time_mlprodict3': 0.0011695020833334031}
bench 19 : {'n_obs': 1000, 'nfeat': 30, 'max_depth': 12, 'n_estimators': 100, 'method': 'predict', 'n_jobs': 8, 'time_skl': 0.11922896444432102, 'time_ort': 0.009758657222038083, 'time_mlprodict': 0.0216845111111373, 'time_mlprodict2': 0.02257569533362079, 'time_mlprodict3': 0.005062062332904639}
bench 20 : {'n_obs': 10000, 'nfeat': 30, 'max_depth': 12, 'n_estimators': 100, 'method': 'predict', 'n_jobs': 8, 'time_skl': 0.15181953100026085, 'time_ort': 0.0753591640002144, 'time_mlprodict': 0.18593439099952644, 'time_mlprodict2': 0.22329019057152827, 'time_mlprodict3': 0.0387260398575953}
Total time = 216.418 sec cpu=8
15 16 17 18 19
n_obs 1 10 100 1000 10000
nfeat 30 30 30 30 30
max_depth 12 12 12 12 12
n_estimators 100 100 100 100 100
method predict predict predict predict predict
n_jobs 8 8 8 8 8
time_skl 0.064601 0.07175 0.089037 0.119229 0.15182
time_ort 0.000119 0.001167 0.001935 0.009759 0.075359
time_mlprodict 0.003136 0.001183 0.005166 0.021685 0.185934
time_mlprodict2 0.000222 0.001394 0.002702 0.022576 0.22329
time_mlprodict3 0.000098 0.000331 0.00117 0.005062 0.038726
speedup_ort 543.225537 61.471685 46.014146 12.217763 2.014613
speedup_mlprodict 20.601439 60.64039 17.234383 5.498347 0.816522
speedup_mlprodict2 291.541369 51.468282 32.952099 5.281298 0.67992
speedup_mlprodict3 660.360553 216.875052 76.132427 23.553437 3.920347
Total running time of the script: ( 3 minutes 49.118 seconds)