自訂模型的自訂轉換器

sklearn-onnx 轉換 scikit-learn 管線時,它會檢視每個轉換器和預測器,並擷取相關聯的轉換器。產生的 ONNX 圖表會將每個轉換器的結果組合到單一圖表中。如果模型沒有其轉換器,它會顯示錯誤訊息,指出它缺少轉換器。

<<<

import numpy
from sklearn.linear_model import LogisticRegression
from skl2onnx import to_onnx


class MyLogisticRegression(LogisticRegression):
    pass


X = numpy.array([[0, 0.1]])
try:
    to_onnx(MyLogisticRegression(), X)
except Exception as e:
    print(e)

>>>

    Unable to find a shape calculator for type '<class 'sphinx_runpython.runpython.sphinx_runpython_extension.run_python_script_140489269341504.<locals>.MyLogisticRegression'>'.
    It usually means the pipeline being converted contains a
    transformer or a predictor with no corresponding converter
    implemented in sklearn-onnx. If the converted is implemented
    in another library, you need to register
    the converted so that it can be used by sklearn-onnx (function
    update_registered_converter). If the model is not yet covered
    by sklearn-onnx, you may raise an issue to
    https://github.com/onnx/sklearn-onnx/issues
    to get the converter implemented or even contribute to the
    project. If the model is a custom model, a new converter must
    be implemented. Examples can be found in the gallery.

以下章節說明如何建立自訂轉換器。它假設這個新的轉換器並非要新增到此套件,而只是在轉換管線時註冊和使用。若要貢獻並為 scikit-learn 模型新增轉換器,邏輯仍然相同,只有轉換器註冊會變更。PR 737 可以作為範例。