PermutationFeatureImportanceExtensions.PermutationFeatureImportance 메서드

정의

오버로드

PermutationFeatureImportance(MulticlassClassificationCatalog, ITransformer, IDataView, String, Boolean, Nullable<Int32>, Int32)

MulticlassClassification에 대한 순열 기능 중요도(PFI)입니다.

PermutationFeatureImportance(RegressionCatalog, ITransformer, IDataView, String, Boolean, Nullable<Int32>, Int32)

회귀에 대한 순열 기능 중요도(PFI)입니다.

PermutationFeatureImportance(RankingCatalog, ITransformer, IDataView, String, String, Boolean, Nullable<Int32>, Int32)

순위에 대한 순열 기능 중요도(PFI)입니다.

PermutationFeatureImportance<TModel>(BinaryClassificationCatalog, ISingleFeaturePredictionTransformer<TModel>, IDataView, String, Boolean, Nullable<Int32>, Int32)

이진 분류에 대한 순열 기능 중요도(PFI)입니다.

PermutationFeatureImportance<TModel>(MulticlassClassificationCatalog, ISingleFeaturePredictionTransformer<TModel>, IDataView, String, Boolean, Nullable<Int32>, Int32)

MulticlassClassification에 대한 순열 기능 중요도(PFI)입니다.

PermutationFeatureImportance<TModel>(RegressionCatalog, ISingleFeaturePredictionTransformer<TModel>, IDataView, String, Boolean, Nullable<Int32>, Int32)

회귀에 대한 순열 기능 중요도(PFI)입니다.

PermutationFeatureImportance<TModel>(RankingCatalog, ISingleFeaturePredictionTransformer<TModel>, IDataView, String, String, Boolean, Nullable<Int32>, Int32)

순위에 대한 순열 기능 중요도(PFI)입니다.

PermutationFeatureImportance(MulticlassClassificationCatalog, ITransformer, IDataView, String, Boolean, Nullable<Int32>, Int32)

MulticlassClassification에 대한 순열 기능 중요도(PFI)입니다.

public static System.Collections.Immutable.ImmutableDictionary<string,Microsoft.ML.Data.MulticlassClassificationMetricsStatistics> PermutationFeatureImportance (this Microsoft.ML.MulticlassClassificationCatalog catalog, Microsoft.ML.ITransformer model, Microsoft.ML.IDataView data, string labelColumnName = "Label", bool useFeatureWeightFilter = false, int? numberOfExamplesToUse = default, int permutationCount = 1);
static member PermutationFeatureImportance : Microsoft.ML.MulticlassClassificationCatalog * Microsoft.ML.ITransformer * Microsoft.ML.IDataView * string * bool * Nullable<int> * int -> System.Collections.Immutable.ImmutableDictionary<string, Microsoft.ML.Data.MulticlassClassificationMetricsStatistics>
<Extension()>
Public Function PermutationFeatureImportance (catalog As MulticlassClassificationCatalog, model As ITransformer, data As IDataView, Optional labelColumnName As String = "Label", Optional useFeatureWeightFilter As Boolean = false, Optional numberOfExamplesToUse As Nullable(Of Integer) = Nothing, Optional permutationCount As Integer = 1) As ImmutableDictionary(Of String, MulticlassClassificationMetricsStatistics)

매개 변수

catalog
MulticlassClassificationCatalog

다중 클래스 분류 카탈로그입니다.

model
ITransformer

기능 중요도를 평가할 모델입니다.

data
IDataView

평가 데이터 집합입니다.

labelColumnName
String

레이블 열 이름입니다. 열 데이터는 이어야 KeyDataViewType합니다.

useFeatureWeightFilter
Boolean

기능 가중치를 사용하여 기능을 미리 필터링합니다.

numberOfExamplesToUse
Nullable<Int32>

평가할 예제 수를 제한합니다. 는 최대 2개의 Bln 예제가 사용됨을 의미합니다.

permutationCount
Int32

수행할 순열의 수입니다.

반환

각 기능을 기능별 '기여'에 점수에 매핑하는 사전입니다.

예제

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.ML;

namespace Samples.Dynamic.Trainers.MulticlassClassification
{
    public static class PermutationFeatureImportance
    {
        public static void Example()
        {
            // Create a new context for ML.NET operations. It can be used for
            // exception tracking and logging, as a catalog of available operations
            // and as the source of randomness.
            var mlContext = new MLContext(seed: 1);

            // Create sample data.
            var samples = GenerateData();

            // Load the sample data as an IDataView.
            var data = mlContext.Data.LoadFromEnumerable(samples);

            // Define a training pipeline that concatenates features into a vector,
            // normalizes them, and then trains a linear model.
            var featureColumns =
                new string[] { nameof(Data.Feature1), nameof(Data.Feature2) };

            var pipeline = mlContext.Transforms
                .Concatenate("Features", featureColumns)
                .Append(mlContext.Transforms.Conversion.MapValueToKey("Label"))
                .Append(mlContext.Transforms.NormalizeMinMax("Features"))
                .Append(mlContext.MulticlassClassification.Trainers
                .SdcaMaximumEntropy());

            // Fit the pipeline to the data.
            var model = pipeline.Fit(data);

            // Transform the dataset.
            var transformedData = model.Transform(data);

            // Extract the predictor.
            var linearPredictor = model.LastTransformer;

            // Compute the permutation metrics for the linear model using the
            // normalized data.
            var permutationMetrics = mlContext.MulticlassClassification
                .PermutationFeatureImportance(linearPredictor, transformedData,
                permutationCount: 30);

            // Now let's look at which features are most important to the model
            // overall. Get the feature indices sorted by their impact on
            // microaccuracy.
            var sortedIndices = permutationMetrics
                .Select((metrics, index) => new { index, metrics.MicroAccuracy })
                .OrderByDescending(feature => Math.Abs(feature.MicroAccuracy.Mean))
                .Select(feature => feature.index);

            Console.WriteLine("Feature\tChange in MicroAccuracy\t95% Confidence in "
                + "the Mean Change in MicroAccuracy");

            var microAccuracy = permutationMetrics.Select(x => x.MicroAccuracy)
                .ToArray();

            foreach (int i in sortedIndices)
            {
                Console.WriteLine("{0}\t{1:G4}\t{2:G4}",
                    featureColumns[i],
                    microAccuracy[i].Mean,
                    1.96 * microAccuracy[i].StandardError);
            }

            // Expected output:
            //Feature     Change in MicroAccuracy  95% Confidence in the Mean Change in MicroAccuracy
            //Feature2     -0.1395                 0.0006567
            //Feature1     -0.05367                0.0006908
        }

        private class Data
        {
            public float Label { get; set; }

            public float Feature1 { get; set; }

            public float Feature2 { get; set; }
        }

