Loading a Keras Model with ML.NET
Introduction
ML.NET is a powerful machine learning framework for .NET applications. While ML.NET offers extensive functionality, it sometimes becomes necessary to leverage pre-trained models created with other frameworks like Keras. This article explores the process of loading a Keras model into an ML.NET application.
Prerequisites
- Visual Studio with ML.NET workload installed
- Keras model (saved as an HDF5 file, .h5)
- ONNX runtime (NuGet package: Microsoft.ML.OnnxRuntime)
Conversion to ONNX
ML.NET utilizes ONNX (Open Neural Network Exchange) format for model loading. Therefore, the Keras model must be converted to ONNX before it can be used with ML.NET.
Code Example: Converting a Keras Model to ONNX
pip install onnx
pip install onnxruntime
pip install keras2onnx
import keras2onnx
import onnx
# Load your Keras model
model = keras.models.load_model('your_keras_model.h5')
# Convert the model to ONNX format
onnx_model = keras2onnx.convert_keras(model, 'your_keras_model.onnx')
# Save the ONNX model
onnx.save(onnx_model, 'your_keras_model.onnx')
Loading and Using the ONNX Model in ML.NET
Once the model is converted to ONNX, you can load and use it within your ML.NET application.
Code Example: Loading the ONNX Model in ML.NET
using Microsoft.ML;
using Microsoft.ML.OnnxRuntime;
// Load the ONNX model
var onnxModel = new OnnxModel(Path.Combine("your_keras_model.onnx"));
// Create an MLContext
var mlContext = new MLContext();
// Create an OnnxTransformer
var onnxTransformer = mlContext.Transforms.ApplyOnnxModel(
onnxModel,
new[] { "Input" }, // Input node name(s)
new[] { "Output" } // Output node name(s)
);
// Create a pipeline
var pipeline = mlContext.Transforms.Concatenate("Features", "Input")
.Append(onnxTransformer);
// Train (actually load) the model
var model = pipeline.Fit(data);
// Use the loaded model to make predictions
var prediction = model.Transform(testData);
Example: MNIST Classification
Here’s an example demonstrating the process using the MNIST dataset for handwritten digit classification:
Keras Model | ONNX Conversion | ML.NET Loading |
---|---|---|
|
|
|
Conclusion
Loading pre-trained Keras models into ML.NET applications is achievable through the ONNX conversion process. This enables the integration of external model expertise while harnessing the power of ML.NET for .NET development.