Я получаю исключение, когда пытаюсь предсказать изображение в модели, импортированной в ML.Transform.Tensorflow? - PullRequest
0 голосов
/ 29 сентября 2019

Я использую предварительно обученную модель, где мне нужно предсказать изображение с меткой. Но я постоянно получаю сообщение об ошибке, когда он пытается предсказать изображение. Здесь не исключение: Microsoft.ML.Transforms.TensorFlow.TFException: 'Первым измерением отступов должен быть ранг входных данных [4,2] [1,1,224,224,3]

Размеры изображений 224x224, то есть размеры изображений, которые использовались в предварительно обученной модели. Код также изменяет размеры изображений заранее. Вот код:

  `


 static void Main(string[] args)
    {
        var modelScorer = new TFModelScorer(_trainTagsTsv, _assetsPath, _inceptionPb, _trainLabels);
        modelScorer.Score();

    }
    public class TFModelScorer
    {
        private readonly string dataLocation;
        private readonly string imagesFolder;
        private readonly string modelLocation;
        private readonly string labelsLocation;
        private readonly MLContext mlContext;
        private static string ImageReal = nameof(ImageReal);

        public TFModelScorer(string dataLocation, string imagesFolder, string modelLocation, string labelsLocation)
        {
            this.dataLocation = dataLocation;
            this.imagesFolder = imagesFolder;
            this.modelLocation = modelLocation;
            this.labelsLocation = labelsLocation;
            mlContext = new MLContext();
        }

        public struct ImageNetSettings
        {
            public const int imageHeight = 224;
            public const int imageWidth = 224;
            public const int mean = 117;
            public const bool channelsLast = true;
        }

        public struct InceptionSettings
        {
            // for checking tensor names, you can use tools like Netron,
            // which is installed by Visual Studio AI Tools

            // input tensor name
            public const string inputTensorName = "data";

            // output tensor name
            public const string outputTensorName = "fc8/Softmax";
        }

        public void Score()
        {
            var model = LoadModel(dataLocation, imagesFolder, modelLocation);

            var predictions = PredictDataUsingModel(dataLocation, imagesFolder, labelsLocation, model).ToArray();

        }

        private PredictionEngine<ImageNetData, ImageNetPrediction> LoadModel(string dataLocation, string imagesFolder, string modelLocation)
        {
            Console.WriteLine($"Model location: {modelLocation}");
            Console.WriteLine($"Images folder: {imagesFolder}");
            Console.WriteLine($"Training file: {dataLocation}");
            Console.WriteLine($"Default parameters: image size=({ImageNetSettings.imageWidth},{ImageNetSettings.imageHeight}), image mean: {ImageNetSettings.mean}");

            var data = mlContext.Data.LoadFromTextFile<ImageNetData>(dataLocation, hasHeader: true);

            var pipeline = mlContext.Transforms.LoadImages(outputColumnName: "data", imageFolder: imagesFolder, inputColumnName: nameof(ImageNetData.ImagePath))
                            .Append(mlContext.Transforms.ResizeImages(outputColumnName: "data", imageWidth: ImageNetSettings.imageWidth, imageHeight: ImageNetSettings.imageHeight, inputColumnName: "data"))
                            .Append(mlContext.Transforms.ExtractPixels(outputColumnName: "data", interleavePixelColors: ImageNetSettings.channelsLast, offsetImage: ImageNetSettings.mean))
                            .Append(mlContext.Model.LoadTensorFlowModel(modelLocation).
                            ScoreTensorFlowModel(outputColumnNames: new[] { "fc8/Softmax" },
                                                inputColumnNames: new[] { "data" }, addBatchDimensionInput: true));

            ITransformer model = pipeline.Fit(data);

            var predictionEngine = mlContext.Model.CreatePredictionEngine<ImageNetData, ImageNetPrediction>(model);

            return predictionEngine;
        }

        protected IEnumerable<ImageNetData> PredictDataUsingModel(string testLocation,
                                                                  string imagesFolder,
                                                                  string labelsLocation,
                                                                  PredictionEngine<ImageNetData, ImageNetPrediction> model)
        {
            Console.WriteLine($"Images folder: {imagesFolder}");
            Console.WriteLine($"Training file: {testLocation}");
            Console.WriteLine($"Labels file: {labelsLocation}");


            var labels = ModelHelpers.ReadLabels(labelsLocation);

            var testData = ImageNetData.ReadFromCsv(testLocation, imagesFolder);

            foreach (var sample in testData)
            {
                var probs = model.Predict(sample);
                var imageData = new ImageNetDataProbability()
                {
                    ImagePath = sample.ImagePath,
                    Label = sample.Label
                };
                (imageData.PredictedLabel, imageData.Probability) = ModelHelpers.GetBestLabel(labels, probs.PredictedLabels);
                Console.WriteLine(imageData.PredictedLabel.ToString());
                yield return imageData;
            }
        }
    }
}`

Я получаю сообщение об ошибке в этой части программы:

foreach (var sample in testData)
                {
                    var probs = model.Predict(sample);
                    var imageData = new ImageNetDataProbability()
                    {
                        ImagePath = sample.ImagePath,
                        Label = sample.Label
                    };
                    (imageData.PredictedLabel, imageData.Probability) = ModelHelpers.GetBestLabel(labels, probs.PredictedLabels);
                    Console.WriteLine(imageData.PredictedLabel.ToString());
                    yield return imageData;
                }

...