        /// <summary>
        /// Generate an enumerable of Data objects, creating the label as a simple
        /// linear combination of the features.
        /// </summary>
        /// <param name="nExamples">The number of examples.</param>
        /// <param name="bias">The bias, or offset, in the calculation of the
        /// label.</param>
        /// <param name="weight1">The weight to multiply the first feature with to
        /// compute the label.</param>
        /// <param name="weight2">The weight to multiply the second feature with to
        /// compute the label.</param>
        /// <param name="seed">The seed for generating feature values and label
        /// noise.</param>
        /// <returns>An enumerable of Data objects.</returns>
        private static IEnumerable<Data> GenerateData(int nExamples = 10000,
            double bias = 0, double weight1 = 1, double weight2 = 2, int seed = 1)
        {
            var rng = new Random(seed);
            var max = bias + 4.5 * weight1 + 4.5 * weight2 + 0.5;
            for (int i = 0; i < nExamples; i++)
            {
                var data = new Data
                {
                    Feature1 = (float)(rng.Next(10) * (rng.NextDouble() - 0.5)),
                    Feature2 = (float)(rng.Next(10) * (rng.NextDouble() - 0.5)),
                };

                // Create a noisy label.
                var value = (float)
                    (bias + weight1 * data.Feature1 + weight2 * data.Feature2 +
                    rng.NextDouble() - 0.5);

                if (value < max / 3)
                    data.Label = 0;
                else if (value < 2 * max / 3)
                    data.Label = 1;
                else
                    data.Label = 2;
                yield return data;
            }
        }
    }
}

설명

PFI(순열 기능 중요도)는 학습된 기계 학습 모델에서 기능의 전역 중요성을 결정하는 기술입니다. PFI는 Breiman이 랜덤 포레스트 논문 섹션 10(Breiman)에서 동기를 부여받은 단순하면서도 강력한 기술입니다. "임의 포리스트" Machine Learning, 2001.) PFI 메서드의 장점은 모델 중립적이라는 점입니다. 이는 평가할 수 있는 모든 모델에서 작동하며 학습 집합뿐만 아니라 모든 데이터 세트를 사용하여 기능 중요도 메트릭을 계산할 수 있다는 것입니다.

PFI는 레이블이 지정된 데이터 세트를 사용하고, 기능을 선택하고, 모든 예제에서 해당 기능의 값을 통근하여 작동하므로 각 예제는 이제 기능의 임의 값과 다른 모든 기능에 대한 원래 값을 갖습니다. 그런 다음, 이 수정된 데이터 세트에 대해 평가 메트릭(예: 마이크로 정확도)이 계산되고 원래 데이터 세트의 평가 메트릭 변경 내용이 계산됩니다. 평가 메트릭의 변경 내용이 클수록 모델에 대한 기능이 더 중요합니다. PFI는 모델의 모든 기능에서 이 순열 분석을 하나씩 수행하여 작동합니다.

이 구현에서 PFI는 각 기능에 대해 가능한 모든 다중 클래스 분류 평가 메트릭의 변경 사항을 계산하고 ImmutableArray 개체가 MulticlassClassificationMetrics 반환됩니다. 모델의 기능 중요성을 분석하기 위해 이러한 결과를 사용하는 예제는 아래 샘플을 참조하세요.

적용 대상

PermutationFeatureImportance(RegressionCatalog, ITransformer, IDataView, String, Boolean, Nullable<Int32>, Int32)

회귀에 대한 순열 기능 중요도(PFI)입니다.

public static System.Collections.Immutable.ImmutableDictionary<string,Microsoft.ML.Data.RegressionMetricsStatistics> PermutationFeatureImportance (this Microsoft.ML.RegressionCatalog catalog, Microsoft.ML.ITransformer model, Microsoft.ML.IDataView data, string labelColumnName = "Label", bool useFeatureWeightFilter = false, int? numberOfExamplesToUse = default, int permutationCount = 1);
static member PermutationFeatureImportance : Microsoft.ML.RegressionCatalog * Microsoft.ML.ITransformer * Microsoft.ML.IDataView * string * bool * Nullable<int> * int -> System.Collections.Immutable.ImmutableDictionary<string, Microsoft.ML.Data.RegressionMetricsStatistics>
<Extension()>
Public Function PermutationFeatureImportance (catalog As RegressionCatalog, model As ITransformer, data As IDataView, Optional labelColumnName As String = "Label", Optional useFeatureWeightFilter As Boolean = false, Optional numberOfExamplesToUse As Nullable(Of Integer) = Nothing, Optional permutationCount As Integer = 1) As ImmutableDictionary(Of String, RegressionMetricsStatistics)

매개 변수

catalog
RegressionCatalog

회귀 카탈로그입니다.

model
ITransformer

기능 중요도를 평가할 모델입니다.

data
IDataView

평가 데이터 집합입니다.

labelColumnName
String

레이블 열 이름입니다. 열 데이터는 이어야 Single합니다.

useFeatureWeightFilter
Boolean

기능 가중치를 사용하여 기능을 미리 필터링합니다.

numberOfExamplesToUse
Nullable<Int32>

평가할 예제 수를 제한합니다. 는 최대 2개의 Bln 예제가 사용됨을 의미합니다.

permutationCount
Int32

수행할 순열의 수입니다.

반환

각 기능을 기능별 '기여'에 점수에 매핑하는 사전입니다.

예제

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.ML;

namespace Samples.Dynamic.Trainers.Regression
{
    public static class PermutationFeatureImportance
    {
        public static void Example()
        {
            // Create a new context for ML.NET operations. It can be used for
            // exception tracking and logging, as a catalog of available operations
            // and as the source of randomness.
            var mlContext = new MLContext(seed: 1);

            // Create sample data.
            var samples = GenerateData();

            // Load the sample data as an IDataView.
            var data = mlContext.Data.LoadFromEnumerable(samples);

            // Define a training pipeline that concatenates features into a vector,
            // normalizes them, and then trains a linear model.
            var featureColumns = new string[] { nameof(Data.Feature1),
                nameof(Data.Feature2) };

            var pipeline = mlContext.Transforms.Concatenate(
                "Features",
                featureColumns)
                .Append(mlContext.Transforms.NormalizeMinMax("Features"))
                .Append(mlContext.Regression.Trainers.Ols());

            // Fit the pipeline to the data.
            var model = pipeline.Fit(data);

            // Transform the dataset.
            var transformedData = model.Transform(data);

            // Extract the predictor.
            var linearPredictor = model.LastTransformer;

            // Compute the permutation metrics for the linear model using the
            // normalized data.
            var permutationMetrics = mlContext.Regression
                .PermutationFeatureImportance(
                linearPredictor, transformedData, permutationCount: 30);

            // Now let's look at which features are most important to the model
            // overall. Get the feature indices sorted by their impact on RMSE.
            var sortedIndices = permutationMetrics
                .Select((metrics, index) => new
                {
                    index,
                    metrics.RootMeanSquaredError
                })

                .OrderByDescending(feature => Math.Abs(
                    feature.RootMeanSquaredError.Mean))

                .Select(feature => feature.index);

            Console.WriteLine("Feature\tModel Weight\tChange in RMSE\t95%" +
                "Confidence in the Mean Change in RMSE");

            var rmse = permutationMetrics.Select(x => x.RootMeanSquaredError)
                .ToArray();

            foreach (int i in sortedIndices)
            {
                Console.WriteLine("{0}\t{1:0.00}\t{2:G4}\t{3:G4}",
                    featureColumns[i],
                    linearPredictor.Model.Weights[i],
                    rmse[i].Mean,
                    1.96 * rmse[i].StandardError);
            }

            // Expected output:
            //  Feature    Model Weight Change in RMSE  95% Confidence in the Mean Change in RMSE
            //  Feature2        9.00        4.009       0.008304
            //  Feature1        4.48        1.901       0.003351
        }

        private class Data
        {
            public float Label { get; set; }

            public float Feature1 { get; set; }

            public float Feature2 { get; set; }
        }

