ML.NET是一個面向.NET開發人員的開源、跨平台的機器學習框架。
使用ML.NET,您可以輕松地為諸如情緒分析、價格預測、銷售分析、推薦、圖像分類等場景構建自定義機器學習模型。
ML.NET從0.8版開始,支持評估特性的重要性,從而了解哪些列對於預測最終值更重要。
排列特征的重要性在於,突出最重要的特征,以便理解哪些特征必須包括,哪些不用包括;從數據集中排除一些特性意味着減少噪音,結果會更好。
因此,通過PFI,我們可以了解在我們的學習pipeline中什么是最重要的列,並使用它們來預測值。
Pipeline
第一步與預測值的步驟相同,因此必須構建pipeline。
例如,一個標准pipeline可以是這樣的:
var mlContext = new MLContext(); var dataView = MlContext.Data.LoadFromTextFile<T>(dataPath, separator, hasHeader: false); var pipeline = MlContext.Transforms.CopyColumns("Label", _predictedColumn.ColumnName).Append(MlContext.Transforms.Concatenate(_featureColumn, _concatenatedColumns));
這是一個非常簡單的pipeline,從文件中加載數據,復制label列並添加feature列。
現在pipeline已經配置好了,我們可以構建模型了。
Model
建立模型意味着獲取pipeline、附加選擇算法,對其進行擬合和變換。
var tranformedDataView = pipeline.Append(MlContext.Regression.Trainers.LbfgsPoissonRegression()).Fit(DataView).Transform(DataView);
結果是一個轉換后的數據視圖,其中應用了pipeline轉換所有數據,我們將在Permutation Feature Importance方法中使用這些轉換。
Metrics
為了獲得PFI指標,除了轉換后的數據視圖,我們還需要一個轉換器:
var transformer = pipeline.MlContext.Regression.Trainers.LbfgsPoissonRegression().Fit(tranformedDataView);
現在我們可以得到度量:
var permutationMetrics = pipeline.MlContext.Regression.PermutationFeatureImportance(transformer, transformedDataView, permutationCount: 3);
使用permutation count參數,我們可以指定希望為回歸度量執行的觀察次數。
結果是一個回歸度量統計數據的數組,並在一個特定的度量上可用的排序,比如平均值:
var regressionMetrics = permutationMetrics.Select((metric, index) => new { index, metric.RSquared }).OrderByDescending(features => Math.Abs(features.RSquared.Mean));
有了循環,我們現在可以打印的指標:
foreach (var metric in regressionMetrics) { if (metric.index >= transformedData.Schema.Count || (transformedData.Schema[metric.index].IsHidden || transformedData.Schema[metric.index].Name == "Label" || transformedData.Schema[metric.index].Name == "Features")) continue; Console.WriteLine($"{transformedData.Schema[metric.index].Name,-20}|\t{metric.RSquared.Mean:F6}"); }
在這個示例的情況下,輸出是:

有了這個統計數據,我們可以了解什么是最重要的特性,並將更改應用到pipeline構建中。
這篇文章的源代碼可以在GitHub項目上找到。
