Skip to main content

Converting scikit-learn Models to ONNX

The skl2onnx library enables conversion of scikit-learn models to ONNX format, allowing you to deploy traditional machine learning models with ONNX Runtime for improved performance.

Prerequisites

Basic Conversion

Simple Classification Model

Regression Model

Pipeline Conversion

Convert entire scikit-learn pipelines including preprocessing:

Advanced Conversions

Multiple Input Types

Custom Options

Control conversion behavior with options:

Supported Models

Classification

  • LogisticRegression
  • DecisionTreeClassifier
  • RandomForestClassifier
  • GradientBoostingClassifier
  • SVC (Support Vector Classifier)
  • MLPClassifier
  • KNeighborsClassifier

Regression

  • LinearRegression
  • Ridge, Lasso, ElasticNet
  • DecisionTreeRegressor
  • RandomForestRegressor
  • GradientBoostingRegressor
  • SVR (Support Vector Regressor)
  • MLPRegressor

Clustering

  • KMeans
  • DBSCAN
  • AgglomerativeClustering

Preprocessing

  • StandardScaler, MinMaxScaler
  • OneHotEncoder, LabelEncoder
  • PCA, TruncatedSVD
  • PolynomialFeatures
  • Imputer

Inference with ONNX Runtime

Validation

Always validate that the ONNX model produces the same results:

Text Processing Example

Convert text processing pipelines:

Handling Missing Values

Best Practices

  1. Specify batch dimension as None: Allow variable batch sizes with [None, n_features]
  2. Use pipelines: Convert entire workflows including preprocessing
  3. Validate outputs: Always compare sklearn and ONNX predictions
  4. Set target_opset: Use opset 14 or higher for compatibility
  5. Test edge cases: Validate with various input types and ranges
  6. Handle data types: Ensure input data types match the initial_types specification
  7. Disable ZipMap for production: Set {'zipmap': False} for classification models

Troubleshooting

Common Issues

“Operator not supported”: Check skl2onnx documentation for supported operators
Shape mismatch errors: Verify that initial_types matches your model’s expected input Type conversion errors: Ensure input data is the correct type (e.g., float32)

Performance Comparison

Next Steps