        /// <summary>
        /// Generate an enumerable of Data objects, creating the label as a simple
        /// linear combination of the features.
        /// </summary>
        /// <param name="nExamples">The number of examples.</param>
        /// <param name="bias">The bias, or offset, in the calculation of the label.
        /// </param>
        /// <param name="weight1">The weight to multiply the first feature with to
        /// compute the label.</param>
        /// <param name="weight2">The weight to multiply the second feature with to
        /// compute the label.</param>
        /// <param name="seed">The seed for generating feature values and label
        /// noise.</param>
        /// <returns>An enumerable of Data objects.</returns>
        private static IEnumerable<Data> GenerateData(int nExamples = 10000,
            double bias = 0, double weight1 = 1, double weight2 = 2, int seed = 1)
        {
            var rng = new Random(seed);
            for (int i = 0; i < nExamples; i++)
            {
                var data = new Data
                {
                    Feature1 = (float)(rng.Next(10) * (rng.NextDouble() - 0.5)),
                    Feature2 = (float)(rng.Next(10) * (rng.NextDouble() - 0.5)),
                };

                // Create a noisy label.
                data.Label = (float)(bias + weight1 * data.Feature1 + weight2 *
                    data.Feature2 + rng.NextDouble() - 0.5);
                yield return data;
            }
        }
    }
}

설명

PFI(순열 기능 중요도)는 학습된 기계 학습 모델에서 기능의 전역 중요성을 결정하는 기술입니다. PFI는 Breiman이 랜덤 포레스트 논문 섹션 10(Breiman)에서 동기를 부여받은 단순하면서도 강력한 기술입니다. "임의 포리스트" Machine Learning, 2001.) PFI 메서드의 장점은 모델 중립적이라는 점입니다. 이는 평가할 수 있는 모든 모델에서 작동하며 학습 집합뿐만 아니라 모든 데이터 세트를 사용하여 기능 중요도 메트릭을 계산할 수 있다는 것입니다.

PFI는 레이블이 지정된 데이터 세트를 사용하고, 기능을 선택하고, 모든 예제에서 해당 기능의 값을 통근하여 작동하므로 각 예제는 이제 기능의 임의 값과 다른 모든 기능에 대한 원래 값을 갖습니다. 그런 다음, 이 수정된 데이터 세트에 대해 평가 메트릭(예: R 제곱)이 계산되고 원래 데이터 세트의 평가 메트릭 변경 내용이 계산됩니다. 평가 메트릭의 변경 내용이 클수록 모델에 대한 기능이 더 중요합니다. PFI는 모델의 모든 기능에서 이 순열 분석을 하나씩 수행하여 작동합니다.

이 구현에서 PFI는 각 기능에 대해 가능한 모든 회귀 평가 메트릭의 변경 사항을 계산하고 ImmutableArray 개체가 RegressionMetrics 반환됩니다. 모델의 기능 중요성을 분석하기 위해 이러한 결과를 사용하는 예제는 아래 샘플을 참조하세요.

적용 대상

PermutationFeatureImportance(RankingCatalog, ITransformer, IDataView, String, String, Boolean, Nullable<Int32>, Int32)

순위에 대한 순열 기능 중요도(PFI)입니다.

public static System.Collections.Immutable.ImmutableDictionary<string,Microsoft.ML.Data.RankingMetricsStatistics> PermutationFeatureImportance (this Microsoft.ML.RankingCatalog catalog, Microsoft.ML.ITransformer model, Microsoft.ML.IDataView data, string labelColumnName = "Label", string rowGroupColumnName = "GroupId", bool useFeatureWeightFilter = false, int? numberOfExamplesToUse = default, int permutationCount = 1);
static member PermutationFeatureImportance : Microsoft.ML.RankingCatalog * Microsoft.ML.ITransformer * Microsoft.ML.IDataView * string * string * bool * Nullable<int> * int -> System.Collections.Immutable.ImmutableDictionary<string, Microsoft.ML.Data.RankingMetricsStatistics>
<Extension()>
Public Function PermutationFeatureImportance (catalog As RankingCatalog, model As ITransformer, data As IDataView, Optional labelColumnName As String = "Label", Optional rowGroupColumnName As String = "GroupId", Optional useFeatureWeightFilter As Boolean = false, Optional numberOfExamplesToUse As Nullable(Of Integer) = Nothing, Optional permutationCount As Integer = 1) As ImmutableDictionary(Of String, RankingMetricsStatistics)

매개 변수

catalog
RankingCatalog

순위 카탈로그입니다.

model
ITransformer

기능 중요도를 평가할 모델입니다.

data
IDataView

평가 데이터 집합입니다.

labelColumnName
String

레이블 열 이름입니다. 열 데이터는 이어야 Single 합니다.KeyDataViewType

rowGroupColumnName
String

GroupId 열 이름

useFeatureWeightFilter
Boolean

기능 가중치를 사용하여 기능을 미리 필터링합니다.

numberOfExamplesToUse
Nullable<Int32>

평가할 예제 수를 제한합니다. 는 최대 2개의 Bln 예제가 사용됨을 의미합니다.

permutationCount
Int32

수행할 순열의 수입니다.

반환

각 기능을 기능별 '기여'에 점수에 매핑하는 사전입니다.

예제

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.ML;

namespace Samples.Dynamic.Trainers.Ranking
{
    public static class PermutationFeatureImportance
    {
        public static void Example()
        {
            // Create a new context for ML.NET operations. It can be used for
            // exception tracking and logging, as a catalog of available operations
            // and as the source of randomness.
            var mlContext = new MLContext(seed: 1);

            // Create sample data.
            var samples = GenerateData();

            // Load the sample data as an IDataView.
            var data = mlContext.Data.LoadFromEnumerable(samples);

            // Define a training pipeline that concatenates features into a vector,
            // normalizes them, and then trains a linear model.
            var featureColumns = new string[] { nameof(Data.Feature1), nameof(
                Data.Feature2) };
            var pipeline = mlContext.Transforms.Concatenate("Features",
                featureColumns)
                    .Append(mlContext.Transforms.Conversion.MapValueToKey("Label"))
                    .Append(mlContext.Transforms.Conversion.MapValueToKey(
                        "GroupId"))
                    .Append(mlContext.Transforms.NormalizeMinMax("Features"))
                    .Append(mlContext.Ranking.Trainers.FastTree());

            // Fit the pipeline to the data.
            var model = pipeline.Fit(data);

            // Transform the dataset.
            var transformedData = model.Transform(data);

            // Extract the predictor.
            var linearPredictor = model.LastTransformer;

            // Compute the permutation metrics for the linear model using the
            // normalized data.
            var permutationMetrics = mlContext.Ranking.PermutationFeatureImportance(
                linearPredictor, transformedData, permutationCount: 30);

            // Now let's look at which features are most important to the model
            // overall. Get the feature indices sorted by their impact on NDCG@1.
            var sortedIndices = permutationMetrics.Select((metrics, index) => new
            {
                index,
                metrics.NormalizedDiscountedCumulativeGains
            })
                .OrderByDescending(feature => Math.Abs(
                    feature.NormalizedDiscountedCumulativeGains[0].Mean))

                .Select(feature => feature.index);

            Console.WriteLine("Feature\tChange in NDCG@1\t95% Confidence in the" +
                "Mean Change in NDCG@1");
            var ndcg = permutationMetrics.Select(
                x => x.NormalizedDiscountedCumulativeGains).ToArray();
            foreach (int i in sortedIndices)
            {
                Console.WriteLine("{0}\t{1:G4}\t{2:G4}",
                    featureColumns[i],
                    ndcg[i][0].Mean,
                    1.96 * ndcg[i][0].StandardError);
            }

            // Expected output:
            //  Feature     Change in NDCG@1    95% Confidence in the Mean Change in NDCG@1
            //  Feature2     -0.2421            0.001748
            //  Feature1     -0.0513            0.001184
        }

