После обновления до ml.net v0.10 Fit () не работает - PullRequest
0 голосов
/ 06 февраля 2019

Я использую .NET-Framework 4.6.1

После обновления ML.NET до версии 0.10 я не могу запустить свой код.Я строю свой конвейер, и у меня появляется ошибка при выполнении Fit () - Method.

Message = "Метод не найден: \" System.Collections.Generic.IEnumerable 1<!!0> System.Linq.Enumerable.Append(System.Collections.Generic.IEnumerable 1, !! 0) \"."

using System.Collections.Generic;в моих директивах.

Я что-то упустил или я должен придерживаться v0.9 сейчас?

Спасибо

using System;
using System.IO;

using Microsoft.ML;
using Microsoft.ML.Core.Data;
using Microsoft.ML.Data;
using MulticlassClassification_Iris.DataStructures;

namespace MulticlassClassification_Iris
{
public static partial class Program
{
    private static string AppPath => Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);


    private static string TrainDataPath = @"..\machinelearning-samples\samples\csharp\getting-started\MulticlassClassification_Iris\IrisClassification\Data\iris-train.txt";
    private static string TestDataPath = @"..\machinelearning-samples\samples\csharp\getting-started\MulticlassClassification_Iris\IrisClassification\Data\iris-test.txt";


    private static string ModelPath = @"C:\Users\waldemar\Documents\model.txt";

    private static void Main(string[] args)
    {
        // Create MLContext to be shared across the model creation workflow objects 
        // Set a random seed for repeatable/deterministic results across multiple trainings.
        var mlContext = new MLContext(seed: 0);

        //1.
        BuildTrainEvaluateAndSaveModel(mlContext);

        //2.
        TestSomePredictions(mlContext);

        Console.WriteLine("=============== End of process, hit any key to finish ===============");
        Console.ReadKey();
    }

    private static void BuildTrainEvaluateAndSaveModel(MLContext mlContext)
    {
        // STEP 1: Common data loading configuration
        var trainingDataView = mlContext.Data.ReadFromTextFile<IrisData>(TrainDataPath, hasHeader: true);
        var testDataView = mlContext.Data.ReadFromTextFile<IrisData>(TestDataPath, hasHeader: true);


        // STEP 2: Common data process configuration with pipeline data transformations
        var dataProcessPipeline = mlContext.Transforms.Concatenate("Features", "SepalLength",
                                                                               "SepalWidth",
                                                                               "PetalLength",
                                                                               "PetalWidth").AppendCacheCheckpoint(mlContext);

        // STEP 3: Set the training algorithm, then append the trainer to the pipeline  
        var trainer = mlContext.MulticlassClassification.Trainers.StochasticDualCoordinateAscent(labelColumn: "Label", featureColumn: "Features");
        var trainingPipeline = dataProcessPipeline.Append(trainer);

        // STEP 4: Train the model fitting to the DataSet

        //Measure training time
        var watch = System.Diagnostics.Stopwatch.StartNew();

        Console.WriteLine("=============== Training the model ===============");
        ITransformer trainedModel = trainingPipeline.Fit(trainingDataView);

        //Stop measuring time
        watch.Stop();
        long elapsedMs = watch.ElapsedMilliseconds;
        Console.WriteLine($"***** Training time: {elapsedMs/1000} seconds *****");


        // STEP 5: Evaluate the model and show accuracy stats
        Console.WriteLine("===== Evaluating Model's accuracy with Test data =====");
        var predictions = trainedModel.Transform(testDataView);
        var metrics = mlContext.MulticlassClassification.Evaluate(predictions, "Label", "Score");

        Common.ConsoleHelper.PrintMultiClassClassificationMetrics(trainer.ToString(), metrics);

        // STEP 6: Save/persist the trained model to a .ZIP file
        using (var fs = new FileStream(ModelPath, FileMode.Create, FileAccess.Write, FileShare.Write))
            mlContext.Model.Save(trainedModel, fs);

        Console.WriteLine("The model is saved to {0}", ModelPath);
    }

    private static void TestSomePredictions(MLContext mlContext)
    {
        //Test Classification Predictions with some hard-coded samples 

        ITransformer trainedModel;
        using (var stream = new FileStream(ModelPath, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            trainedModel = mlContext.Model.Load(stream);
        }

        // Create prediction engine related to the loaded trained model
        var predEngine = trainedModel.CreatePredictionEngine<IrisData, IrisPrediction>(mlContext);

        //Score sample 1
        var resultprediction1 = predEngine.Predict(SampleIrisData.Iris1);

        Console.WriteLine($"Actual: setosa.     Predicted probability: setosa:      {resultprediction1.Score[0]:0.####}");
        Console.WriteLine($"                                           versicolor:  {resultprediction1.Score[1]:0.####}");
        Console.WriteLine($"                                           virginica:   {resultprediction1.Score[2]:0.####}");
        Console.WriteLine();

        //Score sample 2
        var resultprediction2 = predEngine.Predict(SampleIrisData.Iris2);

        Console.WriteLine($"Actual: setosa.     Predicted probability: setosa:      {resultprediction2.Score[0]:0.####}");
        Console.WriteLine($"                                           versicolor:  {resultprediction2.Score[1]:0.####}");
        Console.WriteLine($"                                           virginica:   {resultprediction2.Score[2]:0.####}");
        Console.WriteLine();

        //Score sample 3
        var resultprediction3 = predEngine.Predict(SampleIrisData.Iris3);

        Console.WriteLine($"Actual: setosa.     Predicted probability: setosa:      {resultprediction3.Score[0]:0.####}");
        Console.WriteLine($"                                           versicolor:  {resultprediction3.Score[1]:0.####}");
        Console.WriteLine($"                                           virginica:   {resultprediction3.Score[2]:0.####}");
        Console.WriteLine();

    }
}

}

Ответы [ 2 ]

0 голосов
/ 08 февраля 2019

Сейчас работает ML.NET v0.10.Мне пришлось обновить мою .NET-Framework до 4.7.1.

0 голосов
/ 06 февраля 2019
  • API в ML.NET v0.10 и переход на 0.11 изменяется, поэтому он совместим со многими различными классами в API.

Вероятно, проблема, с которой вы столкнулись, может быть вызвана тем, что во многих методах API мы изменили порядок параметров .Следовательно, если эти параметры имеют один и тот же тип, он скомпилируется, но не будет работать должным образом.

Проверьте все ваши параметры, используемые в API ML.NET, чтобы убедиться, что они верны.Что-то, что может помочь, - предоставить имя параметров, например:

.method(param1:value1, param2:value2)

Проверьте эту ветку, где мы переносим образцы в v0.10, если вам нужна дополнительная помощь из примеров,ок?

ссылка

Надеюсь, это поможет.:)

Цезарь

...