-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
PermutationFeatureImportanceExtensions.cs
739 lines (686 loc) · 42.1 KB
/
PermutationFeatureImportanceExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using Microsoft.ML.Data;
using Microsoft.ML.Runtime;
using Microsoft.ML.Transforms;
namespace Microsoft.ML
{
/// <summary>
/// Collection of extension methods used by <see cref="RegressionCatalog"/>,
/// <see cref="BinaryClassificationCatalog"/>, <see cref="MulticlassClassificationCatalog"/>,
/// and <see cref="RankingCatalog"/> to create instances of permutation feature importance components.
/// </summary>
public static class PermutationFeatureImportanceExtensions
{
#region Regression
/// <summary>
/// Permutation Feature Importance (PFI) for Regression.
/// </summary>
/// <remarks>
/// <para>
/// Permutation feature importance (PFI) is a technique to determine the global importance of features in a trained
/// machine learning model. PFI is a simple yet powerful technique motivated by Breiman in his Random Forest paper, section 10
/// (Breiman. <a href='https://www.stat.berkeley.edu/~breiman/randomforest2001.pdf'>"Random Forests."</a> Machine Learning, 2001.)
/// The advantage of the PFI method is that it is model agnostic -- it works with any model that can be
/// evaluated -- and it can use any dataset, not just the training set, to compute feature importance metrics.
/// </para>
/// <para>
/// PFI works by taking a labeled dataset, choosing a feature, and permuting the values
/// for that feature across all the examples, so that each example now has a random value for the feature and
/// the original values for all other features. The evaluation metric (e.g. R-squared) is then calculated
/// for this modified dataset, and the change in the evaluation metric from the original dataset is computed.
/// The larger the change in the evaluation metric, the more important the feature is to the model.
/// PFI works by performing this permutation analysis across all the features of a model, one after another.
/// </para>
/// <para>
/// In this implementation, PFI computes the change in all possible regression evaluation metrics for each feature, and an
/// <see cref="ImmutableArray"/> of <see cref="RegressionMetrics"/> objects is returned. See the sample below for an
/// example of working with these results to analyze the feature importance of a model.
/// </para>
/// </remarks>
/// <example>
/// <format type="text/markdown">
/// <![CDATA[
/// [!code-csharp[PermutationFeatureImportance](~/../docs/samples/docs/samples/Microsoft.ML.Samples/Dynamic/Trainers/Regression/PermutationFeatureImportance.cs)]
/// ]]>
/// </format>
/// </example>
/// <param name="catalog">The regression catalog.</param>
/// <param name="predictionTransformer">The model on which to evaluate feature importance.</param>
/// <param name="data">The evaluation data set.</param>
/// <param name="labelColumnName">Label column name. The column data must be <see cref="System.Single"/>.</param>
/// <param name="useFeatureWeightFilter">Use features weight to pre-filter features.</param>
/// <param name="numberOfExamplesToUse">Limit the number of examples to evaluate on. <cref langword="null"/> means up to ~2 bln examples from <paramref param="data"/> will be used.</param>
/// <param name="permutationCount">The number of permutations to perform.</param>
/// <returns>Array of per-feature 'contributions' to the score.</returns>
public static ImmutableArray<RegressionMetricsStatistics>
PermutationFeatureImportance<TModel>(
this RegressionCatalog catalog,
ISingleFeaturePredictionTransformer<TModel> predictionTransformer,
IDataView data,
string labelColumnName = DefaultColumnNames.Label,
bool useFeatureWeightFilter = false,
int? numberOfExamplesToUse = null,
int permutationCount = 1) where TModel : class
{
return PermutationFeatureImportance<TModel, RegressionMetrics, RegressionMetricsStatistics>.GetImportanceMetricsMatrix(
catalog.GetEnvironment(),
predictionTransformer,
data,
() => new RegressionMetricsStatistics(),
idv => catalog.Evaluate(idv, labelColumnName),
RegressionDelta,
predictionTransformer.FeatureColumnName,
permutationCount,
useFeatureWeightFilter,
numberOfExamplesToUse);
}
/// <summary>
/// Permutation Feature Importance (PFI) for Regression.
/// </summary>
/// <remarks>
/// <para>
/// Permutation feature importance (PFI) is a technique to determine the global importance of features in a trained
/// machine learning model. PFI is a simple yet powerful technique motivated by Breiman in his Random Forest paper, section 10
/// (Breiman. <a href='https://www.stat.berkeley.edu/~breiman/randomforest2001.pdf'>"Random Forests."</a> Machine Learning, 2001.)
/// The advantage of the PFI method is that it is model agnostic -- it works with any model that can be
/// evaluated -- and it can use any dataset, not just the training set, to compute feature importance metrics.
/// </para>
/// <para>
/// PFI works by taking a labeled dataset, choosing a feature, and permuting the values
/// for that feature across all the examples, so that each example now has a random value for the feature and
/// the original values for all other features. The evaluation metric (e.g. R-squared) is then calculated
/// for this modified dataset, and the change in the evaluation metric from the original dataset is computed.
/// The larger the change in the evaluation metric, the more important the feature is to the model.
/// PFI works by performing this permutation analysis across all the features of a model, one after another.
/// </para>
/// <para>
/// In this implementation, PFI computes the change in all possible regression evaluation metrics for each feature, and an
/// <see cref="ImmutableArray"/> of <see cref="RegressionMetrics"/> objects is returned. See the sample below for an
/// example of working with these results to analyze the feature importance of a model.
/// </para>
/// </remarks>
/// <example>
/// <format type="text/markdown">
/// <![CDATA[
/// [!code-csharp[PermutationFeatureImportance](~/../docs/samples/docs/samples/Microsoft.ML.Samples/Dynamic/Trainers/Regression/PermutationFeatureImportance.cs)]
/// ]]>
/// </format>
/// </example>
/// <param name="catalog">The regression catalog.</param>
/// <param name="model">The model on which to evaluate feature importance.</param>
/// <param name="data">The evaluation data set.</param>
/// <param name="labelColumnName">Label column name. The column data must be <see cref="System.Single"/>.</param>
/// <param name="useFeatureWeightFilter">Use features weight to pre-filter features.</param>
/// <param name="numberOfExamplesToUse">Limit the number of examples to evaluate on. <cref langword="null"/> means up to ~2 bln examples from <paramref param="data"/> will be used.</param>
/// <param name="permutationCount">The number of permutations to perform.</param>
/// <returns>Dictionary mapping each feature to its per-feature 'contributions' to the score.</returns>
public static ImmutableDictionary<string, RegressionMetricsStatistics>
PermutationFeatureImportance(
this RegressionCatalog catalog,
ITransformer model,
IDataView data,
string labelColumnName = DefaultColumnNames.Label,
bool useFeatureWeightFilter = false,
int? numberOfExamplesToUse = null,
int permutationCount = 1)
{
Contracts.CheckValue(catalog, nameof(catalog));
var env = catalog.GetEnvironment();
Contracts.CheckValue(env, nameof(env));
env.CheckValue(data, nameof(data));
env.CheckValue(model, nameof(model));
RegressionMetricsStatistics resultInitializer() => new();
RegressionMetrics evaluationFunc(IDataView idv) => catalog.Evaluate(idv, labelColumnName);
return PermutationFeatureImportance(
env,
model,
data,
resultInitializer,
evaluationFunc,
RegressionDelta,
permutationCount,
useFeatureWeightFilter,
numberOfExamplesToUse
);
}
private static RegressionMetrics RegressionDelta(
RegressionMetrics a, RegressionMetrics b)
{
return new RegressionMetrics(
l1: a.MeanAbsoluteError - b.MeanAbsoluteError,
l2: a.MeanSquaredError - b.MeanSquaredError,
rms: a.RootMeanSquaredError - b.RootMeanSquaredError,
lossFunction: a.LossFunction - b.LossFunction,
rSquared: a.RSquared - b.RSquared);
}
#endregion
#region Binary Classification
/// <summary>
/// Permutation Feature Importance (PFI) for Binary Classification.
/// </summary>
/// <remarks>
/// <para>
/// Permutation feature importance (PFI) is a technique to determine the global importance of features in a trained
/// machine learning model. PFI is a simple yet powerful technique motivated by Breiman in his Random Forest paper, section 10
/// (Breiman. <a href='https://www.stat.berkeley.edu/~breiman/randomforest2001.pdf'>"Random Forests."</a> Machine Learning, 2001.)
/// The advantage of the PFI method is that it is model agnostic -- it works with any model that can be
/// evaluated -- and it can use any dataset, not just the training set, to compute feature importance metrics.
/// </para>
/// <para>
/// PFI works by taking a labeled dataset, choosing a feature, and permuting the values
/// for that feature across all the examples, so that each example now has a random value for the feature and
/// the original values for all other features. The evaluation metric (e.g. AUC) is then calculated
/// for this modified dataset, and the change in the evaluation metric from the original dataset is computed.
/// The larger the change in the evaluation metric, the more important the feature is to the model.
/// PFI works by performing this permutation analysis across all the features of a model, one after another.
/// </para>
/// <para>
/// In this implementation, PFI computes the change in all possible binary classification evaluation metrics for each feature, and an
/// <see cref="ImmutableArray"/> of <see cref="BinaryClassificationMetrics"/> objects is returned. See the sample below for an
/// example of working with these results to analyze the feature importance of a model.
/// </para>
/// </remarks>
/// <example>
/// <format type="text/markdown">
/// <![CDATA[
/// [!code-csharp[PermutationFeatureImportance](~/../docs/samples/docs/samples/Microsoft.ML.Samples/Dynamic/Trainers/BinaryClassification/PermutationFeatureImportance.cs)]
/// ]]>
/// </format>
/// </example>
/// <param name="catalog">The binary classification catalog.</param>
/// <param name="predictionTransformer">The model on which to evaluate feature importance.</param>
/// <param name="data">The evaluation data set.</param>
/// <param name="labelColumnName">Label column name. The column data must be <see cref="System.Boolean"/>.</param>
/// <param name="useFeatureWeightFilter">Use features weight to pre-filter features.</param>
/// <param name="numberOfExamplesToUse">Limit the number of examples to evaluate on. <cref langword="null"/> means up to ~2 bln examples from <paramref param="data"/> will be used.</param>
/// <param name="permutationCount">The number of permutations to perform.</param>
/// <returns>Array of per-feature 'contributions' to the score.</returns>
public static ImmutableArray<BinaryClassificationMetricsStatistics>
PermutationFeatureImportance<TModel>(
this BinaryClassificationCatalog catalog,
ISingleFeaturePredictionTransformer<TModel> predictionTransformer,
IDataView data,
string labelColumnName = DefaultColumnNames.Label,
bool useFeatureWeightFilter = false,
int? numberOfExamplesToUse = null,
int permutationCount = 1) where TModel : class
{
return PermutationFeatureImportance<TModel, BinaryClassificationMetrics, BinaryClassificationMetricsStatistics>.GetImportanceMetricsMatrix(
catalog.GetEnvironment(),
predictionTransformer,
data,
() => new BinaryClassificationMetricsStatistics(),
idv => catalog.EvaluateNonCalibrated(idv, labelColumnName),
BinaryClassifierDelta,
predictionTransformer.FeatureColumnName,
permutationCount,
useFeatureWeightFilter,
numberOfExamplesToUse);
}
/// <summary>
/// Permutation Feature Importance (PFI) for Binary Classification.
/// </summary>
/// <remarks>
/// <para>
/// Permutation feature importance (PFI) is a technique to determine the global importance of features in a trained
/// machine learning model. PFI is a simple yet powerful technique motivated by Breiman in his Random Forest paper, section 10
/// (Breiman. <a href='https://www.stat.berkeley.edu/~breiman/randomforest2001.pdf'>"Random Forests."</a> Machine Learning, 2001.)
/// The advantage of the PFI method is that it is model agnostic -- it works with any model that can be
/// evaluated -- and it can use any dataset, not just the training set, to compute feature importance metrics.
/// </para>
/// <para>
/// PFI works by taking a labeled dataset, choosing a feature, and permuting the values
/// for that feature across all the examples, so that each example now has a random value for the feature and
/// the original values for all other features. The evaluation metric (e.g. AUC) is then calculated
/// for this modified dataset, and the change in the evaluation metric from the original dataset is computed.
/// The larger the change in the evaluation metric, the more important the feature is to the model.
/// PFI works by performing this permutation analysis across all the features of a model, one after another.
/// </para>
/// <para>
/// In this implementation, PFI computes the change in all possible binary classification evaluation metrics for each feature, and an
/// <see cref="ImmutableArray"/> of <see cref="BinaryClassificationMetrics"/> objects is returned. See the sample below for an
/// example of working with these results to analyze the feature importance of a model.
/// </para>
/// </remarks>
/// <example>
/// <format type="text/markdown">
/// <![CDATA[
/// [!code-csharp[PermutationFeatureImportance](~/../docs/samples/docs/samples/Microsoft.ML.Samples/Dynamic/Trainers/BinaryClassification/PermutationFeatureImportance.cs)]
/// ]]>
/// </format>
/// </example>
/// <param name="catalog">The binary classification catalog.</param>
/// <param name="model">The model on which to evaluate feature importance.</param>
/// <param name="data">The evaluation data set.</param>
/// <param name="labelColumnName">Label column name. The column data must be <see cref="System.Boolean"/>.</param>
/// <param name="useFeatureWeightFilter">Use features weight to pre-filter features.</param>
/// <param name="numberOfExamplesToUse">Limit the number of examples to evaluate on. <cref langword="null"/> means up to ~2 bln examples from <paramref param="data"/> will be used.</param>
/// <param name="permutationCount">The number of permutations to perform.</param>
/// <returns>Dictionary mapping each feature to its per-feature 'contributions' to the score.</returns>
public static ImmutableDictionary<string, BinaryClassificationMetricsStatistics>
PermutationFeatureImportanceNonCalibrated(
this BinaryClassificationCatalog catalog,
ITransformer model,
IDataView data,
string labelColumnName = DefaultColumnNames.Label,
bool useFeatureWeightFilter = false,
int? numberOfExamplesToUse = null,
int permutationCount = 1)
{
Contracts.CheckValue(catalog, nameof(catalog));
var env = catalog.GetEnvironment();
Contracts.CheckValue(env, nameof(env));
env.CheckValue(data, nameof(data));
env.CheckValue(model, nameof(model));
BinaryClassificationMetricsStatistics resultInitializer() => new();
BinaryClassificationMetrics evaluationFunc(IDataView idv) => catalog.EvaluateNonCalibrated(idv, labelColumnName);
return PermutationFeatureImportance(
env,
model,
data,
resultInitializer,
evaluationFunc,
BinaryClassifierDelta,
permutationCount,
useFeatureWeightFilter,
numberOfExamplesToUse
);
}
private static BinaryClassificationMetrics BinaryClassifierDelta(
BinaryClassificationMetrics a, BinaryClassificationMetrics b)
{
return new BinaryClassificationMetrics(
auc: a.AreaUnderRocCurve - b.AreaUnderRocCurve,
accuracy: a.Accuracy - b.Accuracy,
positivePrecision: a.PositivePrecision - b.PositivePrecision,
positiveRecall: a.PositiveRecall - b.PositiveRecall,
negativePrecision: a.NegativePrecision - b.NegativePrecision,
negativeRecall: a.NegativeRecall - b.NegativeRecall,
f1Score: a.F1Score - b.F1Score,
auprc: a.AreaUnderPrecisionRecallCurve - b.AreaUnderPrecisionRecallCurve);
}
#endregion Binary Classification
#region Multiclass Classification
/// <summary>
/// Permutation Feature Importance (PFI) for MulticlassClassification.
/// </summary>
/// <remarks>
/// <para>
/// Permutation feature importance (PFI) is a technique to determine the global importance of features in a trained
/// machine learning model. PFI is a simple yet powerful technique motivated by Breiman in his Random Forest paper, section 10
/// (Breiman. <a href='https://www.stat.berkeley.edu/~breiman/randomforest2001.pdf'>"Random Forests."</a> Machine Learning, 2001.)
/// The advantage of the PFI method is that it is model agnostic -- it works with any model that can be
/// evaluated -- and it can use any dataset, not just the training set, to compute feature importance metrics.
/// </para>
/// <para>
/// PFI works by taking a labeled dataset, choosing a feature, and permuting the values
/// for that feature across all the examples, so that each example now has a random value for the feature and
/// the original values for all other features. The evaluation metric (e.g. micro-accuracy) is then calculated
/// for this modified dataset, and the change in the evaluation metric from the original dataset is computed.
/// The larger the change in the evaluation metric, the more important the feature is to the model.
/// PFI works by performing this permutation analysis across all the features of a model, one after another.
/// </para>
/// <para>
/// In this implementation, PFI computes the change in all possible multiclass classification evaluation metrics for each feature, and an
/// <see cref="ImmutableArray"/> of <see cref="MulticlassClassificationMetrics"/> objects is returned. See the sample below for an
/// example of working with these results to analyze the feature importance of a model.
/// </para>
/// </remarks>
/// <example>
/// <format type="text/markdown">
/// <![CDATA[
/// [!code-csharp[PermutationFeatureImportance](~/../docs/samples/docs/samples/Microsoft.ML.Samples/Dynamic/Trainers/MulticlassClassification/PermutationFeatureImportance.cs)]
/// ]]>
/// </format>
/// </example>
/// <param name="catalog">The multiclass classification catalog.</param>
/// <param name="predictionTransformer">The model on which to evaluate feature importance.</param>
/// <param name="data">The evaluation data set.</param>
/// <param name="labelColumnName">Label column name. The column data must be <see cref="KeyDataViewType"/>.</param>
/// <param name="useFeatureWeightFilter">Use features weight to pre-filter features.</param>
/// <param name="numberOfExamplesToUse">Limit the number of examples to evaluate on. <cref langword="null"/> means up to ~2 bln examples from <paramref param="data"/> will be used.</param>
/// <param name="permutationCount">The number of permutations to perform.</param>
/// <returns>Array of per-feature 'contributions' to the score.</returns>
public static ImmutableArray<MulticlassClassificationMetricsStatistics>
PermutationFeatureImportance<TModel>(
this MulticlassClassificationCatalog catalog,
ISingleFeaturePredictionTransformer<TModel> predictionTransformer,
IDataView data,
string labelColumnName = DefaultColumnNames.Label,
bool useFeatureWeightFilter = false,
int? numberOfExamplesToUse = null,
int permutationCount = 1) where TModel : class
{
return PermutationFeatureImportance<TModel, MulticlassClassificationMetrics, MulticlassClassificationMetricsStatistics>.GetImportanceMetricsMatrix(
catalog.GetEnvironment(),
predictionTransformer,
data,
() => new MulticlassClassificationMetricsStatistics(),
idv => catalog.Evaluate(idv, labelColumnName),
MulticlassClassificationDelta,
predictionTransformer.FeatureColumnName,
permutationCount,
useFeatureWeightFilter,
numberOfExamplesToUse);
}
/// <summary>
/// Permutation Feature Importance (PFI) for MulticlassClassification.
/// </summary>
/// <remarks>
/// <para>
/// Permutation feature importance (PFI) is a technique to determine the global importance of features in a trained
/// machine learning model. PFI is a simple yet powerful technique motivated by Breiman in his Random Forest paper, section 10
/// (Breiman. <a href='https://www.stat.berkeley.edu/~breiman/randomforest2001.pdf'>"Random Forests."</a> Machine Learning, 2001.)
/// The advantage of the PFI method is that it is model agnostic -- it works with any model that can be
/// evaluated -- and it can use any dataset, not just the training set, to compute feature importance metrics.
/// </para>
/// <para>
/// PFI works by taking a labeled dataset, choosing a feature, and permuting the values
/// for that feature across all the examples, so that each example now has a random value for the feature and
/// the original values for all other features. The evaluation metric (e.g. micro-accuracy) is then calculated
/// for this modified dataset, and the change in the evaluation metric from the original dataset is computed.
/// The larger the change in the evaluation metric, the more important the feature is to the model.
/// PFI works by performing this permutation analysis across all the features of a model, one after another.
/// </para>
/// <para>
/// In this implementation, PFI computes the change in all possible multiclass classification evaluation metrics for each feature, and an
/// <see cref="ImmutableArray"/> of <see cref="MulticlassClassificationMetrics"/> objects is returned. See the sample below for an
/// example of working with these results to analyze the feature importance of a model.
/// </para>
/// </remarks>
/// <example>
/// <format type="text/markdown">
/// <![CDATA[
/// [!code-csharp[PermutationFeatureImportance](~/../docs/samples/docs/samples/Microsoft.ML.Samples/Dynamic/Trainers/MulticlassClassification/PermutationFeatureImportance.cs)]
/// ]]>
/// </format>
/// </example>
/// <param name="catalog">The multiclass classification catalog.</param>
/// <param name="model">The model on which to evaluate feature importance.</param>
/// <param name="data">The evaluation data set.</param>
/// <param name="labelColumnName">Label column name. The column data must be <see cref="KeyDataViewType"/>.</param>
/// <param name="useFeatureWeightFilter">Use features weight to pre-filter features.</param>
/// <param name="numberOfExamplesToUse">Limit the number of examples to evaluate on. <cref langword="null"/> means up to ~2 bln examples from <paramref param="data"/> will be used.</param>
/// <param name="permutationCount">The number of permutations to perform.</param>
/// <returns>Dictionary mapping each feature to its per-feature 'contributions' to the score.</returns>
public static ImmutableDictionary<string, MulticlassClassificationMetricsStatistics>
PermutationFeatureImportance(
this MulticlassClassificationCatalog catalog,
ITransformer model,
IDataView data,
string labelColumnName = DefaultColumnNames.Label,
bool useFeatureWeightFilter = false,
int? numberOfExamplesToUse = null,
int permutationCount = 1)
{
Contracts.CheckValue(catalog, nameof(catalog));
var env = catalog.GetEnvironment();
Contracts.CheckValue(env, nameof(env));
env.CheckValue(data, nameof(data));
env.CheckValue(model, nameof(model));
MulticlassClassificationMetricsStatistics resultInitializer() => new();
MulticlassClassificationMetrics evaluationFunc(IDataView idv) => catalog.Evaluate(idv, labelColumnName);
return PermutationFeatureImportance(
env,
model,
data,
resultInitializer,
evaluationFunc,
MulticlassClassificationDelta,
permutationCount,
useFeatureWeightFilter,
numberOfExamplesToUse
);
}
private static MulticlassClassificationMetrics MulticlassClassificationDelta(
MulticlassClassificationMetrics a, MulticlassClassificationMetrics b)
{
if (a.TopKPredictionCount != b.TopKPredictionCount)
Contracts.Assert(a.TopKPredictionCount == b.TopKPredictionCount, "TopK to compare must be the same length.");
var perClassLogLoss = ComputeSequenceDeltas(a.PerClassLogLoss, b.PerClassLogLoss);
return new MulticlassClassificationMetrics(
accuracyMicro: a.MicroAccuracy - b.MicroAccuracy,
accuracyMacro: a.MacroAccuracy - b.MacroAccuracy,
logLoss: a.LogLoss - b.LogLoss,
logLossReduction: a.LogLossReduction - b.LogLossReduction,
topKPredictionCount: a.TopKPredictionCount,
topKAccuracies: a?.TopKAccuracyForAllK?.Zip(b.TopKAccuracyForAllK, (a, b) => a - b)?.ToArray(),
perClassLogLoss: perClassLogLoss
);
}
#endregion
#region Ranking
/// <summary>
/// Permutation Feature Importance (PFI) for Ranking.
/// </summary>
/// <remarks>
/// <para>
/// Permutation feature importance (PFI) is a technique to determine the global importance of features in a trained
/// machine learning model. PFI is a simple yet powerful technique motivated by Breiman in his Random Forest paper, section 10
/// (Breiman. <a href='https://www.stat.berkeley.edu/~breiman/randomforest2001.pdf'>"Random Forests."</a> Machine Learning, 2001.)
/// The advantage of the PFI method is that it is model agnostic -- it works with any model that can be
/// evaluated -- and it can use any dataset, not just the training set, to compute feature importance metrics.
/// </para>
/// <para>
/// PFI works by taking a labeled dataset, choosing a feature, and permuting the values
/// for that feature across all the examples, so that each example now has a random value for the feature and
/// the original values for all other features. The evaluation metric (e.g. NDCG) is then calculated
/// for this modified dataset, and the change in the evaluation metric from the original dataset is computed.
/// The larger the change in the evaluation metric, the more important the feature is to the model.
/// PFI works by performing this permutation analysis across all the features of a model, one after another.
/// </para>
/// <para>
/// In this implementation, PFI computes the change in all possible ranking evaluation metrics for each feature, and an
/// <see cref="ImmutableArray"/> of <see cref="RankingMetrics"/> objects is returned. See the sample below for an
/// example of working with these results to analyze the feature importance of a model.
/// </para>
/// </remarks>
/// <example>
/// <format type="text/markdown">
/// <![CDATA[
/// [!code-csharp[PermutationFeatureImportance](~/../docs/samples/docs/samples/Microsoft.ML.Samples/Dynamic/Trainers/Ranking/PermutationFeatureImportance.cs)]
/// ]]>
/// </format>
/// </example>
/// <param name="catalog">The ranking catalog.</param>
/// <param name="predictionTransformer">The model on which to evaluate feature importance.</param>
/// <param name="data">The evaluation data set.</param>
/// <param name="labelColumnName">Label column name. The column data must be <see cref="System.Single"/> or <see cref="KeyDataViewType"/>.</param>
/// <param name="rowGroupColumnName">GroupId column name</param>
/// <param name="useFeatureWeightFilter">Use features weight to pre-filter features.</param>
/// <param name="numberOfExamplesToUse">Limit the number of examples to evaluate on. <cref langword="null"/> means up to ~2 bln examples from <paramref param="data"/> will be used.</param>
/// <param name="permutationCount">The number of permutations to perform.</param>
/// <returns>Array of per-feature 'contributions' to the score.</returns>
public static ImmutableArray<RankingMetricsStatistics>
PermutationFeatureImportance<TModel>(
this RankingCatalog catalog,
ISingleFeaturePredictionTransformer<TModel> predictionTransformer,
IDataView data,
string labelColumnName = DefaultColumnNames.Label,
string rowGroupColumnName = DefaultColumnNames.GroupId,
bool useFeatureWeightFilter = false,
int? numberOfExamplesToUse = null,
int permutationCount = 1) where TModel : class
{
return PermutationFeatureImportance<TModel, RankingMetrics, RankingMetricsStatistics>.GetImportanceMetricsMatrix(
catalog.GetEnvironment(),
predictionTransformer,
data,
() => new RankingMetricsStatistics(),
idv => catalog.Evaluate(idv, labelColumnName, rowGroupColumnName),
RankingDelta,
predictionTransformer.FeatureColumnName,
permutationCount,
useFeatureWeightFilter,
numberOfExamplesToUse);
}
/// <summary>
/// Permutation Feature Importance (PFI) for Ranking.
/// </summary>
/// <remarks>
/// <para>
/// Permutation feature importance (PFI) is a technique to determine the global importance of features in a trained
/// machine learning model. PFI is a simple yet powerful technique motivated by Breiman in his Random Forest paper, section 10
/// (Breiman. <a href='https://www.stat.berkeley.edu/~breiman/randomforest2001.pdf'>"Random Forests."</a> Machine Learning, 2001.)
/// The advantage of the PFI method is that it is model agnostic -- it works with any model that can be
/// evaluated -- and it can use any dataset, not just the training set, to compute feature importance metrics.
/// </para>
/// <para>
/// PFI works by taking a labeled dataset, choosing a feature, and permuting the values
/// for that feature across all the examples, so that each example now has a random value for the feature and
/// the original values for all other features. The evaluation metric (e.g. NDCG) is then calculated
/// for this modified dataset, and the change in the evaluation metric from the original dataset is computed.
/// The larger the change in the evaluation metric, the more important the feature is to the model.
/// PFI works by performing this permutation analysis across all the features of a model, one after another.
/// </para>
/// <para>
/// In this implementation, PFI computes the change in all possible ranking evaluation metrics for each feature, and an
/// <see cref="ImmutableArray"/> of <see cref="RankingMetrics"/> objects is returned. See the sample below for an
/// example of working with these results to analyze the feature importance of a model.
/// </para>
/// </remarks>
/// <example>
/// <format type="text/markdown">
/// <![CDATA[
/// [!code-csharp[PermutationFeatureImportance](~/../docs/samples/docs/samples/Microsoft.ML.Samples/Dynamic/Trainers/Ranking/PermutationFeatureImportance.cs)]
/// ]]>
/// </format>
/// </example>
/// <param name="catalog">The ranking catalog.</param>
/// <param name="model">The model on which to evaluate feature importance.</param>
/// <param name="data">The evaluation data set.</param>
/// <param name="labelColumnName">Label column name. The column data must be <see cref="System.Single"/> or <see cref="KeyDataViewType"/>.</param>
/// <param name="rowGroupColumnName">GroupId column name</param>
/// <param name="useFeatureWeightFilter">Use features weight to pre-filter features.</param>
/// <param name="numberOfExamplesToUse">Limit the number of examples to evaluate on. <cref langword="null"/> means up to ~2 bln examples from <paramref param="data"/> will be used.</param>
/// <param name="permutationCount">The number of permutations to perform.</param>
/// <returns>Dictionary mapping each feature to its per-feature 'contributions' to the score.</returns>
public static ImmutableDictionary<string, RankingMetricsStatistics>
PermutationFeatureImportance(
this RankingCatalog catalog,
ITransformer model,
IDataView data,
string labelColumnName = DefaultColumnNames.Label,
string rowGroupColumnName = DefaultColumnNames.GroupId,
bool useFeatureWeightFilter = false,
int? numberOfExamplesToUse = null,
int permutationCount = 1)
{
Contracts.CheckValue(catalog, nameof(catalog));
var env = catalog.GetEnvironment();
Contracts.CheckValue(env, nameof(env));
env.CheckValue(data, nameof(data));
env.CheckValue(model, nameof(model));
RankingMetricsStatistics resultInitializer() => new();
RankingMetrics evaluationFunc(IDataView idv) => catalog.Evaluate(idv, labelColumnName, rowGroupColumnName);
return PermutationFeatureImportance(
env,
model,
data,
resultInitializer,
evaluationFunc,
RankingDelta,
permutationCount,
useFeatureWeightFilter,
numberOfExamplesToUse
);
}
private static RankingMetrics RankingDelta(
RankingMetrics a, RankingMetrics b)
{
var dcg = ComputeSequenceDeltas(a.DiscountedCumulativeGains, b.DiscountedCumulativeGains);
var ndcg = ComputeSequenceDeltas(a.NormalizedDiscountedCumulativeGains, b.NormalizedDiscountedCumulativeGains);
return new RankingMetrics(dcg: dcg, ndcg: ndcg);
}
#endregion
#region Helpers
private static double[] ComputeSequenceDeltas(IReadOnlyList<double> a, IReadOnlyList<double> b)
{
Contracts.Assert(a.Count == b.Count);
var delta = new double[a.Count];
for (int i = 0; i < a.Count; i++)
delta[i] = a[i] - b[i];
return delta;
}
private static ImmutableDictionary<string, TResult>
PermutationFeatureImportance<TMetric, TResult>(
IHostEnvironment env,
ITransformer model,
IDataView data,
Func<TResult> resultInitializer,
Func<IDataView, TMetric> evaluationFunc,
Func<TMetric, TMetric, TMetric> deltaFunc,
int permutationCount,
bool useFeatureWeightFilter,
int? numberOfExamplesToUse) where TResult : IMetricsStatistics<TMetric>
{
env.CheckValue(data, nameof(data));
env.CheckValue(model, nameof(model));
ISingleFeaturePredictionTransformer lastTransformer = null;
if (model is TransformerChain<ITransformer> chain)
{
foreach (var transformer in chain.Reverse())
{
if (transformer is ISingleFeaturePredictionTransformer singlePredictionTransformer)
{
lastTransformer = singlePredictionTransformer;
break;
}
}
}
else lastTransformer = model as ISingleFeaturePredictionTransformer;
env.CheckValue(lastTransformer, nameof(lastTransformer), "The model provided does not have a compatible predictor");
string featureColumnName = lastTransformer.FeatureColumnName;
var predictionTransformerGenericType = GetImplementedIPredictionTransformer(lastTransformer.GetType());
Type[] types = { predictionTransformerGenericType.GenericTypeArguments[0], typeof(TMetric), typeof(TResult) };
Type pfiGenericType = typeof(PermutationFeatureImportance<,,>).MakeGenericType(types);
object[] param = { env,
lastTransformer,
data,
resultInitializer,
evaluationFunc,
deltaFunc,
featureColumnName,
permutationCount,
useFeatureWeightFilter,
numberOfExamplesToUse
};
MethodInfo mi = pfiGenericType.GetMethod("GetImportanceMetricsMatrix", BindingFlags.Static | BindingFlags.Public);
var permutationFeatureImportance = (ImmutableArray<TResult>)mi.Invoke(null, param);
VBuffer<ReadOnlyMemory<char>> nameBuffer = default;
data.Schema[featureColumnName].Annotations.GetValue("SlotNames", ref nameBuffer);
var featureColumnNames = nameBuffer.DenseValues().ToList();
var output = new Dictionary<string, TResult>();
for (int i = 0; i < permutationFeatureImportance.Length; i++)
{
var name = featureColumnNames[i].ToString();
// If the slot wasn't given a name, default to just the slot number.
if (string.IsNullOrEmpty(name))
{
name = $"Slot {i}";
}
output.Add(name, permutationFeatureImportance[i]);
}
return output.ToImmutableDictionary();
}
private static Type GetImplementedIPredictionTransformer(Type type)
{
foreach (Type iType in type.GetInterfaces())
{
if (iType.IsGenericType && iType.GetGenericTypeDefinition() == typeof(IPredictionTransformer<>))
{
return iType;
}
}
throw new ArgumentException($"Type IPredictionTransformer not implemented by provided type", nameof(type));
}
#endregion
}
}