        private class Data
        {
            public float Label { get; set; }

            public int GroupId { get; set; }

            public float Feature1 { get; set; }

            public float Feature2 { get; set; }
        }

        /// <summary>
        /// Generate an enumerable of Data objects, creating the label as a simple
        /// linear combination of the features.
        /// </summary>
        /// 
        /// <param name="nExamples">The number of examples.</param>
        /// 
        /// <param name="bias">The bias, or offset, in the calculation of the label.
        /// </param>
        /// 
        /// <param name="weight1">The weight to multiply the first feature with to
        /// compute the label.</param>
        /// 
        /// <param name="weight2">The weight to multiply the second feature with to
        /// compute the label.</param>
        /// 
        /// <param name="seed">The seed for generating feature values and label
        /// noise.</param>
        /// 
        /// <returns>An enumerable of Data objects.</returns>
        private static IEnumerable<Data> GenerateData(int nExamples = 10000,
            double bias = 0, double weight1 = 1, double weight2 = 2, int seed = 1,
                int groupSize = 5)
        {
            var rng = new Random(seed);
            var max = bias + 4.5 * weight1 + 4.5 * weight2 + 0.5;
            for (int i = 0; i < nExamples; i++)
            {
                var data = new Data
                {
                    GroupId = i / groupSize,
                    Feature1 = (float)(rng.Next(10) * (rng.NextDouble() - 0.5)),
                    Feature2 = (float)(rng.Next(10) * (rng.NextDouble() - 0.5)),
                };

                // Create a noisy label.
                var value = (float)(bias + weight1 * data.Feature1 + weight2 *
                    data.Feature2 + rng.NextDouble() - 0.5);
                if (value < max / 3)
                    data.Label = 0;
                else if (value < 2 * max / 3)
                    data.Label = 1;
                else
                    data.Label = 2;
                yield return data;
            }
        }
    }
}

설명

PFI(순열 기능 중요도)는 학습된 기계 학습 모델에서 기능의 전역 중요성을 결정하는 기술입니다. PFI는 Breiman이 랜덤 포레스트 논문 섹션 10(Breiman)에서 동기를 부여받은 단순하면서도 강력한 기술입니다. "임의 포리스트" Machine Learning, 2001.) PFI 메서드의 장점은 모델 중립적이라는 점입니다. 이는 평가할 수 있는 모든 모델에서 작동하며 학습 집합뿐만 아니라 모든 데이터 세트를 사용하여 기능 중요도 메트릭을 계산할 수 있다는 것입니다.

PFI는 레이블이 지정된 데이터 세트를 사용하고, 기능을 선택하고, 모든 예제에서 해당 기능의 값을 통근하여 작동하므로 각 예제는 이제 기능의 임의 값과 다른 모든 기능에 대한 원래 값을 갖습니다. 그런 다음, 이 수정된 데이터 세트에 대해 평가 메트릭(예: NDCG)이 계산되고 원래 데이터 세트의 평가 메트릭 변경 내용이 계산됩니다. 평가 메트릭의 변경 내용이 클수록 모델에 대한 기능이 더 중요합니다. PFI는 모델의 모든 기능에서 이 순열 분석을 하나씩 수행하여 작동합니다.

이 구현에서 PFI는 각 기능에 대해 가능한 모든 순위 평가 메트릭의 변경 사항을 계산하고 ImmutableArray 개체가 RankingMetrics 반환됩니다. 모델의 기능 중요성을 분석하기 위해 이러한 결과를 사용하는 예제는 아래 샘플을 참조하세요.

적용 대상

PermutationFeatureImportance<TModel>(BinaryClassificationCatalog, ISingleFeaturePredictionTransformer<TModel>, IDataView, String, Boolean, Nullable<Int32>, Int32)

이진 분류에 대한 순열 기능 중요도(PFI)입니다.

public static System.Collections.Immutable.ImmutableArray<Microsoft.ML.Data.BinaryClassificationMetricsStatistics> PermutationFeatureImportance<TModel> (this Microsoft.ML.BinaryClassificationCatalog catalog, Microsoft.ML.ISingleFeaturePredictionTransformer<TModel> predictionTransformer, Microsoft.ML.IDataView data, string labelColumnName = "Label", bool useFeatureWeightFilter = false, int? numberOfExamplesToUse = default, int permutationCount = 1) where TModel : class;
static member PermutationFeatureImportance : Microsoft.ML.BinaryClassificationCatalog * Microsoft.ML.ISingleFeaturePredictionTransformer<'Model (requires 'Model : null)> * Microsoft.ML.IDataView * string * bool * Nullable<int> * int -> System.Collections.Immutable.ImmutableArray<Microsoft.ML.Data.BinaryClassificationMetricsStatistics> (requires 'Model : null)
<Extension()>
Public Function PermutationFeatureImportance(Of TModel As Class) (catalog As BinaryClassificationCatalog, predictionTransformer As ISingleFeaturePredictionTransformer(Of TModel), data As IDataView, Optional labelColumnName As String = "Label", Optional useFeatureWeightFilter As Boolean = false, Optional numberOfExamplesToUse As Nullable(Of Integer) = Nothing, Optional permutationCount As Integer = 1) As ImmutableArray(Of BinaryClassificationMetricsStatistics)

형식 매개 변수

TModel

매개 변수

catalog
BinaryClassificationCatalog

이진 분류 카탈로그입니다.

predictionTransformer
ISingleFeaturePredictionTransformer<TModel>

기능 중요도를 평가할 모델입니다.

data
IDataView

평가 데이터 집합입니다.

labelColumnName
String

레이블 열 이름입니다. 열 데이터는 이어야 Boolean합니다.

useFeatureWeightFilter
Boolean

기능 가중치를 사용하여 기능을 미리 필터링합니다.

numberOfExamplesToUse
Nullable<Int32>

평가할 예제 수를 제한합니다. 는 최대 2개의 Bln 예제가 사용됨을 의미합니다.

permutationCount
Int32

수행할 순열의 수입니다.

반환

점수에 대한 기능별 '기여' 배열입니다.

예제

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.ML;

namespace Samples.Dynamic.Trainers.BinaryClassification
{
    public static class PermutationFeatureImportance
    {
        public static void Example()
        {
            // Create a new context for ML.NET operations. It can be used for
            // exception tracking and logging, as a catalog of available operations
            // and as the source of randomness.
            var mlContext = new MLContext(seed: 1);

            // Create sample data.
            var samples = GenerateData();

            // Load the sample data as an IDataView.
            var data = mlContext.Data.LoadFromEnumerable(samples);

            // Define a training pipeline that concatenates features into a vector,
            // normalizes them, and then trains a linear model.
            var featureColumns =
                new string[] { nameof(Data.Feature1), nameof(Data.Feature2) };
            var pipeline = mlContext.Transforms
                .Concatenate("Features", featureColumns)
                .Append(mlContext.Transforms.NormalizeMinMax("Features"))
                .Append(mlContext.BinaryClassification.Trainers
                .SdcaLogisticRegression());

            // Fit the pipeline to the data.
            var model = pipeline.Fit(data);

            // Transform the dataset.
            var transformedData = model.Transform(data);

            // Extract the predictor.
            var linearPredictor = model.LastTransformer;

            // Compute the permutation metrics for the linear model using the
            // normalized data.
            var permutationMetrics = mlContext.BinaryClassification
                .PermutationFeatureImportance(linearPredictor, transformedData,
                permutationCount: 30);

            // Now let's look at which features are most important to the model
            // overall. Get the feature indices sorted by their impact on AUC.
            var sortedIndices = permutationMetrics
                .Select((metrics, index) => new { index, metrics.AreaUnderRocCurve })
                .OrderByDescending(
                feature => Math.Abs(feature.AreaUnderRocCurve.Mean))
                .Select(feature => feature.index);

            Console.WriteLine("Feature\tModel Weight\tChange in AUC"
                + "\t95% Confidence in the Mean Change in AUC");
            var auc = permutationMetrics.Select(x => x.AreaUnderRocCurve).ToArray();
            foreach (int i in sortedIndices)
            {
                Console.WriteLine("{0}\t{1:0.00}\t{2:G4}\t{3:G4}",
                    featureColumns[i],
                    linearPredictor.Model.SubModel.Weights[i],
                    auc[i].Mean,
                    1.96 * auc[i].StandardError);
            }

            // Expected output:
            //  Feature     Model Weight Change in AUC  95% Confidence in the Mean Change in AUC
            //  Feature2        35.15     -0.387        0.002015
            //  Feature1        17.94     -0.1514       0.0008963
        }

        private class Data
        {
            public bool Label { get; set; }

            public float Feature1 { get; set; }

            public float Feature2 { get; set; }
        }

        /// <summary>
        /// Generate an enumerable of Data objects, creating the label as a simple
        /// linear combination of the features.
        /// </summary>
        /// <param name="nExamples">The number of examples.</param>
        /// <param name="bias">The bias, or offset, in the calculation of the label.
        /// </param>
        /// <param name="weight1">The weight to multiply the first feature with to
        /// compute the label.</param>
        /// <param name="weight2">The weight to multiply the second feature with to
        /// compute the label.</param>
        /// <param name="seed">The seed for generating feature values and label
        /// noise.</param>
        /// <returns>An enumerable of Data objects.</returns>
        private static IEnumerable<Data> GenerateData(int nExamples = 10000,
            double bias = 0, double weight1 = 1, double weight2 = 2, int seed = 1)
        {
            var rng = new Random(seed);
            for (int i = 0; i < nExamples; i++)
            {
                var data = new Data
                {
                    Feature1 = (float)(rng.Next(10) * (rng.NextDouble() - 0.5)),
                    Feature2 = (float)(rng.Next(10) * (rng.NextDouble() - 0.5)),
                };

                // Create a noisy label.
                var value = (float)(bias + weight1 * data.Feature1 + weight2 *
                    data.Feature2 + rng.NextDouble() - 0.5);

                data.Label = Sigmoid(value) > 0.5;
                yield return data;
            }
        }

        private static double Sigmoid(double x) => 1.0 / (1.0 + Math.Exp(-1 * x));
    }
}

설명

PFI(순열 기능 중요도)는 학습된 기계 학습 모델에서 기능의 전역 중요성을 결정하는 기술입니다. PFI는 Breiman이 랜덤 포레스트 논문 섹션 10(Breiman)에서 동기를 부여받은 단순하면서도 강력한 기술입니다. "임의 포리스트" Machine Learning, 2001.) PFI 메서드의 장점은 모델 중립적이라는 점입니다. 이는 평가할 수 있는 모든 모델에서 작동하며 학습 집합뿐만 아니라 모든 데이터 세트를 사용하여 기능 중요도 메트릭을 계산할 수 있다는 것입니다.

