次の方法で共有


AutoMLExperiment クラス

定義

AutoML 実験のクラス

public class AutoMLExperiment
type AutoMLExperiment = class
Public Class AutoMLExperiment
継承
AutoMLExperiment

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.ML.Data;

namespace Microsoft.ML.AutoML.Samples
{
    public static class AutoMLExperiment
    {
        public static async Task RunAsync()
        {
            var seed = 0;

            // 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. Setting the seed to a fixed number
            // in this example to make outputs deterministic.
            var context = new MLContext(seed);

            // Create a list of training data points and convert it to IDataView.
            var data = GenerateRandomBinaryClassificationDataPoints(100, seed);
            var dataView = context.Data.LoadFromEnumerable(data);

            var trainTestSplit = context.Data.TrainTestSplit(dataView);

            // Define the sweepable pipeline using predefined binary trainers and search space.
            var pipeline = context.Auto().BinaryClassification(labelColumnName: "Label", featureColumnName: "Features");

            // Create an AutoML experiment
            var experiment = context.Auto().CreateExperiment();

            // Redirect AutoML log to console
            context.Log += (object o, LoggingEventArgs e) =>
            {
                if (e.Source == nameof(AutoMLExperiment) && e.Kind > Runtime.ChannelMessageKind.Trace)
                {
                    Console.WriteLine(e.RawMessage);
                }
            };

            // Config experiment to optimize "Accuracy" metric on given dataset.
            // This experiment will run hyper-parameter optimization on given pipeline
            experiment.SetPipeline(pipeline)
                      .SetDataset(trainTestSplit.TrainSet, fold: 5) // use 5-fold cross validation to evaluate each trial
                      .SetBinaryClassificationMetric(BinaryClassificationMetric.Accuracy, "Label")
                      .SetMaxModelToExplore(100); // explore 100 trials

            // start automl experiment
            var result = await experiment.RunAsync();

            // Expected output samples during training:
            //      Update Running Trial - Id: 0
            //      Update Completed Trial - Id: 0 - Metric: 0.5536912515402218 - Pipeline: FastTreeBinary - Duration: 595 - Peak CPU: 0.00 % -Peak Memory in MB: 35.81
            //      Update Best Trial - Id: 0 - Metric: 0.5536912515402218 - Pipeline: FastTreeBinary

            // evaluate test dataset on best model.
            var bestModel = result.Model;
            var eval = bestModel.Transform(trainTestSplit.TestSet);
            var metrics = context.BinaryClassification.Evaluate(eval);

            PrintMetrics(metrics);

            // Expected output:
            //  Accuracy: 0.67
            //  AUC: 0.75
            //  F1 Score: 0.33
            //  Negative Precision: 0.88
            //  Negative Recall: 0.70
            //  Positive Precision: 0.25
            //  Positive Recall: 0.50

            //  TEST POSITIVE RATIO: 0.1667(2.0 / (2.0 + 10.0))
            //  Confusion table
            //            ||======================
            //  PREDICTED || positive | negative | Recall
            //  TRUTH     ||======================
            //   positive || 1 | 1 | 0.5000
            //   negative || 3 | 7 | 0.7000
            //            ||======================
            //  Precision || 0.2500 | 0.8750 |
        }

        private static IEnumerable<BinaryClassificationDataPoint> GenerateRandomBinaryClassificationDataPoints(int count,
            int seed = 0)

        {
            var random = new Random(seed);
            float randomFloat() => (float)random.NextDouble();
            for (int i = 0; i < count; i++)
            {
                var label = randomFloat() > 0.5f;
                yield return new BinaryClassificationDataPoint
                {
                    Label = label,
                    // Create random features that are correlated with the label.
                    // For data points with false label, the feature values are
                    // slightly increased by adding a constant.
                    Features = Enumerable.Repeat(label, 50)
                        .Select(x => x ? randomFloat() : randomFloat() +
                        0.1f).ToArray()

                };
            }
        }

