Skip to content

Commit d9584cf

Browse files
authored
Fixes onnx exports for binary classification trainers (#4463)
* Squashed commit of the following: commit a5e274ef8869576190bbb794360a5f56d998b470 Merge: b7db4fa d7f9996 Author: Keren Fuentes <dkeren@seas.upenn.edu> Date: Thu Nov 14 14:51:21 2019 -0800 Merge branch 'onnx_bin_classifiers' of https://github.com/Lynx1820/machinelearning into onnx_bin_classifiers commit b7db4fa Author: Harish Kulkarni <harishsk@users.noreply.github.com> Date: Thu Nov 14 17:41:12 2019 +0000 Added onnx export support for KeyToValueMappingTransformer (#4455) commit f3e0f6b Author: Eric Erhardt <eric.erhardt@microsoft.com> Date: Thu Nov 14 07:22:12 2019 -0600 Fix a flaky Extensions.ML test. (#4458) * Fix a flaky Extensions.ML test. Make the reload model tests more resistant to timing changes. * PR feedback. commit c1e190a Author: Harish Kulkarni <harishsk@users.noreply.github.com> Date: Thu Nov 14 05:24:14 2019 +0000 Added onnx export support for OptionalColumnTransform (#4454) * Initial work for adding onnx export support for OptionalColumnTransform * Implemented support for optional initializers in OnnxTranformer to support OptionalColumnTransform * Fixed handling of double values and non-long numeric types * Removed redundant line * Updated review comment commit f96761b Author: Harish Kulkarni <harishsk@users.noreply.github.com> Date: Thu Nov 14 03:17:12 2019 +0000 Fixed model saving and loading of OneVersusAllTrainer to include SoftMax (#4472) * Fixed model saving and loading of OneVersusAllTrainer to include SoftMax * Modified existing test to include SoftMax option * Modified test to verify both cases: when UseSoftmax is true and false commit d45cc8a Author: Jake <31937616+JakeRadMSFT@users.noreply.github.com> Date: Wed Nov 13 17:26:49 2019 -0800 Add InternalsVisibleTo in AutoML and CodeGenerator for the assembly Microsoft.ML.ModelBuilder.AutoMLService.Gpu (#4474) commit 5e83e23 Author: Eric Erhardt <eric.erhardt@microsoft.com> Date: Wed Nov 13 16:09:05 2019 -0600 CpuMathNative assembly is not getting copied when using packages.config. (#4465) When we refactored CpuMath to support netcoreapp3.0, we broke the packages.config support to copy the native assembly. This fixes it again by copying the file from the correct location. Fix #93 commit 693250b Author: Harish Kulkarni <harishsk@users.noreply.github.com> Date: Wed Nov 13 21:58:07 2019 +0000 Added onnx export support for WordTokenizingTransformer and NgramExtractingTransformer (#4451) * Added onnx export support for string related transforms * Updated baseline test files A large portion of this commit is upgrading the baseline test files. The rest of the fixes deal with build breaks resulting from the upgrade of ORT version. * Fixed bugs in ValueToKeyMappingTransformer and added additional tests commit 5910910 Author: Antonio Velázquez <38739674+antoniovs1029@users.noreply.github.com> Date: Mon Nov 11 17:19:39 2019 -0800 Fixes #4292 about using PFI with BPT and CMPB (#4306) *Changes in PredictionTransformer.cs and Calibrator.cs to fix the problem of the create methods not being called, to make CMP load its internal calibrator and predictor first so to assign the correct paramaters types and runtimes, and added a PredictionTransformerLoadTypeAttribute so that the binary prediction transformer knows what type to assign when loading a CMP as its internal model. *Added a working sample for using PFI with BPT and CMPB while loading a model from disk. This is based entirely in the original sample. *Added file CalibratedModelParametersTests.cs with tests that the CMPs modified in this PR are now being correctly loaded from disk. *Changed a couple of tests in LbfgsTests.cs that failed because they used casts that now return 'null'. commit bcdac55 Author: Brian Stark <54910472+bpstark@users.noreply.github.com> Date: Mon Nov 11 13:42:42 2019 -0800 Stabilize the LR test (#4446) * Stabilize the LR test Found issue with how we were using random for our ImageClassificationTrainer. This caused instability in our unit test, as we were not able to control the random seed. Modified the code to now use the same random object throughout, the trainer, thus allowing us to control the seed and therefor have predictable output. commit d7f9996 Author: Keren Fuentes <dkeren@seas.upenn.edu> Date: Mon Nov 11 11:33:17 2019 -0800 workaround Scores commit 7fba31c Merge: 93388b6 c96d690 Author: Keren Fuentes <dkeren@seas.upenn.edu> Date: Mon Nov 11 11:25:28 2019 -0800 merging changes commit 93388b6 Author: Keren Fuentes <dkeren@seas.upenn.edu> Date: Mon Nov 11 11:19:59 2019 -0800 Added extraction of score column before node creation commit ea71828 Author: Keren Fuentes <dkeren@seas.upenn.edu> Date: Fri Nov 8 15:53:11 2019 -0800 fix for binary classification trainers export to onnx commit 6fad293 Author: Keren Fuentes <dkeren@seas.upenn.edu> Date: Thu Oct 31 15:26:43 2019 -0700 Revert "draft regression test" This reverts commit 1ad45c995516b9d39fc05aca855ce2abe96c407b. commit 83c1c80 Author: Keren Fuentes <dkeren@seas.upenn.edu> Date: Thu Oct 31 15:24:23 2019 -0700 draft regression test commit 8884161 Author: frank-dong-ms <55860649+frank-dong-ms@users.noreply.github.com> Date: Fri Nov 8 20:20:53 2019 -0800 nightly build pipeline (#4444) * nightly build pipeline commit c96d690 Author: Keren Fuentes <dkeren@seas.upenn.edu> Date: Fri Nov 8 15:53:11 2019 -0800 fix for binary classification trainers export to onnx commit 8100364 Author: Keren Fuentes <dkeren@seas.upenn.edu> Date: Thu Oct 31 15:26:43 2019 -0700 Revert "draft regression test" This reverts commit 1ad45c995516b9d39fc05aca855ce2abe96c407b. commit 81381e2 Author: Keren Fuentes <dkeren@seas.upenn.edu> Date: Thu Oct 31 15:24:23 2019 -0700 draft regression test * update name and remove some dependency code * baseline file changes * Refactored function
1 parent e63fa8f commit d9584cf

File tree

7 files changed

+147
-16
lines changed

7 files changed

+147
-16
lines changed

src/Microsoft.ML.Data/Scorers/BinaryClassifierScorer.cs

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,7 @@ private protected override void SaveAsOnnxCore(OnnxContext ctx)
184184
{
185185
Host.CheckValue(ctx, nameof(ctx));
186186
Host.Assert(Bindable is IBindableCanSaveOnnx);
187+
Host.Assert(Bindings.InfoCount >= 2);
187188

188189
if (!ctx.ContainsColumn(DefaultColumnNames.Features))
189190
return;
@@ -197,15 +198,28 @@ private protected override void SaveAsOnnxCore(OnnxContext ctx)
197198
for (int iinfo = 0; iinfo < Bindings.InfoCount; ++iinfo)
198199
outColumnNames[iinfo] = Bindings.GetColumnName(Bindings.MapIinfoToCol(iinfo));
199200

200-
//Check if "Probability" column was generated by the base class, only then
201-
//label can be predicted.
202-
if (Bindings.InfoCount >= 3 && ctx.ContainsColumn(outColumnNames[2]))
201+
/* If the probability column was generated, then the classification threshold is set to 0.5. Otherwise,
202+
the predicted label is based on the sign of the score.
203+
*/
204+
string opType = "Binarizer";
205+
OnnxNode node;
206+
var binarizerOutput = ctx.AddIntermediateVariable(null, "BinarizerOutput", true);
207+
208+
if (Bindings.InfoCount >= 3)
203209
{
204-
string opType = "Binarizer";
205-
var node = ctx.CreateNode(opType, new[] { ctx.GetVariableName(outColumnNames[2]) },
206-
new[] { ctx.GetVariableName(outColumnNames[0]) }, ctx.GetNodeName(opType));
210+
Host.Assert(ctx.ContainsColumn(outColumnNames[2]));
211+
node = ctx.CreateNode(opType, ctx.GetVariableName(outColumnNames[2]), binarizerOutput, ctx.GetNodeName(opType));
207212
node.AddAttribute("threshold", 0.5);
208213
}
214+
else
215+
{
216+
node = ctx.CreateNode(opType, ctx.GetVariableName(outColumnNames[1]), binarizerOutput, ctx.GetNodeName(opType));
217+
node.AddAttribute("threshold", 0.0);
218+
}
219+
opType = "Cast";
220+
node = ctx.CreateNode(opType, binarizerOutput, ctx.GetVariableName(outColumnNames[0]), ctx.GetNodeName(opType), "");
221+
var t = InternalDataKindExtensions.ToInternalDataKind(DataKind.Boolean).ToType();
222+
node.AddAttribute("to", t);
209223
}
210224

211225
private protected override IDataTransform ApplyToDataCore(IHostEnvironment env, IDataView newSource)

src/Microsoft.ML.FastTree/FastTree.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3049,6 +3049,7 @@ private enum AggregateFunction
30493049
private protected virtual bool SaveAsOnnx(OnnxContext ctx, string[] outputNames, string featureColumn)
30503050
{
30513051
Host.CheckValue(ctx, nameof(ctx));
3052+
Host.Check(Utils.Size(outputNames) >= 1);
30523053

30533054
//Nodes.
30543055
var nodesTreeids = new List<long>();
@@ -3111,7 +3112,8 @@ private protected virtual bool SaveAsOnnx(OnnxContext ctx, string[] outputNames,
31113112
}
31123113

31133114
string opType = "TreeEnsembleRegressor";
3114-
var node = ctx.CreateNode(opType, new[] { featureColumn }, outputNames, ctx.GetNodeName(opType));
3115+
string scoreVarName = (Utils.Size(outputNames) == 2) ? outputNames[1] : outputNames[0]; // Get Score from PredictedLabel and/or Score columns
3116+
var node = ctx.CreateNode(opType, new[] { featureColumn }, new[] { scoreVarName }, ctx.GetNodeName(opType));
31153117

31163118
node.AddAttribute("post_transform", PostTransform.None.GetDescription());
31173119
node.AddAttribute("n_targets", 1);

src/Microsoft.ML.StandardTrainers/Standard/LinearModelParameters.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,9 +136,10 @@ internal LinearModelParameters(IHostEnvironment env, string name, in VBuffer<flo
136136
private protected virtual bool SaveAsOnnx(OnnxContext ctx, string[] outputs, string featureColumn)
137137
{
138138
Host.CheckValue(ctx, nameof(ctx));
139-
Host.Check(Utils.Size(outputs) == 1);
139+
Host.Check(Utils.Size(outputs) >= 1);
140140
string opType = "LinearRegressor";
141-
var node = ctx.CreateNode(opType, new[] { featureColumn }, outputs, ctx.GetNodeName(opType));
141+
string scoreVarName = (Utils.Size(outputs) == 2) ? outputs[1] : outputs[0]; // Get Score from PredictedLabel and/or Score columns
142+
var node = ctx.CreateNode(opType, new[] { featureColumn }, new[] { scoreVarName }, ctx.GetNodeName(opType));
142143
// Selection of logit or probit output transform. enum {'NONE', 'LOGIT', 'PROBIT}
143144
node.AddAttribute("post_transform", "NONE");
144145
node.AddAttribute("targets", 1);

test/BaselineOutput/Common/Onnx/BinaryClassification/BreastCancer/ExcludeVariablesInOnnxConversion.txt

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -416,7 +416,7 @@
416416
"Probability"
417417
],
418418
"output": [
419-
"PredictedLabel"
419+
"BinarizerOutput"
420420
],
421421
"name": "Binarizer",
422422
"opType": "Binarizer",
@@ -429,6 +429,23 @@
429429
],
430430
"domain": "ai.onnx.ml"
431431
},
432+
{
433+
"input": [
434+
"BinarizerOutput"
435+
],
436+
"output": [
437+
"PredictedLabel"
438+
],
439+
"name": "Cast1",
440+
"opType": "Cast",
441+
"attribute": [
442+
{
443+
"name": "to",
444+
"i": "9",
445+
"type": "INT"
446+
}
447+
]
448+
},
432449
{
433450
"input": [
434451
"PredictedLabel"

test/BaselineOutput/Common/Onnx/BinaryClassification/BreastCancer/ModelWithLessIO.txt

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -742,7 +742,7 @@
742742
"Probability"
743743
],
744744
"output": [
745-
"PredictedLabel"
745+
"BinarizerOutput"
746746
],
747747
"name": "Binarizer",
748748
"opType": "Binarizer",
@@ -755,6 +755,23 @@
755755
],
756756
"domain": "ai.onnx.ml"
757757
},
758+
{
759+
"input": [
760+
"BinarizerOutput"
761+
],
762+
"output": [
763+
"PredictedLabel"
764+
],
765+
"name": "Cast1",
766+
"opType": "Cast",
767+
"attribute": [
768+
{
769+
"name": "to",
770+
"i": "9",
771+
"type": "INT"
772+
}
773+
]
774+
},
758775
{
759776
"input": [
760777
"PredictedLabel"

test/BaselineOutput/Common/Onnx/BinaryClassification/BreastCancer/OneHotBagPipeline.txt

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -369,7 +369,7 @@
369369
"Probability"
370370
],
371371
"output": [
372-
"PredictedLabel"
372+
"BinarizerOutput"
373373
],
374374
"name": "Binarizer",
375375
"opType": "Binarizer",
@@ -382,6 +382,23 @@
382382
],
383383
"domain": "ai.onnx.ml"
384384
},
385+
{
386+
"input": [
387+
"BinarizerOutput"
388+
],
389+
"output": [
390+
"PredictedLabel"
391+
],
392+
"name": "Cast1",
393+
"opType": "Cast",
394+
"attribute": [
395+
{
396+
"name": "to",
397+
"i": "9",
398+
"type": "INT"
399+
}
400+
]
401+
},
385402
{
386403
"input": [
387404
"Label"

test/Microsoft.ML.Tests/OnnxConversionTest.cs

Lines changed: 67 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,15 @@ private class BreastCancerMulticlassExample
134134
public float[] Features;
135135
}
136136

137+
private class BreastCancerBinaryClassification
138+
{
139+
[LoadColumn(0)]
140+
public bool Label;
141+
142+
[LoadColumn(2, 9), VectorType(8)]
143+
public float[] Features;
144+
}
145+
137146
[LessThanNetCore30OrNotNetCoreFact("netcoreapp3.0 output differs from Baseline. Tracked by https://github.com/dotnet/machinelearning/issues/2087")]
138147
public void KmeansOnnxConversionTest()
139148
{
@@ -202,14 +211,15 @@ public void RegressionTrainersOnnxConversionTest()
202211
List<IEstimator<ITransformer>> estimators = new List<IEstimator<ITransformer>>()
203212
{
204213
mlContext.Regression.Trainers.Sdca("Target","FeatureVector"),
205-
mlContext.Regression.Trainers.Ols("Target","FeatureVector"),
214+
mlContext.Regression.Trainers.Ols("Target","FeatureVector"),
206215
mlContext.Regression.Trainers.OnlineGradientDescent("Target","FeatureVector"),
207216
mlContext.Regression.Trainers.FastForest("Target", "FeatureVector"),
208217
mlContext.Regression.Trainers.FastTree("Target", "FeatureVector"),
209218
mlContext.Regression.Trainers.FastTreeTweedie("Target", "FeatureVector"),
210219
mlContext.Regression.Trainers.LbfgsPoissonRegression("Target", "FeatureVector"),
211220
};
212-
if (Environment.Is64BitProcess) {
221+
if (Environment.Is64BitProcess)
222+
{
213223
estimators.Add(mlContext.Regression.Trainers.LightGbm("Target", "FeatureVector"));
214224
}
215225
foreach (var estimator in estimators)
@@ -232,7 +242,7 @@ public void RegressionTrainersOnnxConversionTest()
232242
CompareSelectedR4ScalarColumns(transformedData.Schema[2].Name, outputNames[2], transformedData, onnxResult, 3); // compare score results
233243
}
234244
// Compare the Onnx graph to a baseline if OnnxRuntime is not supported
235-
else
245+
else
236246
{
237247
var onnxFileName = $"{estimator.ToString()}.txt";
238248
var subDir = Path.Combine("..", "..", "BaselineOutput", "Common", "Onnx", "Regression", "Adult");
@@ -244,6 +254,58 @@ public void RegressionTrainersOnnxConversionTest()
244254
Done();
245255
}
246256

257+
[Fact]
258+
public void BinaryClassificationTrainersOnnxConversionTest()
259+
{
260+
var mlContext = new MLContext(seed: 1);
261+
string dataPath = GetDataPath("breast-cancer.txt");
262+
// Now read the file (remember though, readers are lazy, so the actual reading will happen when the data is accessed).
263+
var dataView = mlContext.Data.LoadFromTextFile<BreastCancerBinaryClassification>(dataPath, separatorChar: '\t', hasHeader: true);
264+
List<IEstimator<ITransformer>> estimators = new List<IEstimator<ITransformer>>()
265+
{
266+
mlContext.BinaryClassification.Trainers.AveragedPerceptron(),
267+
mlContext.BinaryClassification.Trainers.FastForest(),
268+
mlContext.BinaryClassification.Trainers.FastTree(),
269+
mlContext.BinaryClassification.Trainers.LbfgsLogisticRegression(),
270+
mlContext.BinaryClassification.Trainers.LinearSvm(),
271+
mlContext.BinaryClassification.Trainers.SdcaLogisticRegression(),
272+
mlContext.BinaryClassification.Trainers.SdcaNonCalibrated(),
273+
mlContext.BinaryClassification.Trainers.SgdCalibrated(),
274+
mlContext.BinaryClassification.Trainers.SgdNonCalibrated(),
275+
mlContext.BinaryClassification.Trainers.SymbolicSgdLogisticRegression(),
276+
};
277+
if (Environment.Is64BitProcess)
278+
{
279+
estimators.Add(mlContext.BinaryClassification.Trainers.LightGbm());
280+
}
281+
282+
var initialPipeline = mlContext.Transforms.ReplaceMissingValues("Features").
283+
Append(mlContext.Transforms.NormalizeMinMax("Features"));
284+
foreach (var estimator in estimators)
285+
{
286+
var pipeline = initialPipeline.Append(estimator);
287+
var model = pipeline.Fit(dataView);
288+
var transformedData = model.Transform(dataView);
289+
var onnxModel = mlContext.Model.ConvertToOnnxProtobuf(model, dataView);
290+
// Compare model scores produced by ML.NET and ONNX's runtime.
291+
if (IsOnnxRuntimeSupported())
292+
{
293+
var onnxFileName = $"{estimator.ToString()}.onnx";
294+
var onnxModelPath = GetOutputPath(onnxFileName);
295+
SaveOnnxModel(onnxModel, onnxModelPath, null);
296+
// Evaluate the saved ONNX model using the data used to train the ML.NET pipeline.
297+
string[] inputNames = onnxModel.Graph.Input.Select(valueInfoProto => valueInfoProto.Name).ToArray();
298+
string[] outputNames = onnxModel.Graph.Output.Select(valueInfoProto => valueInfoProto.Name).ToArray();
299+
var onnxEstimator = mlContext.Transforms.ApplyOnnxModel(outputNames, inputNames, onnxModelPath);
300+
var onnxTransformer = onnxEstimator.Fit(dataView);
301+
var onnxResult = onnxTransformer.Transform(dataView);
302+
CompareSelectedR4ScalarColumns(transformedData.Schema[5].Name, outputNames[3], transformedData, onnxResult, 3);
303+
CompareSelectedScalarColumns<Boolean>(transformedData.Schema[4].Name, outputNames[2], transformedData, onnxResult);
304+
}
305+
}
306+
Done();
307+
}
308+
247309
private class DataPoint
248310
{
249311
[VectorType(3)]
@@ -1225,7 +1287,8 @@ private void CreateDummyExamplesToMakeComplierHappy()
12251287
var dummyExample = new BreastCancerFeatureVector() { Features = null };
12261288
var dummyExample1 = new BreastCancerCatFeatureExample() { Label = false, F1 = 0, F2 = "Amy" };
12271289
var dummyExample2 = new BreastCancerMulticlassExample() { Label = "Amy", Features = null };
1228-
var dummyExample3 = new SmallSentimentExample() { Tokens = null };
1290+
var dummyExample3 = new BreastCancerBinaryClassification() { Label = false, Features = null };
1291+
var dummyExample4 = new SmallSentimentExample() { Tokens = null };
12291292
}
12301293

12311294
private void CompareResults(string leftColumnName, string rightColumnName, IDataView left, IDataView right)

0 commit comments

Comments
 (0)