PFI는 레이블이 지정된 데이터 세트를 사용하고, 기능을 선택하고, 모든 예제에서 해당 기능의 값을 통근하여 작동하므로 각 예제는 이제 기능의 임의 값과 다른 모든 기능에 대한 원래 값을 갖습니다. 그런 다음, 이 수정된 데이터 세트에 대해 평가 메트릭(예: AUC)이 계산되고 원래 데이터 세트의 평가 메트릭 변경 내용이 계산됩니다. 평가 메트릭의 변경 내용이 클수록 모델에 대한 기능이 더 중요합니다. PFI는 모델의 모든 기능에서 이 순열 분석을 하나씩 수행하여 작동합니다.

이 구현에서 PFI는 각 기능에 대해 가능한 모든 이진 분류 평가 메트릭의 변경 사항을 계산하고 ImmutableArray 개체가 BinaryClassificationMetrics 반환됩니다. 모델의 기능 중요성을 분석하기 위해 이러한 결과를 사용하는 예제는 아래 샘플을 참조하세요.

적용 대상

PermutationFeatureImportance<TModel>(MulticlassClassificationCatalog, ISingleFeaturePredictionTransformer<TModel>, IDataView, String, Boolean, Nullable<Int32>, Int32)

MulticlassClassification에 대한 순열 기능 중요도(PFI)입니다.