        // Example with label and 50 feature values. A data set is a collection of
        // such examples.
        private class BinaryClassificationDataPoint
        {
            public bool Label { get; set; }

            [VectorType(50)]
            public float[] Features { get; set; }
        }

        // Class used to capture predictions.
        private class Prediction
        {
            // Original label.
            public bool Label { get; set; }
            // Predicted label from the trainer.
            public bool PredictedLabel { get; set; }
        }

        // Pretty-print BinaryClassificationMetrics objects.
        private static void PrintMetrics(BinaryClassificationMetrics metrics)
        {
            Console.WriteLine($"Accuracy: {metrics.Accuracy:F2}");
            Console.WriteLine($"AUC: {metrics.AreaUnderRocCurve:F2}");
            Console.WriteLine($"F1 Score: {metrics.F1Score:F2}");
            Console.WriteLine($"Negative Precision: " +
                $"{metrics.NegativePrecision:F2}");

            Console.WriteLine($"Negative Recall: {metrics.NegativeRecall:F2}");
            Console.WriteLine($"Positive Precision: " +
                $"{metrics.PositivePrecision:F2}");

            Console.WriteLine($"Positive Recall: {metrics.PositiveRecall:F2}\n");
            Console.WriteLine(metrics.ConfusionMatrix.GetFormattedConfusionTable());
        }
    }
}

コンストラクター

AutoMLExperiment(MLContext, AutoMLExperiment+AutoMLExperimentSettings)

AutoML 実験のクラス

メソッド

AddSearchSpace(String, SearchSpace)

AutoML 実験のクラス

Run()

実験を実行し、最良の試用版の結果を同期して返します。

RunAsync(CancellationToken)

実験を実行し、最良の試用版の結果を非同期的に返します。 この実験では、取り消されたときに ct 試用が完了した場合に現在の最適な試用版の結果が返され、試用版が完了していない場合は "試用の実行を完了せずにトレーニング時間が完了しました" というメッセージがスロー TimeoutException されます。 もう 1 つ注意する必要があるのは、この関数が取り消された後 ct すぐに戻らないということです。 代わりに、 を呼び出 Microsoft.ML.MLContext.CancelExecution してすべてのトレーニング プロセスを取り消し、実行中のすべての試用版が取り消されるか完了するまで待機します。

SetMaximumMemoryUsageInMegaByte(Double)

AutoML 実験のクラス

SetMaxModelToExplore(Int32)

AutoML 実験のクラス

SetMonitor<TMonitor>()

AutoML 実験のクラス

SetMonitor<TMonitor>(Func<IServiceProvider,TMonitor>)

AutoML 実験のクラス

SetMonitor<TMonitor>(TMonitor)

AutoML 実験のクラス

SetTrainingTimeInSeconds(UInt32)

AutoML 実験のクラス

SetTrialRunner<TTrialRunner>()

AutoML 実験のクラス

SetTrialRunner<TTrialRunner>(Func<IServiceProvider,TTrialRunner>)

AutoML 実験のクラス

SetTrialRunner<TTrialRunner>(TTrialRunner)

AutoML 実験のクラス

SetTuner<TTuner>()

AutoML 実験のクラス

SetTuner<TTuner>(Func<IServiceProvider,TTuner>)

AutoML 実験のクラス

SetTuner<TTuner>(TTuner)

AutoML 実験のクラス

拡張メソッド

SetBinaryClassificationMetric(AutoMLExperiment, BinaryClassificationMetric, String, String)

の評価マネージャーとして設定 Microsoft.ML.AutoML.BinaryMetricManager します AutoMLExperiment。 これにより、評価メトリックとして を使用metricできるようになりますAutoMLExperiment

SetCheckpoint(AutoMLExperiment, String)

チェックポイント フォルダーを に AutoMLExperiment設定します。 チェックポイント フォルダーは、一時的な出力の保存、履歴の実行、および最後のチェックポイントからのトレーニング プロセスの復元に使用されるその他の多くのものを保存し、トレーニングを続行するために使用されます。

