machinelearning icon indicating copy to clipboard operation
machinelearning copied to clipboard

PermutationFeatureImportance on Categorical Features dataset

Open Vijay27anand opened this issue 7 years ago • 8 comments

@caesar1995 @rogancarr @asthana86

I need an example how to use PermutationFeatureImportance on Categorical Feature dataset with MulticlassClassification. I need to understand the output score of each categorical feature columns to understand most important columns for a label column using PermutationFeatureImportance. Can you please provide me one, i am struggling to make it work.

Vijay27anand avatar Feb 18 '19 12:02 Vijay27anand

Hi @Vijay27anand ! This is a very good question. PermutationFeatureImportance operates on feature vectors, not on raw columnar datasets, so it requires a bit of hands-on work to look at categorical features.

To get a sense for feature importance of categorical features, you'll need to look at the parts of the feature vector that encode for those categorical features. For example, if you do a simple one-hot encoding, then a categorical feature with four categories will create four slots in the feature vector, e.g. 1 0 0 0, 0 1 0 0, 0 0 1 0, 0 0 0 1. Hashing will do a very similar thing [1]. If you can work through your data and identify which slots of the feature vector your categorical sits in, then you can get your feature importance by summing the importance of those slots (because the importance of your categorical is the combination of the importance of all those slots).

[1] In ML.NET, there is an option to "save" the input => output mapping which will allow you to work backwards from slot to categorical value.

rogancarr avatar Feb 19 '19 18:02 rogancarr

@rogancarr Thanks for the information, can you explain more on option to "save" the input => output mapping, is there any sample or documentation how to do that so i can refer to that.

Vijay27anand avatar Feb 20 '19 09:02 Vijay27anand

@Vijay27anand Let me give you some more details.

The feature vectors we create have metadata associated with them, so you can annotate individual feature entries (called "slots"). Our hash transforms have the option to put the hashed values as the names of the hashed vector slots. There is an option Invert Hash that accepts an integer. This limits the number of values that can be hashed into a particular bin, and puts those values in the slot metadata. If you used an InvertHash value of 2, you might see slot metadata like this: Slot 0: {'truck'}, Slot 1: {'dog', 'apple'}, etc.

Using this metadata, you can track backwards through the hash transform to see the values that generated the count.

Unfortunately, we don't have any samples available for this yet — these are coming, though!

rogancarr avatar Feb 20 '19 16:02 rogancarr

@rogancarr I tried to do a sample with your suggestions with OneHotEncoding & OneHotHashEncoding.

When i use simple with OneHotEncoding, i get 76 slots and 82 PermutationMetrics. With OneHotHashEncoding, I get 71 slots like "{3:Exec-managerial,2:Widowed}" and 262 permutationMetrics.
So now how do i map these Permutation metrics score with the slots in both the encoding to derive the feature importance of the categorical columns, can you help. Attaching the code/dataset below for both the encoding.

Attaching the code and the dataset, can you please help. adult.tiny.with-schema.txt

            string dataPath = "C:\\ML.NET\\test\\data\\adult.tiny.with-schema.txt";
            var mlContext = new MLContext();

        // Define the reader: specify the data columns and where to find them in the text file.
        var reader = mlContext.Data.CreateTextLoader(new[]
            {
                new TextLoader.Column("Label", DataKind.BL, 0),
                // We will load all the categorical features into one vector column of size 8.
                new TextLoader.Column("CategoricalFeatures", DataKind.TX, 1, 8),
                // Similarly, load all numerical features into one vector of size 6.
                new TextLoader.Column("NumericalFeatures", DataKind.R4, 9, 14)
              
            },
            hasHeader: true
        );

        // Read the data.
        var data = reader.Read(dataPath);

         //OneHotEncoding sample
          var pipeline = mlContext.Transforms.Categorical.OneHotEncoding("CategoricalBag", 
         "CategoricalFeatures", OneHotEncodingTransformer.OutputKind.Bag);

          //OneHotHashEncoding sample
         //    var pipeline = mlContext.Transforms.Categorical.OneHotHashEncoding("CategoricalBag", 
         "CategoricalFeatures", 8, 2, OneHotEncodingTransformer.OutputKind.Bag);

        // Let's train our pipeline, and then apply it to the same data.
        var transformedData = pipeline.Fit(data).Transform(data);

        var fullLearningPipeline = pipeline
            // Concatenate two of the categorical pipelines, and the numeric features.
            .Append(mlContext.Transforms.Concatenate("Features", "NumericalFeatures", "CategoricalBag"))
            // Now we're ready to train. We chose our FastTree trainer for this classification task.
            .Append(mlContext.BinaryClassification.Trainers.LogisticRegression(
                    labelColumn: "Label", featureColumn: "Features"));

        // Train the model.
        var model = fullLearningPipeline.Fit(data);

        var linearPredictor = model.LastTransformer;

        var transformedDataOut = model.Transform(data);

        //Permutation Accuracy metrics
        var permutationMetrics = mlContext.BinaryClassification.PermutationFeatureImportance(
            linearPredictor, transformedDataOut, label: "Label", features: "Features", permutationCount: 3);

        
        VBuffer<ReadOnlyMemory<char>> slotNames = new VBuffer<ReadOnlyMemory<char>>();
        transformedDataOut.Schema["CategoricalBag"].Metadata.GetValue(MetadataUtils.Kinds.SlotNames, ref slotNames);

        //output slots
        var slots = slotNames.GetValues();

Vijay27anand avatar Feb 22 '19 12:02 Vijay27anand

Hi @Vijay27anand ! Apologies for the delay — this issue got lost in the shuffle.

The issue here is that OneHotEncoding creates a dense vector, while OneHotHashEncoding creates a sparse vector.

When you call slotNames.GetValues() on a slotNames created by OneHotEncoding, you are doing so on a dense vector, so you get the full length of the vector back. When you do so on a slotNames created by OneHotHashEncoding, you are doing so on sparse vector, so the VBuffer will only return those that have been defined.

Now, to get around this, you can do a check for density

bool isDense = slotNames.IsDense();

And if you have a sparse vector, in addition to GetValues, you can also get the indices. This will let you page through the slotNames and know which slot they belong to.

var values = slotNames.GetValues();
var indices = slotNames.GetIndices();

And for a sanity check, you can also get the length of the (sparse) vector:

var numberOfCategoricalFeatures = slotNames.Length;

rogancarr avatar Mar 01 '19 20:03 rogancarr

Now, for how to map these back to the original values.

Your one-hot hash encoding is creating a slot named {3:Exec-managerial,2:Widowed}. This means that the counts in this hash bin are created from the (zero-based) third slot in the CategoricalFeatures vector ("Occupation") and from the second slot in the CaterogicalFeatures vector (MaritalStatus).

rogancarr avatar Mar 01 '19 20:03 rogancarr

Oh, one last comment — I was confused about invertHash. Set it to -1 to make sure all the unique values end up being added to the slot name. A value of 2 means "Only use the first 2 values seen in the slot name."

rogancarr avatar Mar 01 '19 23:03 rogancarr

This thread has been inactive, and I think we resolved the issue, so I'm going to close this now. Please reopen if you have more questions!

rogancarr avatar Apr 04 '19 01:04 rogancarr