public static System.Collections.Immutable.ImmutableArray<Microsoft.ML.Data.MulticlassClassificationMetricsStatistics> PermutationFeatureImportance<TModel> (this Microsoft.ML.MulticlassClassificationCatalog catalog, Microsoft.ML.ISingleFeaturePredictionTransformer<TModel> predictionTransformer, Microsoft.ML.IDataView data, string labelColumnName = "Label", bool useFeatureWeightFilter = false, int? numberOfExamplesToUse = default, int permutationCount = 1) where TModel : class;
static member PermutationFeatureImportance : Microsoft.ML.MulticlassClassificationCatalog * Microsoft.ML.ISingleFeaturePredictionTransformer<'Model (requires 'Model : null)> * Microsoft.ML.IDataView * string * bool * Nullable<int> * int -> System.Collections.Immutable.ImmutableArray<Microsoft.ML.Data.MulticlassClassificationMetricsStatistics> (requires 'Model : null)
<Extension()>
Public Function PermutationFeatureImportance(Of TModel As Class) (catalog As MulticlassClassificationCatalog, predictionTransformer As ISingleFeaturePredictionTransformer(Of TModel), data As IDataView, Optional labelColumnName As String = "Label", Optional useFeatureWeightFilter As Boolean = false, Optional numberOfExamplesToUse As Nullable(Of Integer) = Nothing, Optional permutationCount As Integer = 1) As ImmutableArray(Of MulticlassClassificationMetricsStatistics)

형식 매개 변수

TModel

매개 변수

catalog
MulticlassClassificationCatalog

다중 클래스 분류 카탈로그입니다.

predictionTransformer
ISingleFeaturePredictionTransformer<TModel>

기능 중요도를 평가할 모델입니다.

data
IDataView

평가 데이터 집합입니다.

labelColumnName
String

레이블 열 이름입니다. 열 데이터는 이어야 KeyDataViewType합니다.

useFeatureWeightFilter
Boolean

기능 가중치를 사용하여 기능을 미리 필터링합니다.

numberOfExamplesToUse
Nullable<Int32>

평가할 예제 수를 제한합니다. 는 최대 2개의 Bln 예제가 사용됨을 의미합니다.

permutationCount
Int32

수행할 순열의 수입니다.

반환

점수에 대한 기능별 '기여' 배열입니다.

예제

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.ML;

namespace Samples.Dynamic.Trainers.MulticlassClassification
{
    public static class PermutationFeatureImportance
    {
        public static void Example()
        {
            // Create a new context for ML.NET operations. It can be used for
            // exception tracking and logging, as a catalog of available operations
            // and as the source of randomness.
            var mlContext = new MLContext(seed: 1);

            // Create sample data.
            var samples = GenerateData();

            // Load the sample data as an IDataView.
            var data = mlContext.Data.LoadFromEnumerable(samples);

            // Define a training pipeline that concatenates features into a vector,
            // normalizes them, and then trains a linear model.
            var featureColumns =
                new string[] { nameof(Data.Feature1), nameof(Data.Feature2) };

            var pipeline = mlContext.Transforms
                .Concatenate("Features", featureColumns)
                .Append(mlContext.Transforms.Conversion.MapValueToKey("Label"))
                .Append(mlContext.Transforms.NormalizeMinMax("Features"))
                .Append(mlContext.MulticlassClassification.Trainers
                .SdcaMaximumEntropy());

            // Fit the pipeline to the data.
            var model = pipeline.Fit(data);

            // Transform the dataset.
            var transformedData = model.Transform(data);

            // Extract the predictor.
            var linearPredictor = model.LastTransformer;

            // Compute the permutation metrics for the linear model using the
            // normalized data.
            var permutationMetrics = mlContext.MulticlassClassification
                .PermutationFeatureImportance(linearPredictor, transformedData,
                permutationCount: 30);

            // Now let's look at which features are most important to the model
            // overall. Get the feature indices sorted by their impact on
            // microaccuracy.
            var sortedIndices = permutationMetrics
                .Select((metrics, index) => new { index, metrics.MicroAccuracy })
                .OrderByDescending(feature => Math.Abs(feature.MicroAccuracy.Mean))
                .Select(feature => feature.index);

            Console.WriteLine("Feature\tChange in MicroAccuracy\t95% Confidence in "
                + "the Mean Change in MicroAccuracy");

            var microAccuracy = permutationMetrics.Select(x => x.MicroAccuracy)
                .ToArray();

            foreach (int i in sortedIndices)
            {
                Console.WriteLine("{0}\t{1:G4}\t{2:G4}",
                    featureColumns[i],
                    microAccuracy[i].Mean,
                    1.96 * microAccuracy[i].StandardError);
            }

            // Expected output:
            //Feature     Change in MicroAccuracy  95% Confidence in the Mean Change in MicroAccuracy
            //Feature2     -0.1395                 0.0006567
            //Feature1     -0.05367                0.0006908
        }

        private class Data
        {
            public float Label { get; set; }

            public float Feature1 { get; set; }

            public float Feature2 { get; set; }
        }

        /// <summary>
        /// Generate an enumerable of Data objects, creating the label as a simple
        /// linear combination of the features.
        /// </summary>
        /// <param name="nExamples">The number of examples.</param>
        /// <param name="bias">The bias, or offset, in the calculation of the
        /// label.</param>
        /// <param name="weight1">The weight to multiply the first feature with to
        /// compute the label.</param>
        /// <param name="weight2">The weight to multiply the second feature with to
        /// compute the label.</param>
        /// <param name="seed">The seed for generating feature values and label
        /// noise.</param>
        /// <returns>An enumerable of Data objects.</returns>
        private static IEnumerable<Data> GenerateData(int nExamples = 10000,
            double bias = 0, double weight1 = 1, double weight2 = 2, int seed = 1)
        {
            var rng = new Random(seed);
            var max = bias + 4.5 * weight1 + 4.5 * weight2 + 0.5;
            for (int i = 0; i < nExamples; i++)
            {
                var data = new Data
                {
                    Feature1 = (float)(rng.Next(10) * (rng.NextDouble() - 0.5)),
                    Feature2 = (float)(rng.Next(10) * (rng.NextDouble() - 0.5)),
                };

                // Create a noisy label.
                var value = (float)
                    (bias + weight1 * data.Feature1 + weight2 * data.Feature2 +
                    rng.NextDouble() - 0.5);

                if (value < max / 3)
                    data.Label = 0;
                else if (value < 2 * max / 3)
                    data.Label = 1;
                else
                    data.Label = 2;
                yield return data;
            }
        }
    }
}

설명

PFI(순열 기능 중요도)는 학습된 기계 학습 모델에서 기능의 전역 중요성을 결정하는 기술입니다. PFI는 Breiman이 랜덤 포레스트 논문 섹션 10(Breiman)에서 동기를 부여받은 단순하면서도 강력한 기술입니다. "임의 포리스트" Machine Learning, 2001.) PFI 메서드의 장점은 모델 중립적이라는 점입니다. 이는 평가할 수 있는 모든 모델에서 작동하며 학습 집합뿐만 아니라 모든 데이터 세트를 사용하여 기능 중요도 메트릭을 계산할 수 있다는 것입니다.

PFI는 레이블이 지정된 데이터 세트를 사용하고, 기능을 선택하고, 모든 예제에서 해당 기능의 값을 통근하여 작동하므로 각 예제는 이제 기능의 임의 값과 다른 모든 기능에 대한 원래 값을 갖습니다. 그런 다음, 이 수정된 데이터 세트에 대해 평가 메트릭(예: 마이크로 정확도)이 계산되고 원래 데이터 세트의 평가 메트릭 변경 내용이 계산됩니다. 평가 메트릭의 변경 내용이 클수록 모델에 대한 기능이 더 중요합니다. PFI는 모델의 모든 기능에서 이 순열 분석을 하나씩 수행하여 작동합니다.

이 구현에서 PFI는 각 기능에 대해 가능한 모든 다중 클래스 분류 평가 메트릭의 변경 사항을 계산하고 ImmutableArray 개체가 MulticlassClassificationMetrics 반환됩니다. 모델의 기능 중요성을 분석하기 위해 이러한 결과를 사용하는 예제는 아래 샘플을 참조하세요.

적용 대상

PermutationFeatureImportance<TModel>(RegressionCatalog, ISingleFeaturePredictionTransformer<TModel>, IDataView, String, Boolean, Nullable<Int32>, Int32)

회귀에 대한 순열 기능 중요도(PFI)입니다.

