Skip to content

Instantly share code, notes, and snippets.

@elbruno
Created July 10, 2018 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elbruno/9ba9504786d267ea9513eaacbece552e to your computer and use it in GitHub Desktop.
Save elbruno/9ba9504786d267ea9513eaacbece552e to your computer and use it in GitHub Desktop.
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