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
Happy Coding!
Saludos @ Toronto
El Bruno
References
My Posts
- Loading Data In our Learning Pipeline With List (Lists for ever!)
- What’s new in version 0.2.0
- What’s a Machine Learning model? A 7 minute video as the best possible explanation
- Write and Load models using Machine Learning .Net
- Understanding the step by step of Hello World
- Hello World in ML.Net, Machine Learning for .Net !