SetCostFrugalTuner(AutoMLExperiment)

ハイパーパラメーター最適化のチューナーとして設定 Microsoft.ML.AutoML.CostFrugalTuner します。

SetDataset(AutoMLExperiment, DataOperationsCatalog+TrainTestData)

のトレーニングデータセットと検証データセットを設定します AutoMLExperiment。 これにより、 AutoMLExperimenttrainValidationSplit使用TrainSetしてモデルをトレーニングし、 をtrainValidationSplit使用TestSetしてモデルを評価します。

SetDataset(AutoMLExperiment, IDataView, IDataView, Boolean)

のトレーニングデータセットと検証データセットを設定します AutoMLExperiment。 これにより、 AutoMLExperiment を使用 train してモデルをトレーニングし、 を使用 validation してモデルを評価します。

SetDataset(AutoMLExperiment, IDataView, Int32, String)

のクロス検証データセットを設定します AutoMLExperiment。 これにより、n=fold クロス検証分割をdataset使用して、モデルのトレーニングと評価が行われますAutoMLExperiment

SetEciCostFrugalTuner(AutoMLExperiment)

ハイパーパラメーター最適化用のチューナーとして設定 Microsoft.ML.AutoML.EciCostFrugalTuner します。 このチューナーは、 からの SweepablePipeline検索空間でのみ機能します。

SetGridSearchTuner(AutoMLExperiment, Int32)

ハイパーパラメーターの最適化のためにチューナーとして設定 Microsoft.ML.AutoML.GridSearchTuner します。

SetMulticlassClassificationMetric(AutoMLExperiment, MulticlassClassificationMetric, String, String)

の評価マネージャーとして設定 Microsoft.ML.AutoML.MultiClassMetricManager します AutoMLExperiment。 これにより、評価メトリックとして を使用metricできるようになりますAutoMLExperiment

SetPerformanceMonitor(AutoMLExperiment, Int32)

IPerformanceMonitor設定DefaultPerformanceMonitorしますAutoMLExperiment

SetPerformanceMonitor<TPerformanceMonitor>(AutoMLExperiment)

カスタム パフォーマンス モニターを として IPerformanceMonitor 設定します AutoMLExperiment

SetPerformanceMonitor<TPerformanceMonitor>(AutoMLExperiment, Func<IServiceProvider,TPerformanceMonitor>)

カスタム パフォーマンス モニターを として IPerformanceMonitor 設定します AutoMLExperiment

SetPipeline(AutoMLExperiment, SweepablePipeline)

トレーニング用に設定 pipeline します。 これにより、AutoMLExperimentautoml traininng にも 、 Microsoft.ML.AutoML.MLContextMonitorMicrosoft.ML.AutoML.EciCostFrugalTuner が使用Microsoft.ML.AutoML.SweepablePipelineRunnerされます。

SetRandomSearchTuner(AutoMLExperiment, Nullable<Int32>)

ハイパーパラメーターの最適化のためにチューナーとして設定 Microsoft.ML.AutoML.RandomSearchTuner します。 が指定されている場合 seed は、そのシードを使用して を初期化 Microsoft.ML.AutoML.RandomSearchTunerします。 それ以外の場合は、 Seed が使用されます。

SetRegressionMetric(AutoMLExperiment, RegressionMetric, String, String)

の評価マネージャーとして設定 Microsoft.ML.AutoML.RegressionMetricManager します AutoMLExperiment。 これにより、評価メトリックとして を使用metricできるようになりますAutoMLExperiment

SetSmacTuner(AutoMLExperiment, Int32, Int32, Int32, Int32, Single, Int32, Int32, Double, Int32)

ハイパーパラメーター最適化のチューナーとして設定 Microsoft.ML.AutoML.SmacTuner します。 smac のパフォーマンスは、smac の内部リグレッサーに適合するために使用される、 nMinForSpitsplitRatioによってnumberOfTrees決定される大きな拡張にあります。

適用対象