Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
MLNetExportToOnnx.cs
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);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.