public static System.Collections.Immutable.ImmutableArray<Microsoft.ML.Data.RegressionMetricsStatistics> PermutationFeatureImportance<TModel> (this Microsoft.ML.RegressionCatalog catalog, Microsoft.ML.ISingleFeaturePredictionTransformer<TModel> predictionTransformer, Microsoft.ML.IDataView data, string labelColumnName = "Label", bool useFeatureWeightFilter = false, int? numberOfExamplesToUse = default, int permutationCount = 1) where TModel : class;
static member PermutationFeatureImportance : Microsoft.ML.RegressionCatalog * Microsoft.ML.ISingleFeaturePredictionTransformer<'Model (requires 'Model : null)> * Microsoft.ML.IDataView * string * bool * Nullable<int> * int -> System.Collections.Immutable.ImmutableArray<Microsoft.ML.Data.RegressionMetricsStatistics> (requires 'Model : null)
<Extension()>
Public Function PermutationFeatureImportance(Of TModel As Class) (catalog As RegressionCatalog, predictionTransformer As ISingleFeaturePredictionTransformer(Of TModel), data As IDataView, Optional labelColumnName As String = "Label", Optional useFeatureWeightFilter As Boolean = false, Optional numberOfExamplesToUse As Nullable(Of Integer) = Nothing, Optional permutationCount As Integer = 1) As ImmutableArray(Of RegressionMetricsStatistics)

형식 매개 변수

TModel

매개 변수

catalog
RegressionCatalog

회귀 카탈로그입니다.

predictionTransformer
ISingleFeaturePredictionTransformer<TModel>

기능 중요도를 평가할 모델입니다.

data
IDataView

평가 데이터 집합입니다.

labelColumnName
String

레이블 열 이름입니다. 열 데이터는 이어야 Single합니다.

useFeatureWeightFilter
Boolean

기능 가중치를 사용하여 기능을 미리 필터링합니다.

numberOfExamplesToUse
Nullable<Int32>

평가할 예제 수를 제한합니다. 는 최대 2개의 Bln 예제가 사용됨을 의미합니다.

permutationCount
Int32

수행할 순열의 수입니다.

반환

점수에 대한 기능별 '기여' 배열입니다.

예제

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.ML;

namespace Samples.Dynamic.Trainers.Regression
{
    public static class PermutationFeatureImportance
    {
        public static void Example()
        {
            // Create a new context for ML.NET operations. It can be used for
            // exception tracking and logging, as a catalog of available operations
            // and as the source of randomness.
            var mlContext = new MLContext(seed: 1);

            // Create sample data.
            var samples = GenerateData();

            // Load the sample data as an IDataView.
            var data = mlContext.Data.LoadFromEnumerable(samples);

            // Define a training pipeline that concatenates features into a vector,
            // normalizes them, and then trains a linear model.
            var featureColumns = new string[] { nameof(Data.Feature1),
                nameof(Data.Feature2) };

            var pipeline = mlContext.Transforms.Concatenate(
                "Features",
                featureColumns)
                .Append(mlContext.Transforms.NormalizeMinMax("Features"))
                .Append(mlContext.Regression.Trainers.Ols());

            // Fit the pipeline to the data.
            var model = pipeline.Fit(data);

            // Transform the dataset.
            var transformedData = model.Transform(data);

            // Extract the predictor.
            var linearPredictor = model.LastTransformer;

            // Compute the permutation metrics for the linear model using the
            // normalized data.
            var permutationMetrics = mlContext.Regression
                .PermutationFeatureImportance(
                linearPredictor, transformedData, permutationCount: 30);

            // Now let's look at which features are most important to the model
            // overall. Get the feature indices sorted by their impact on RMSE.
            var sortedIndices = permutationMetrics
                .Select((metrics, index) => new
                {
                    index,
                    metrics.RootMeanSquaredError
                })

                .OrderByDescending(feature => Math.Abs(
                    feature.RootMeanSquaredError.Mean))

                .Select(feature => feature.index);

            Console.WriteLine("Feature\tModel Weight\tChange in RMSE\t95%" +
                "Confidence in the Mean Change in RMSE");

            var rmse = permutationMetrics.Select(x => x.RootMeanSquaredError)
                .ToArray();

            foreach (int i in sortedIndices)
            {
                Console.WriteLine("{0}\t{1:0.00}\t{2:G4}\t{3:G4}",
                    featureColumns[i],
                    linearPredictor.Model.Weights[i],
                    rmse[i].Mean,
                    1.96 * rmse[i].StandardError);
            }

            // Expected output:
            //  Feature    Model Weight Change in RMSE  95% Confidence in the Mean Change in RMSE
            //  Feature2        9.00        4.009       0.008304
            //  Feature1        4.48        1.901       0.003351
        }

        private class Data
        {
            public float Label { get; set; }

            public float Feature1 { get; set; }

            public float Feature2 { get; set; }
        }

        /// <summary>
        /// Generate an enumerable of Data objects, creating the label as a simple
        /// linear combination of the features.
        /// </summary>
        /// <param name="nExamples">The number of examples.</param>
        /// <param name="bias">The bias, or offset, in the calculation of the label.
        /// </param>
        /// <param name="weight1">The weight to multiply the first feature with to
        /// compute the label.</param>
        /// <param name="weight2">The weight to multiply the second feature with to
        /// compute the label.</param>
        /// <param name="seed">The seed for generating feature values and label
        /// noise.</param>
        /// <returns>An enumerable of Data objects.</returns>
        private static IEnumerable<Data> GenerateData(int nExamples = 10000,
            double bias = 0, double weight1 = 1, double weight2 = 2, int seed = 1)
        {
            var rng = new Random(seed);
            for (int i = 0; i < nExamples; i++)
            {
                var data = new Data
                {
                    Feature1 = (float)(rng.Next(10) * (rng.NextDouble() - 0.5)),
                    Feature2 = (float)(rng.Next(10) * (rng.NextDouble() - 0.5)),
                };

                // Create a noisy label.
                data.Label = (float)(bias + weight1 * data.Feature1 + weight2 *
                    data.Feature2 + rng.NextDouble() - 0.5);
                yield return data;
            }
        }
    }
}

설명

PFI(순열 기능 중요도)는 학습된 기계 학습 모델에서 기능의 전역 중요성을 결정하는 기술입니다. PFI는 Breiman이 랜덤 포레스트 논문 섹션 10(Breiman)에서 동기를 부여받은 단순하면서도 강력한 기술입니다. "임의 포리스트" Machine Learning, 2001.) PFI 메서드의 장점은 모델 중립적이라는 점입니다. 이는 평가할 수 있는 모든 모델에서 작동하며 학습 집합뿐만 아니라 모든 데이터 세트를 사용하여 기능 중요도 메트릭을 계산할 수 있다는 것입니다.

PFI는 레이블이 지정된 데이터 세트를 사용하고, 기능을 선택하고, 모든 예제에서 해당 기능의 값을 통근하여 작동하므로 각 예제는 이제 기능의 임의 값과 다른 모든 기능에 대한 원래 값을 갖습니다. 그런 다음, 이 수정된 데이터 세트에 대해 평가 메트릭(예: R 제곱)이 계산되고 원래 데이터 세트의 평가 메트릭 변경 내용이 계산됩니다. 평가 메트릭의 변경 내용이 클수록 모델에 대한 기능이 더 중요합니다. PFI는 모델의 모든 기능에서 이 순열 분석을 하나씩 수행하여 작동합니다.

이 구현에서 PFI는 각 기능에 대해 가능한 모든 회귀 평가 메트릭의 변경 사항을 계산하고 ImmutableArray 개체가 RegressionMetrics 반환됩니다. 모델의 기능 중요성을 분석하기 위해 이러한 결과를 사용하는 예제는 아래 샘플을 참조하세요.

적용 대상

PermutationFeatureImportance<TModel>(RankingCatalog, ISingleFeaturePredictionTransformer<TModel>, IDataView, String, String, Boolean, Nullable<Int32>, Int32)

순위에 대한 순열 기능 중요도(PFI)입니다.

