#MLNET – Exportando modelos de Machine Learning.Net a formato #ONNX

Buenas!

Machine Learning.Net tiene un nuevo release y en esta versión 0.3, hay varias features interesantes. En el post de Cesar De la Torre se comentan estas nuevas features (ver referencias). Yo he tenido un hueco en estos días y me he dedicado a probar algo que me parece muy interesante

La capacidad de exportar modelos Machine Learning.Net a formato ONNX.

Como siempre lo mejor es explicarlo con un par de líneas de código

  • Hasta la línea 28, la Console App crea un Pipeline, y lo entrena para tener un Modelo ML.Net.
  • En las siguientes líneas, utilizando un OnnxConverter, exporto el modelo a ONNX.


using System.IO;
using System.Text.RegularExpressions;
using Microsoft.ML;
using Microsoft.ML.Data;
using Microsoft.ML.Models;
using Microsoft.ML.Trainers;
using Microsoft.ML.Transforms;
using MLNetConsole05;
namespace MLNetConsole06
{
class Program
{
const string FileName = "AgeRangeData.csv";
const string OnnxPath = "SaveModelToOnnxTest.onnx";
const string OnnxAsJsonPath = "SaveModelToOnnxTest.json";
static void Main()
{
var pipeline = new LearningPipeline
{
new TextLoader(FileName).CreateFrom<AgeRange>(separator: ',', useHeader: true),
new Dictionarizer("Label"),
new TextFeaturizer("Sex", "Sex"),
new ColumnConcatenator("Features", "Age", "Sex"),
new StochasticDualCoordinateAscentClassifier(),
new PredictedLabelColumnOriginalValueConverter() {PredictedLabelColumn = "PredictedLabel"}
};
var model = pipeline.Train<AgeRange, AgeRangePrediction>();
var converter = new OnnxConverter()
{
Onnx = OnnxPath,
Json = OnnxAsJsonPath,
Domain = "com.elbruno"
};
converter.Convert(model);
// Strip the version.
var fileText = File.ReadAllText(OnnxAsJsonPath);
fileText = Regex.Replace(fileText, "\"producerVersion\": \"([^\"]+)\"", "\"producerVersion\": \"##VERSION##\"");
File.WriteAllText(OnnxAsJsonPath, fileText);
}
}
}

La documentación de OnnxConverter y los ejemplos de ML.Net detallan escenarios más complejos donde por ejemplo se definen que columnas se incluyen o excluyen. Si abrimos el archivo Onnx, es interesante ver como se representa un pipeline simple como el de este ejemplo

01

Happy Coding!

Saludos @ Toronto

El Bruno

References

My Posts

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: