ONNXMLTools

1.16.0 · active · verified Tue Apr 14

ONNXMLTools facilitates the conversion of various machine learning models (e.g., scikit-learn, LightGBM, XGBoost, TensorFlow, SparkML) into the ONNX (Open Neural Network Exchange) format. This enables model interoperability across different frameworks and hardware. The current version is 1.16.0, and it maintains an active development cycle with new releases every few months.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates converting a simple LightGBM classifier into the ONNX format. It highlights the use of `convert_lightgbm` and the importance of defining `initial_types` and `target_opset`. Remember to install `lightgbm`, `onnx`, and `onnx_lightgbm` separately for this to run.

import lightgbm as lgb
from onnxmltools import convert_lightgbm
from onnxmltools.convert.common.data_types import FloatTensorType
from onnx.checker import check_model
from onnx import save
import numpy as np

# Ensure required packages are installed
try:
    import lightgbm # noqa: F401
    import onnx_lightgbm # noqa: F401
    import onnx # noqa: F401
except ImportError as e:
    print(f"Skipping quickstart: Missing dependency. Please install lightgbm, onnx, and onnx_lightgbm. Error: {e}")
    exit()

# 1. Train a LightGBM model
X = np.array([[0, 0], [1, 1], [2, 2], [3, 3]], dtype=np.float32)
y = np.array([0, 1, 1, 0], dtype=np.int32)
gbm = lgb.LGBMClassifier(n_estimators=3, max_depth=2, learning_rate=0.1, random_state=42)
gbm.fit(X, y)

# 2. Define initial types for ONNX conversion
# 'None' in FloatTensorType([None, 2]) means variable batch size
initial_type = [('float_input', FloatTensorType([None, 2]))]

# 3. Convert to ONNX format, specifying a target opset (e.g., 17)
target_opset = 17 # Or a lower opset depending on ONNX Runtime compatibility
onnx_model = convert_lightgbm(gbm, initial_types=initial_type, target_opset=target_opset)

# 4. Check the ONNX model for validity
check_model(onnx_model)

# 5. Save the ONNX model to a file
save(onnx_model, "lightgbm_model.onnx")

print("LightGBM model successfully converted to lightgbm_model.onnx")

view raw JSON →