public static System.Collections.Immutable.ImmutableArray<Microsoft.ML.Data.RankingMetricsStatistics> PermutationFeatureImportance<TModel> (this Microsoft.ML.RankingCatalog catalog, Microsoft.ML.ISingleFeaturePredictionTransformer<TModel> predictionTransformer, Microsoft.ML.IDataView data, string labelColumnName = "Label", string rowGroupColumnName = "GroupId", bool useFeatureWeightFilter = false, int? numberOfExamplesToUse = default, int permutationCount = 1) where TModel : class;
static member PermutationFeatureImportance : Microsoft.ML.RankingCatalog * Microsoft.ML.ISingleFeaturePredictionTransformer<'Model (requires 'Model : null)> * Microsoft.ML.IDataView * string * string * bool * Nullable<int> * int -> System.Collections.Immutable.ImmutableArray<Microsoft.ML.Data.RankingMetricsStatistics> (requires 'Model : null)
<Extension()>
Public Function PermutationFeatureImportance(Of TModel As Class) (catalog As RankingCatalog, predictionTransformer As ISingleFeaturePredictionTransformer(Of TModel), data As IDataView, Optional labelColumnName As String = "Label", Optional rowGroupColumnName As String = "GroupId", Optional useFeatureWeightFilter As Boolean = false, Optional numberOfExamplesToUse As Nullable(Of Integer) = Nothing, Optional permutationCount As Integer = 1) As ImmutableArray(Of RankingMetricsStatistics)

형식 매개 변수

TModel

매개 변수

catalog
RankingCatalog

순위 카탈로그입니다.

predictionTransformer
ISingleFeaturePredictionTransformer<TModel>

기능 중요도를 평가할 모델입니다.

data
IDataView

평가 데이터 집합입니다.

labelColumnName
String

레이블 열 이름입니다. 열 데이터는 이어야 Single 합니다.KeyDataViewType

rowGroupColumnName
String

GroupId 열 이름

useFeatureWeightFilter
Boolean

기능 가중치를 사용하여 기능을 미리 필터링합니다.

numberOfExamplesToUse
Nullable<Int32>

평가할 예제 수를 제한합니다. 는 최대 2개의 Bln 예제가 사용됨을 의미합니다.

permutationCount
Int32

수행할 순열의 수입니다.

반환

점수에 대한 기능별 '기여' 배열입니다.

예제

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.ML;

namespace Samples.Dynamic.Trainers.Ranking
{
    public static class PermutationFeatureImportance
    {
        public static void Example()
        {
            // Create a new context for ML.NET operations. It can be used for
            // exception tracking and logging, as a catalog of available operations
            // and as the source of randomness.
            var mlContext = new MLContext(seed: 1);

            // Create sample data.
            var samples = GenerateData();

            // Load the sample data as an IDataView.
            var data = mlContext.Data.LoadFromEnumerable(samples);

            // Define a training pipeline that concatenates features into a vector,
            // normalizes them, and then trains a linear model.
            var featureColumns = new string[] { nameof(Data.Feature1), nameof(
                Data.Feature2) };
            var pipeline = mlContext.Transforms.Concatenate("Features",
                featureColumns)
                    .Append(mlContext.Transforms.Conversion.MapValueToKey("Label"))
                    .Append(mlContext.Transforms.Conversion.MapValueToKey(
                        "GroupId"))
                    .Append(mlContext.Transforms.NormalizeMinMax("Features"))
                    .Append(mlContext.Ranking.Trainers.FastTree());

            // Fit the pipeline to the data.
            var model = pipeline.Fit(data);

            // Transform the dataset.
            var transformedData = model.Transform(data);

            // Extract the predictor.
            var linearPredictor = model.LastTransformer;

            // Compute the permutation metrics for the linear model using the
            // normalized data.
            var permutationMetrics = mlContext.Ranking.PermutationFeatureImportance(
                linearPredictor, transformedData, permutationCount: 30);

            // Now let's look at which features are most important to the model
            // overall. Get the feature indices sorted by their impact on NDCG@1.
            var sortedIndices = permutationMetrics.Select((metrics, index) => new
            {
                index,
                metrics.NormalizedDiscountedCumulativeGains
            })
                .OrderByDescending(feature => Math.Abs(
                    feature.NormalizedDiscountedCumulativeGains[0].Mean))

                .Select(feature => feature.index);

            Console.WriteLine("Feature\tChange in NDCG@1\t95% Confidence in the" +
                "Mean Change in NDCG@1");
            var ndcg = permutationMetrics.Select(
                x => x.NormalizedDiscountedCumulativeGains).ToArray();
            foreach (int i in sortedIndices)
            {
                Console.WriteLine("{0}\t{1:G4}\t{2:G4}",
                    featureColumns[i],
                    ndcg[i][0].Mean,
                    1.96 * ndcg[i][0].StandardError);
            }

            // Expected output:
            //  Feature     Change in NDCG@1    95% Confidence in the Mean Change in NDCG@1
            //  Feature2     -0.2421            0.001748
            //  Feature1     -0.0513            0.001184
        }

        private class Data
        {
            public float Label { get; set; }

            public int GroupId { get; set; }

            public float Feature1 { get; set; }

            public float Feature2 { get; set; }
        }

        /// <summary>
        /// Generate an enumerable of Data objects, creating the label as a simple
        /// linear combination of the features.
        /// </summary>
        /// 
        /// <param name="nExamples">The number of examples.</param>
        /// 
        /// <param name="bias">The bias, or offset, in the calculation of the label.
        /// </param>
        /// 
        /// <param name="weight1">The weight to multiply the first feature with to
        /// compute the label.</param>
        /// 
        /// <param name="weight2">The weight to multiply the second feature with to
        /// compute the label.</param>
        /// 
        /// <param name="seed">The seed for generating feature values and label
        /// noise.</param>
        /// 
        /// <returns>An enumerable of Data objects.</returns>
        private static IEnumerable<Data> GenerateData(int nExamples = 10000,
            double bias = 0, double weight1 = 1, double weight2 = 2, int seed = 1,
                int groupSize = 5)
        {
            var rng = new Random(seed);
            var max = bias + 4.5 * weight1 + 4.5 * weight2 + 0.5;
            for (int i = 0; i < nExamples; i++)
            {
                var data = new Data
                {
                    GroupId = i / groupSize,
                    Feature1 = (float)(rng.Next(10) * (rng.NextDouble() - 0.5)),
                    Feature2 = (float)(rng.Next(10) * (rng.NextDouble() - 0.5)),
                };

                // Create a noisy label.
                var value = (float)(bias + weight1 * data.Feature1 + weight2 *
                    data.Feature2 + rng.NextDouble() - 0.5);
                if (value < max / 3)
                    data.Label = 0;
                else if (value < 2 * max / 3)
                    data.Label = 1;
                else
                    data.Label = 2;
                yield return data;
            }
        }
    }
}

설명

PFI(순열 기능 중요도)는 학습된 기계 학습 모델에서 기능의 전역 중요성을 결정하는 기술입니다. PFI는 Breiman이 랜덤 포레스트 논문 섹션 10(Breiman)에서 동기를 부여받은 단순하면서도 강력한 기술입니다. "임의 포리스트" Machine Learning, 2001.) PFI 메서드의 장점은 모델 중립적이라는 점입니다. 이는 평가할 수 있는 모든 모델에서 작동하며 학습 집합뿐만 아니라 모든 데이터 세트를 사용하여 기능 중요도 메트릭을 계산할 수 있다는 것입니다.

PFI는 레이블이 지정된 데이터 세트를 사용하고, 기능을 선택하고, 모든 예제에서 해당 기능의 값을 통근하여 작동하므로 각 예제는 이제 기능의 임의 값과 다른 모든 기능에 대한 원래 값을 갖습니다. 그런 다음, 이 수정된 데이터 세트에 대해 평가 메트릭(예: NDCG)이 계산되고 원래 데이터 세트의 평가 메트릭 변경 내용이 계산됩니다. 평가 메트릭의 변경 내용이 클수록 모델에 대한 기능이 더 중요합니다. PFI는 모델의 모든 기능에서 이 순열 분석을 하나씩 수행하여 작동합니다.

이 구현에서 PFI는 각 기능에 대해 가능한 모든 순위 평가 메트릭의 변경 사항을 계산하고 ImmutableArray 개체가 RankingMetrics 반환됩니다. 모델의 기능 중요성을 분석하기 위해 이러한 결과를 사용하는 예제는 아래 샘플을 참조하세요.

적용 대상