-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Add entrypoint for PFI #4232
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Add entrypoint for PFI #4232
Changes from 2 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
811a3b5
Add entrypoint for PFI
najeeb-kazmi a31efed
Regenerate EP catalog
najeeb-kazmi 35fdaa8
Add tests
najeeb-kazmi 72991f3
Adding Standard Error of Mean to PFI Metrics in EntryPoint
najeeb-kazmi 163292d
PR Feedback
najeeb-kazmi ad491ea
Remove MLContext from EntryPoint
najeeb-kazmi 626914c
Use last predictor in the model if model.LastTransformer is not a pre…
najeeb-kazmi c726e21
nit
najeeb-kazmi 54e51b1
Model file path conflicts in tests
najeeb-kazmi d9f522f
nit
najeeb-kazmi ab0893b
PR Feedback
najeeb-kazmi 32eec60
Pass in model as PredictorModel
najeeb-kazmi de67439
Remove label column and group ID column from entrypoint input arguments
najeeb-kazmi 7f729f1
nit
najeeb-kazmi 3211365
Simplify data prep
najeeb-kazmi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
342 changes: 342 additions & 0 deletions
342
src/Microsoft.ML.EntryPoints/PermutationFeatureImportance.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,342 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using Microsoft.ML; | ||
| using Microsoft.ML.CommandLine; | ||
| using Microsoft.ML.Data; | ||
| using Microsoft.ML.EntryPoints; | ||
| using Microsoft.ML.Runtime; | ||
| using Microsoft.ML.Transforms; | ||
|
|
||
| [assembly: LoadableClass(typeof(void), typeof(PermutationFeatureImportanceEntryPoints), null, typeof(SignatureEntryPointModule), "PermutationFeatureImportance")] | ||
|
|
||
| namespace Microsoft.ML.Transforms | ||
| { | ||
| internal static class PermutationFeatureImportanceEntryPoints | ||
| { | ||
| [TlcModule.EntryPoint(Name = "Transforms.PermutationFeatureImportance", Desc = "Permutation Feature Importance (PFI)", UserName = "PFI", ShortName = "PFI")] | ||
| public static PermutationFeatureImportanceOutput PermutationFeatureImportance(IHostEnvironment env, PermutationFeatureImportanceArguments input) | ||
| { | ||
| Contracts.CheckValue(env, nameof(env)); | ||
| var host = env.Register("Pfi"); | ||
| host.CheckValue(input, nameof(input)); | ||
| EntryPointUtils.CheckInputArgs(host, input); | ||
|
|
||
| var mlContext = new MLContext(); | ||
|
najeeb-kazmi marked this conversation as resolved.
Outdated
|
||
|
|
||
| var model = mlContext.Model.Load(input.ModelPath.OpenReadStream(), out DataViewSchema schema); | ||
| var chain = model as TransformerChain<ITransformer>; | ||
| var predictor = chain.LastTransformer as ISingleFeaturePredictionTransformer<object>; | ||
|
najeeb-kazmi marked this conversation as resolved.
Outdated
|
||
|
|
||
| var transformedData = model.Transform(input.Data); | ||
|
|
||
| IDataView result = PermutationFeatureImportanceUtils.GetMetrics(mlContext, predictor, transformedData, input); | ||
|
|
||
| return new PermutationFeatureImportanceOutput { Metrics = result }; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Awesome change! #Resolved |
||
| } | ||
| } | ||
|
|
||
| internal sealed class PermutationFeatureImportanceOutput | ||
| { | ||
| [TlcModule.Output(Desc = "The PFI metrics")] | ||
| public IDataView Metrics; | ||
| } | ||
|
|
||
| internal sealed class PermutationFeatureImportanceArguments : TransformInputBase | ||
| { | ||
| [Argument(ArgumentType.Required, HelpText = "The path to the model file", ShortName = "path", Visibility = ArgumentAttribute.VisibilityType.EntryPointsOnly)] | ||
| public IFileHandle ModelPath; | ||
|
najeeb-kazmi marked this conversation as resolved.
Outdated
|
||
|
|
||
| [Argument(ArgumentType.AtMostOnce, HelpText = "Label column name", ShortName = "label", Visibility = ArgumentAttribute.VisibilityType.EntryPointsOnly)] | ||
| public string LabelColumnName = "Label"; | ||
|
|
||
| [Argument(ArgumentType.AtMostOnce, HelpText = "Group ID column", ShortName = "groupId", Visibility = ArgumentAttribute.VisibilityType.EntryPointsOnly)] | ||
| public string RowGroupColumnName = "GroupId"; | ||
|
|
||
| [Argument(ArgumentType.AtMostOnce, HelpText = "Use feature weights to pre-filter features", ShortName = "usefw", Visibility = ArgumentAttribute.VisibilityType.EntryPointsOnly)] | ||
| public bool UseFeatureWeightFilter = false; | ||
|
|
||
| [Argument(ArgumentType.AtMostOnce, HelpText = "Limit the number of examples to evaluate on", ShortName = "numexamples", Visibility = ArgumentAttribute.VisibilityType.EntryPointsOnly)] | ||
| public int? NumberOfExamplesToUse = null; | ||
|
|
||
| [Argument(ArgumentType.AtMostOnce, HelpText = "The number of permutations to perform", ShortName = "permutations", Visibility = ArgumentAttribute.VisibilityType.EntryPointsOnly)] | ||
| public int PermutationCount = 1; | ||
| } | ||
|
|
||
| internal static class PermutationFeatureImportanceUtils | ||
| { | ||
| private static string[] GetSlotNames(IDataView data) | ||
| { | ||
| VBuffer<ReadOnlyMemory<char>> slots = default; | ||
| data.Schema["Features"].GetSlotNames(ref slots); | ||
|
|
||
| var column = data.GetColumn<VBuffer<float>>( | ||
| data.Schema["Features"]); | ||
|
|
||
| List<string> slotNames = new List<string>(); | ||
|
|
||
| foreach (var item in column.First<VBuffer<float>>().Items(all: true)) | ||
| { | ||
| slotNames.Add(slots.GetValues()[item.Key].ToString()); | ||
| }; | ||
|
|
||
| return slotNames.ToArray(); | ||
| } | ||
|
|
||
| internal static IDataView GetMetrics( | ||
| MLContext mlContext, | ||
| ISingleFeaturePredictionTransformer<object> predictor, | ||
| IDataView data, | ||
| PermutationFeatureImportanceArguments input) | ||
| { | ||
| IDataView result; | ||
| if (predictor is BinaryPredictionTransformer<IPredictorProducing<float>>) | ||
| result = GetBinaryMetrics(mlContext, predictor, data, input); | ||
| else if (predictor is MulticlassPredictionTransformer<IPredictorProducing<VBuffer<float>>>) | ||
| result = GetMulticlassMetrics(mlContext, predictor, data, input); | ||
| else if (predictor is RegressionPredictionTransformer<IPredictorProducing<float>>) | ||
| result = GetRegressionMetrics(mlContext, predictor, data, input); | ||
| else if (predictor is RankingPredictionTransformer<IPredictorProducing<float>>) | ||
| result = GetRankingMetrics(mlContext, predictor, data, input); | ||
| else | ||
| throw Contracts.Except( | ||
| "Unsupported predictor type. Predictor must be binary classifier," + | ||
| "multiclass classifier, regressor, or ranker."); | ||
|
|
||
| return result; | ||
| } | ||
|
|
||
| private static IDataView GetBinaryMetrics( | ||
| MLContext mlContext, | ||
| ISingleFeaturePredictionTransformer<object> predictor, | ||
| IDataView data, | ||
| PermutationFeatureImportanceArguments input) | ||
| { | ||
| var slotNames = GetSlotNames(data); | ||
|
|
||
| var permutationMetrics = mlContext.BinaryClassification | ||
| .PermutationFeatureImportance(predictor, | ||
| data, | ||
| labelColumnName: input.LabelColumnName, | ||
| useFeatureWeightFilter: input.UseFeatureWeightFilter, | ||
| numberOfExamplesToUse: input.NumberOfExamplesToUse, | ||
| permutationCount: input.PermutationCount); | ||
|
|
||
| Contracts.Assert(slotNames.Length == permutationMetrics.Length, | ||
| "Mismatch between number of feature slots and number of features permuted."); | ||
|
|
||
| IEnumerable<BinaryMetrics> metrics = Enumerable.Empty<BinaryMetrics>(); | ||
| for (int i = 0; i < permutationMetrics.Length; i++) | ||
| { | ||
| var pMetric = permutationMetrics[i]; | ||
| metrics = metrics.Append(new BinaryMetrics | ||
| { | ||
| FeatureName = slotNames[i], | ||
| AreaUnderRocCurve = pMetric.AreaUnderRocCurve.Mean, | ||
| Accuracy = pMetric.Accuracy.Mean, | ||
| PositivePrecision = pMetric.PositivePrecision.Mean, | ||
| PositiveRecall = pMetric.PositiveRecall.Mean, | ||
| NegativePrecision = pMetric.NegativePrecision.Mean, | ||
| NegativeRecall = pMetric.NegativeRecall.Mean, | ||
| F1Score = pMetric.F1Score.Mean, | ||
| AreaUnderPrecisionRecallCurve = pMetric.AreaUnderPrecisionRecallCurve.Mean | ||
| }); | ||
| } | ||
|
|
||
| var result = mlContext.Data.LoadFromEnumerable(metrics); | ||
| return result; | ||
| } | ||
|
|
||
| private static IDataView GetMulticlassMetrics( | ||
| MLContext mlContext, | ||
| ISingleFeaturePredictionTransformer<object> predictor, | ||
| IDataView data, | ||
| PermutationFeatureImportanceArguments input) | ||
| { | ||
| var slotNames = GetSlotNames(data); | ||
|
|
||
| var permutationMetrics = mlContext.MulticlassClassification | ||
| .PermutationFeatureImportance(predictor, | ||
| data, | ||
| labelColumnName: input.LabelColumnName, | ||
| useFeatureWeightFilter: input.UseFeatureWeightFilter, | ||
| numberOfExamplesToUse: input.NumberOfExamplesToUse, | ||
| permutationCount: input.PermutationCount); | ||
|
|
||
| Contracts.Assert(slotNames.Length == permutationMetrics.Length, | ||
| "Mismatch between number of feature slots and number of features permuted."); | ||
|
|
||
| IEnumerable<MulticlassMetrics> metrics = Enumerable.Empty<MulticlassMetrics>(); | ||
|
najeeb-kazmi marked this conversation as resolved.
Outdated
|
||
| for (int i = 0; i < permutationMetrics.Length; i++) | ||
| { | ||
| var pMetric = permutationMetrics[i]; | ||
| metrics = metrics.Append(new MulticlassMetrics | ||
| { | ||
| FeatureName = slotNames[i], | ||
| MacroAccuracy = pMetric.MacroAccuracy.Mean, | ||
| MicroAccuracy = pMetric.MicroAccuracy.Mean, | ||
| LogLoss = pMetric.LogLoss.Mean, | ||
| LogLossReduction = pMetric.LogLossReduction.Mean, | ||
| TopKAccuracy = pMetric.TopKAccuracy.Mean, | ||
| PerClassLogLoss = pMetric.PerClassLogLoss.Select(x => x.Mean).ToArray() | ||
| }); ; | ||
| } | ||
|
|
||
| // Convert unknown size vectors to known size. | ||
| var metric = metrics.First(); | ||
| int perClassLogLossDimension = metric.PerClassLogLoss.Length; | ||
| SchemaDefinition schema = SchemaDefinition.Create(typeof(MulticlassMetrics)); | ||
| var perClassLogLossType = ((VectorDataViewType)schema[nameof(metric.PerClassLogLoss)].ColumnType).ItemType; | ||
| schema[nameof(metric.PerClassLogLoss)].ColumnType = new VectorDataViewType(perClassLogLossType, perClassLogLossDimension); | ||
|
|
||
| var result = mlContext.Data.LoadFromEnumerable(metrics, schema); | ||
| return result; | ||
| } | ||
|
|
||
| private static IDataView GetRegressionMetrics( | ||
| MLContext mlContext, | ||
| ISingleFeaturePredictionTransformer<object> predictor, | ||
| IDataView data, | ||
| PermutationFeatureImportanceArguments input) | ||
| { | ||
| var slotNames = GetSlotNames(data); | ||
|
|
||
| var permutationMetrics = mlContext.Regression | ||
| .PermutationFeatureImportance(predictor, | ||
| data, | ||
| labelColumnName: input.LabelColumnName, | ||
| useFeatureWeightFilter: input.UseFeatureWeightFilter, | ||
| numberOfExamplesToUse: input.NumberOfExamplesToUse, | ||
| permutationCount: input.PermutationCount); | ||
|
|
||
| Contracts.Assert(slotNames.Length == permutationMetrics.Length, | ||
| "Mismatch between number of feature slots and number of features permuted."); | ||
|
|
||
| IEnumerable<RegressionMetrics> metrics = Enumerable.Empty<RegressionMetrics>(); | ||
| for (int i = 0; i < permutationMetrics.Length; i++) | ||
| { | ||
| var pMetric = permutationMetrics[i]; | ||
| metrics = metrics.Append(new RegressionMetrics | ||
| { | ||
| FeatureName = slotNames[i], | ||
| MeanAbsoluteError = pMetric.MeanAbsoluteError.Mean, | ||
| MeanSquaredError = pMetric.MeanSquaredError.Mean, | ||
| RootMeanSquaredError = pMetric.RootMeanSquaredError.Mean, | ||
| LossFunction = pMetric.LossFunction.Mean, | ||
| RSquared = pMetric.RSquared.Mean | ||
| }); | ||
| } | ||
|
|
||
| var result = mlContext.Data.LoadFromEnumerable(metrics); | ||
| return result; | ||
| } | ||
|
|
||
| private static IDataView GetRankingMetrics( | ||
| MLContext mlContext, | ||
| ISingleFeaturePredictionTransformer<object> predictor, | ||
| IDataView data, | ||
| PermutationFeatureImportanceArguments input) | ||
| { | ||
| var slotNames = GetSlotNames(data); | ||
|
|
||
| var permutationMetrics = mlContext.Ranking | ||
| .PermutationFeatureImportance(predictor, | ||
| data, | ||
| labelColumnName: input.LabelColumnName, | ||
| rowGroupColumnName: input.RowGroupColumnName, | ||
| useFeatureWeightFilter: input.UseFeatureWeightFilter, | ||
| numberOfExamplesToUse: input.NumberOfExamplesToUse, | ||
| permutationCount: input.PermutationCount); | ||
|
|
||
| Contracts.Assert(slotNames.Length == permutationMetrics.Length, | ||
| "Mismatch between number of feature slots and number of features permuted."); | ||
|
|
||
| IEnumerable<RankingMetrics> metrics = Enumerable.Empty<RankingMetrics>(); | ||
| for (int i = 0; i < permutationMetrics.Length; i++) | ||
| { | ||
| var pMetric = permutationMetrics[i]; | ||
| metrics = metrics.Append(new RankingMetrics | ||
| { | ||
| FeatureName = slotNames[i], | ||
| DiscountedCumulativeGains = pMetric.DiscountedCumulativeGains.Select(x => x.Mean).ToArray(), | ||
| NormalizedDiscountedCumulativeGains = pMetric.NormalizedDiscountedCumulativeGains.Select(x => x.Mean).ToArray() | ||
| }); | ||
| } | ||
|
|
||
| // Convert unknown size vectors to known size. | ||
| var metric = metrics.First(); | ||
| int dcgDimension = metric.DiscountedCumulativeGains.Length; | ||
| int ndcgDimension = metric.NormalizedDiscountedCumulativeGains.Length; | ||
| SchemaDefinition schema = SchemaDefinition.Create(typeof(RankingMetrics)); | ||
| var dcgType = ((VectorDataViewType)schema[nameof(metric.DiscountedCumulativeGains)].ColumnType).ItemType; | ||
| var ndcgType = ((VectorDataViewType)schema[nameof(metric.NormalizedDiscountedCumulativeGains)].ColumnType).ItemType; | ||
| schema[nameof(metric.DiscountedCumulativeGains)].ColumnType = new VectorDataViewType(dcgType, dcgDimension); | ||
| schema[nameof(metric.NormalizedDiscountedCumulativeGains)].ColumnType = new VectorDataViewType(ndcgType, ndcgDimension); | ||
|
|
||
| var result = mlContext.Data.LoadFromEnumerable(metrics, schema); | ||
| return result; | ||
| } | ||
| } | ||
|
|
||
| internal class BinaryMetrics | ||
| { | ||
| public string FeatureName { get; set; } | ||
|
|
||
| public double AreaUnderRocCurve { get; set; } | ||
|
|
||
| public double Accuracy { get; set; } | ||
|
|
||
| public double PositivePrecision { get; set; } | ||
|
|
||
| public double PositiveRecall { get; set; } | ||
|
|
||
| public double NegativePrecision { get; set; } | ||
|
|
||
| public double NegativeRecall { get; set; } | ||
|
|
||
| public double F1Score { get; set; } | ||
|
|
||
| public double AreaUnderPrecisionRecallCurve { get; set; } | ||
| } | ||
|
|
||
| internal class MulticlassMetrics | ||
|
najeeb-kazmi marked this conversation as resolved.
Outdated
|
||
| { | ||
| public string FeatureName { get; set; } | ||
|
|
||
| public double MacroAccuracy { get; set; } | ||
|
|
||
| public double MicroAccuracy { get; set; } | ||
|
|
||
| public double LogLoss { get; set; } | ||
|
|
||
| public double LogLossReduction { get; set; } | ||
|
|
||
| public double TopKAccuracy { get; set; } | ||
|
|
||
| public double[] PerClassLogLoss { get; set; } | ||
| } | ||
|
|
||
| internal class RegressionMetrics | ||
| { | ||
| public string FeatureName { get; set; } | ||
|
|
||
| public double MeanAbsoluteError { get; set; } | ||
|
|
||
| public double MeanSquaredError { get; set; } | ||
|
|
||
| public double RootMeanSquaredError { get; set; } | ||
|
|
||
| public double LossFunction { get; set; } | ||
|
|
||
| public double RSquared { get; set; } | ||
| } | ||
|
|
||
| internal class RankingMetrics | ||
| { | ||
| public string FeatureName { get; set; } | ||
|
|
||
| public double[] DiscountedCumulativeGains { get; set; } | ||
|
|
||
| public double[] NormalizedDiscountedCumulativeGains { get; set; } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.