|
| 1 | +""" |
| 2 | +
|
| 3 | +.. _l-onnx-diff-example: |
| 4 | +
|
| 5 | +Compares the conversions of the same model with different options |
| 6 | +================================================================= |
| 7 | +
|
| 8 | +The script compares two onnx models obtained with the same trained |
| 9 | +scikit-learn models but converted with different options. |
| 10 | +
|
| 11 | +A model |
| 12 | ++++++++ |
| 13 | +""" |
| 14 | + |
| 15 | +fromsklearn.mixtureimportGaussianMixture |
| 16 | +fromsklearn.datasetsimportload_iris |
| 17 | +fromsklearn.model_selectionimporttrain_test_split |
| 18 | +fromskl2onnximportto_onnx |
| 19 | +fromonnx_array_api.referenceimportcompare_onnx_execution |
| 20 | +fromonnx_array_api.plotting.text_plotimportonnx_simple_text_plot |
| 21 | + |
| 22 | + |
| 23 | +data=load_iris() |
| 24 | +X_train,X_test=train_test_split(data.data) |
| 25 | +model=GaussianMixture() |
| 26 | +model.fit(X_train) |
| 27 | + |
| 28 | +################################# |
| 29 | +# Conversion to onnx |
| 30 | +# ++++++++++++++++++ |
| 31 | + |
| 32 | +onx=to_onnx( |
| 33 | +model,X_train[:1],options={id(model): {"score_samples":True}},target_opset=12 |
| 34 | +) |
| 35 | + |
| 36 | +print(onnx_simple_text_plot(onx)) |
| 37 | + |
| 38 | +################################## |
| 39 | +# Conversion to onnx without ReduceLogSumExp |
| 40 | +# ++++++++++++++++++++++++++++++++++++++++++ |
| 41 | + |
| 42 | +onx2=to_onnx( |
| 43 | +model, |
| 44 | +X_train[:1], |
| 45 | +options={id(model): {"score_samples":True}}, |
| 46 | +black_op={"ReduceLogSumExp"}, |
| 47 | +target_opset=12, |
| 48 | +) |
| 49 | + |
| 50 | +print(onnx_simple_text_plot(onx2)) |
| 51 | + |
| 52 | + |
| 53 | +############################################# |
| 54 | +# Differences |
| 55 | +# +++++++++++ |
| 56 | +# |
| 57 | +# Function :func:`onnx_array_api.reference.compare_onnx_execution` |
| 58 | +# compares the intermediate results of two onnx models. Then it finds |
| 59 | +# the best alignmet between the two models using an edit distance. |
| 60 | + |
| 61 | +res1,res2,align,dc=compare_onnx_execution(onx,onx2,verbose=1) |
| 62 | +print("------------") |
| 63 | +text=dc.to_str(res1,res2,align) |
| 64 | +print(text) |
| 65 | + |
| 66 | +############################### |
| 67 | +# The display shows that ReduceSumSquare was replaced by Mul + ReduceSum, |
| 68 | +# and ReduceLogSumExp by ReduceMax + Sub + Exp + Log + Add. |