Kurz: generování modelu klasifikace imagí ML.NET z předem připraveného modelu TensorFlowTutorial: Generate an ML.NET image classification model from a pre-trained TensorFlow model
Přečtěte si, jak přenést znalosti z existujícího modelu TensorFlow do nového modelu klasifikace imagí ML.NET.Learn how to transfer the knowledge from an existing TensorFlow model into a new ML.NET image classification model.
Model TensorFlow byl vyškolen pro klasifikaci imagí do tisíc kategorií.The TensorFlow model was trained to classify images into a thousand categories. Model ML.NET využívá část modelu TensorFlow ve svém kanálu k vytvoření modelu pro klasifikaci imagí do 3 kategorií.The ML.NET model makes use of part of the TensorFlow model in its pipeline to train a model to classify images into 3 categories.
Školení modelu klasifikace obrázků od začátku vyžaduje nastavení milionů parametrů, tunu školicích dat a obrovského množství výpočetních prostředků (stovky hodin GPU).Training an Image Classification model from scratch requires setting millions of parameters, a ton of labeled training data and a vast amount of compute resources (hundreds of GPU hours). I když není tak efektivní jako školení vlastního modelu od začátku, pomůže vám tento proces zástupcem pracovat s tisíci imagí. miliony imagí s popisky a sestavování vlastního modelu je poměrně rychlé (během hodiny na počítači bez GPU).While not as effective as training a custom model from scratch, transfer learning allows you to shortcut this process by working with thousands of images vs. millions of labeled images and build a customized model fairly quickly (within an hour on a machine without a GPU). Tento kurz škáluje ještě více procesů a používá jenom spoustu školicích imagí.This tutorial scales that process down even further, using only a dozen training images.
V tomto kurzu se naučíte:In this tutorial, you learn how to:
- Pochopení problémuUnderstand the problem
- Zahrňte předem vyškolený model TensorFlow do kanálu ML.NETIncorporate the pre-trained TensorFlow model into the ML.NET pipeline
- Výuka a vyhodnocení modelu ML.NETTrain and evaluate the ML.NET model
- Klasifikace testovací imageClassify a test image
Zdrojový kód pro tento kurz najdete v úložišti dotnet/Samples .You can find the source code for this tutorial at the dotnet/samples repository. Všimněte si, že ve výchozím nastavení je konfigurace projektu .NET pro tento kurz určena pro .NET Core 2,2.Note that by default, the .NET project configuration for this tutorial targets .NET core 2.2.
Co je učení přenosu?What is transfer learning?
Učení přenosu je proces použití znalostí získaných při řešení jednoho problému a jeho použití na jiný, ale související problém.Transfer learning is the process of using knowledge gained while solving one problem and applying it to a different but related problem.
Pro účely tohoto kurzu použijete část TensorFlow modelu vyškolená pro klasifikaci imagí do tisíc kategorií – v modelu ML.NET, který klasifikuje obrázky do 3 kategorií.For this tutorial, you use part of a TensorFlow model - trained to classify images into a thousand categories - in an ML.NET model that classifies images into 3 categories.
PožadavkyPrerequisites
- Visual Studio 2017 verze 15,6 nebo novější s nainstalovanou úlohou vývoj .NET Core pro různé platformy.Visual Studio 2017 version 15.6 or later with the ".NET Core cross-platform development" workload installed.
- Adresář assetů tutorial Soubor ZIPThe tutorial assets directory .ZIP file
- Model strojového učení InceptionV1The InceptionV1 machine learning model
Vyberte správnou úlohu strojového učení.Select the right machine learning task
Obsáhlý LearningDeep learning
Obsáhlý Learning je podmnožinou Machine Learning, což jsou revolutionizing oblasti, jako je počítačové zpracování obrazu a rozpoznávání řeči.Deep learning is a subset of Machine Learning, which is revolutionizing areas like Computer Vision and Speech Recognition.
Modely hloubkového učení jsou vyškoleny pomocí rozsáhlých sad dat s popisky a neuronové sítí , které obsahují více výukových vrstev.Deep learning models are trained by using large sets of labeled data and neural networks that contain multiple learning layers. Obsáhlý Learning:Deep learning:
- Je lepší pro některé úkoly, jako je Počítačové zpracování obrazu.Performs better on some tasks like Computer Vision.
- Vyžaduje velké množství školicích dat.Requires huge amounts of training data.
Klasifikace obrázku je běžný Machine Learning úkol, který nám umožňuje automaticky klasifikovat obrázky do kategorií, jako jsou:Image Classification is a common Machine Learning task that allows us to automatically classify images into categories such as:
- Zjištění lidského obličeje v obrázku nebo ne.Detecting a human face in an image or not.
- Detekce koček a psi.Detecting cats vs. dogs.
Nebo jak na následujících obrázcích zjistit, jestli je image a (n) jídla, hračka nebo zařízení:Or as in the following images, determining if an image is a(n) food, toy, or appliance:
Obrázek
Poznámka
Předchozí image patří do Wikimedia a jsou jim tyto atributy:The preceding images belong to Wikimedia Commons and are attributed as follows:
- Veřejná doména "220px-Pepperoni_pizza. jpg", https://commons.wikimedia.org/w/index.php?curid=79505"220px-Pepperoni_pizza.jpg" Public Domain, https://commons.wikimedia.org/w/index.php?curid=79505,
- "119px-Nalle_-a_small_brown_teddy_bear. jpg" pomocí Jonik – s použitím uživatelsky definovaných grafů, CC by-SA 2,0, https://commons.wikimedia.org/w/index.php?curid=48166."119px-Nalle-_a_small_brown_teddy_bear.jpg" By Jonik - Self-photographed, CC BY-SA 2.0, https://commons.wikimedia.org/w/index.php?curid=48166.
- "193px-Broodrooster. jpg" podle M. Minderhoud vlastní práce, CC by-sa 3,0, https://commons.wikimedia.org/w/index.php?curid=27403"193px-Broodrooster.jpg" By M.Minderhoud - Own work, CC BY-SA 3.0, https://commons.wikimedia.org/w/index.php?curid=27403
Inception model
je vyškolena pro klasifikaci imagí do tisíc kategorií, ale pro tento kurz je potřeba klasifikovat obrázky v menší sadě kategorií a jenom v těchto kategoriích.The Inception model
is trained to classify images into a thousand categories, but for this tutorial, you need to classify images in a smaller category set, and only those categories. Zadejte transfer
část transfer learning
.Enter the transfer
part of transfer learning
. Můžete přenést Inception model
schopnost rozpoznávat a klasifikovat obrázky pro nové kategorie omezené na vlastní třídění imagí.You can transfer the Inception model
's ability to recognize and classify images to the new limited categories of your custom image classifier.
- PotravinářstvíFood
- HračkToy
- NáplněAppliance
V tomto kurzu se používá model hloubkového učení modelu TensorFlow, který je oblíbený pro model rozpoznávání imagí, který je vyškolený pro ImageNet
datovou sadu.This tutorial uses the TensorFlow Inception model deep learning model, a popular image recognition model trained on the ImageNet
dataset. Model TensorFlow klasifikuje celé obrázky do tisíc tříd, například "deštník", "Jersey" a "myčku".The TensorFlow model classifies entire images into a thousand classes, such as “Umbrella”, “Jersey”, and “Dishwasher”.
Vzhledem k tomu, že Inception model
již byl předem vyškolen na tisících různých imagí, interně obsahuje funkce obrázků potřebné pro identifikaci obrázku.Because the Inception model
has already been pre trained on thousands of different images, internally it contains the image features needed for image identification. Pomocí těchto interních funkcí obrázků v modelu můžete vytvořit nový model s mnohem menším počtem tříd.We can make use of these internal image features in the model to train a new model with far fewer classes.
Jak je znázorněno v následujícím diagramu, přidáte odkaz na balíčky NuGet ML.NET v aplikacích .NET Core nebo .NET Framework.As shown in the following diagram, you add a reference to the ML.NET NuGet packages in your .NET Core or .NET Framework applications. V rámci zahrnutí ML.NET zahrnuje a odkazuje na nativní knihovnu TensorFlow
, která umožňuje napsat kód, který načte existující trained TensorFlow
ový soubor modelu.Under the covers, ML.NET includes and references the native TensorFlow
library that allows you to write code that loads an existing trained TensorFlow
model file.
klasifikace s více třídamiMulticlass classification
Po použití modelu TensorFlowho zahájení k extrakci funkcí vhodných jako vstup pro klasický algoritmus strojového učení přidáme ML.NET třídění s více třídami.After using the TensorFlow inception model to extract features suitable as input for a classical machine learning algorithm, we add an ML.NET multi-class classifier.
Konkrétní Trainer použitý v tomto případě je algoritmus MULTINOMIAL logistické regrese.The specific trainer used in this case is the multinomial logistic regression algorithm.
Algoritmus implementovaný tímto Trainer se dobře hodí v případě problémů s velkým počtem funkcí, což je případ pro model hloubkového učení, který pracuje s daty imagí.The algorithm implemented by this trainer performs well on problems with a large number of features, which is the case for a deep learning model operating on image data.
DataData
Existují dva zdroje dat: .tsv
soubor a soubory obrázků.There are two data sources: the .tsv
file, and the image files. tags.tsv
soubor obsahuje dva sloupce: první z nich je definována jako ImagePath
a druhá druhá Label
odpovídající imagi.The tags.tsv
file contains two columns: the first one is defined as ImagePath
and the second one is the Label
corresponding to the image. Následující ukázkový soubor neobsahuje řádek záhlaví a vypadá takto:The following example file doesn't have a header row, and looks like this:
broccoli.jpg food
pizza.jpg food
pizza2.jpg food
teddy2.jpg toy
teddy3.jpg toy
teddy4.jpg toy
toaster.jpg appliance
toaster2.png appliance
Obrázky školení a testování se nacházejí ve složkách assetů, které stáhnete do souboru ZIP.The training and testing images are located in the assets folders that you'll download in a zip file. Tyto image patří do Wikimedia.These images belong to Wikimedia Commons.
Wikimedia, bezplatné úložiště médií.Wikimedia Commons, the free media repository. Načteno 10:48, 17. října 2018 z: https://commons.wikimedia.org/wiki/Pizza https://commons.wikimedia.org/wiki/Toaster https://commons.wikimedia.org/wiki/Teddy_bearRetrieved 10:48, October 17, 2018 from: https://commons.wikimedia.org/wiki/Pizza https://commons.wikimedia.org/wiki/Toaster https://commons.wikimedia.org/wiki/Teddy_bear
NastaveníSetup
Vytvoření projektuCreate a project
Vytvořte konzolovou aplikaci .NET Core nazvanou "TransferLearningTF".Create a .NET Core Console Application called "TransferLearningTF".
Nainstalujte balíček NuGet Microsoft.ml:Install the Microsoft.ML NuGet Package:
- V Průzkumník řešení klikněte pravým tlačítkem na projekt a vyberte Spravovat balíčky NuGet.In Solution Explorer, right-click on your project and select Manage NuGet Packages.
- Jako zdroj balíčku zvolte "nuget.org", vyberte kartu Procházet a vyhledejte Microsoft.ml.Choose "nuget.org" as the Package source, select the Browse tab, search for Microsoft.ML.
- Klikněte na rozevírací seznam verze , v seznamu vyberte balíček 1.4.0 a vyberte tlačítko nainstalovat .Click on the Version drop-down, select the 1.4.0 package in the list, and select the Install button.
- V dialogovém okně Náhled změn vyberte tlačítko OK .Select the OK button on the Preview Changes dialog.
- Pokud souhlasíte s licenčními podmínkami pro uvedené balíčky, v dialogu pro přijetí licence vyberte tlačítko přijmout .Select the I Accept button on the License Acceptance dialog if you agree with the license terms for the packages listed.
- Opakujte tyto kroky pro Microsoft. ml. ImageAnalytics v 1.4.0, SciSharp. TensorFlow. Redist v 1.15.0 a Microsoft. ml. TensorFlow v 1.4.0.Repeat these steps for Microsoft.ML.ImageAnalytics v1.4.0, SciSharp.TensorFlow.Redist v1.15.0 and Microsoft.ML.TensorFlow v1.4.0.
Stažení prostředkůDownload assets
Stáhněte si soubor zip adresáře Project assetsa rozbalte ho.Download The project assets directory zip file, and unzip.
Zkopírujte adresář
assets
do adresáře projektu TransferLearningTF .Copy theassets
directory into your TransferLearningTF project directory. Tento adresář a jeho podadresáře obsahují data a podpůrné soubory (s výjimkou modelu zahájení, který si stáhnete a přidáte v dalším kroku) potřebném pro tento kurz.This directory and its subdirectories contain the data and support files (except for the Inception model, which you'll download and add in the next step) needed for this tutorial.Stáhněte si modelzahájení a rozbalte ho.Download the Inception model, and unzip.
Zkopírujte obsah
inception5h
adresáře do projektu TransferLearningTFassets/inception
Directory.Copy the contents of theinception5h
directory just unzipped into your TransferLearningTF projectassets/inception
directory. Tento adresář obsahuje model a další podpůrné soubory potřebné pro tento kurz, jak je znázorněno na následujícím obrázku:This directory contains the model and additional support files needed for this tutorial, as shown in the following image:V Průzkumník řešení klikněte pravým tlačítkem na každý ze souborů v adresáři assetů a podadresářích a vyberte vlastnosti.In Solution Explorer, right-click each of the files in the asset directory and subdirectories and select Properties. V části Upřesnitzměňte hodnotu Kopírovat do výstupního adresáře na Kopírovat, pokud je novější.Under Advanced, change the value of Copy to Output Directory to Copy if newer.
Vytváření tříd a definování cestCreate classes and define paths
Do horní části souboru program.cs přidejte následující další příkazy
using
:Add the following additionalusing
statements to the top of the Program.cs file:using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.ML; using Microsoft.ML.Data;
Přidejte následující kód na řádek vpravo nad
Main
metodou pro určení cest prostředků:Add the following code to the line right above theMain
method to specify the asset paths:static readonly string _assetsPath = Path.Combine(Environment.CurrentDirectory, "assets"); static readonly string _imagesFolder = Path.Combine(_assetsPath, "images"); static readonly string _trainTagsTsv = Path.Combine(_imagesFolder, "tags.tsv"); static readonly string _testTagsTsv = Path.Combine(_imagesFolder, "test-tags.tsv"); static readonly string _predictSingleImage = Path.Combine(_imagesFolder, "toaster3.jpg"); static readonly string _inceptionTensorFlowModel = Path.Combine(_assetsPath, "inception", "tensorflow_inception_graph.pb");
Vytvořte třídy pro vstupní data a předpovědi.Create classes for your input data, and predictions.
public class ImageData { [LoadColumn(0)] public string ImagePath; [LoadColumn(1)] public string Label; }
ImageData
je vstupní třída dat obrázku a má následující String pole:ImageData
is the input image data class and has the following String fields:ImagePath
obsahuje název souboru obrázku.ImagePath
contains the image file name.Label
obsahuje hodnotu pro popisek obrázku.Label
contains a value for the image label.
Přidejte do projektu novou třídu pro
ImagePrediction
:Add a new class to your project forImagePrediction
:public class ImagePrediction : ImageData { public float[] Score; public string PredictedLabelValue; }
ImagePrediction
je třída prediktivních imagí a má následující pole:ImagePrediction
is the image prediction class and has the following fields:Score
obsahuje procento spolehlivosti pro danou klasifikaci obrázku.Score
contains the confidence percentage for a given image classification.PredictedLabelValue
obsahuje hodnotu pro předpovězený popisek klasifikace obrázku.PredictedLabelValue
contains a value for the predicted image classification label.
ImagePrediction
je třída použitá pro předpověď po vyškolení modelu.ImagePrediction
is the class used for prediction after the model has been trained. Pro cestu k imagi mástring
(ImagePath
).It has astring
(ImagePath
) for the image path.Label
slouží k opakovanému použití a učení modelu.TheLabel
is used to reuse and train the model.PredictedLabelValue
se používá během předpovědi a vyhodnocení.ThePredictedLabelValue
is used during prediction and evaluation. Pro vyhodnocení se používají vstupy s daty o školení, předpovězené hodnoty a model.For evaluation, an input with training data, the predicted values, and the model are used.
Inicializovat proměnné v MainInitialize variables in Main
Inicializujte
mlContext
proměnnou novou instancíMLContext
.Initialize themlContext
variable with a new instance ofMLContext
. NahraďteConsole.WriteLine("Hello World!")
řádek následujícím kódem v metoděMain
:Replace theConsole.WriteLine("Hello World!")
line with the following code in theMain
method:MLContext mlContext = new MLContext();
Třída MLContext je výchozím bodem pro všechny operace ml.NET a inicializuje
mlContext
vytvoří nové prostředí ml.NET, které lze sdílet napříč objekty pracovního postupu vytváření modelů.The MLContext class is a starting point for all ML.NET operations, and initializingmlContext
creates a new ML.NET environment that can be shared across the model creation workflow objects. Je podobný a koncepčněDBContext
v Entity Framework.It's similar, conceptually, toDBContext
in Entity Framework.
Vytvoření struktury pro parametry modelu vytvářenéCreate a struct for Inception model parameters
Model zahájení má několik parametrů, které je třeba předat.The Inception model has several parameters you need to pass in. Vytvořte strukturu pro mapování hodnot parametrů na popisné názvy pomocí následujícího kódu, a to hned za
Main()
metodou:Create a struct to map the parameter values to friendly names with the following code, just after theMain()
method:private struct InceptionSettings { public const int ImageHeight = 224; public const int ImageWidth = 224; public const float Mean = 117; public const float Scale = 1; public const bool ChannelsLast = true; }
Vytvoření metody zobrazovacího nástrojeCreate a display utility method
Vzhledem k tomu, že zobrazíte data obrázku a související předpovědi více než jednou, vytvořte metodu zobrazení nástrojů pro zpracování zobrazení obrázků a výsledků předpovědi.Since you'll display the image data and the related predictions more than once, create a display utility method to handle displaying the image and prediction results.
Vytvořte metodu
DisplayResults()
hned poInceptionSettings
struktuře pomocí následujícího kódu:Create theDisplayResults()
method, just after theInceptionSettings
struct, using the following code:private static void DisplayResults(IEnumerable<ImagePrediction> imagePredictionData) { }
Vyplňte text
DisplayResults
metody:Fill in the body of theDisplayResults
method:foreach (ImagePrediction prediction in imagePredictionData) { Console.WriteLine($"Image: {Path.GetFileName(prediction.ImagePath)} predicted as: {prediction.PredictedLabelValue} with score: {prediction.Score.Max()} "); }
Vytvoření metody Utility souboru. TSVCreate a .tsv file utility method
Vytvořte metodu
ReadFromTsv()
hned za metodouDisplayResults()
pomocí následujícího kódu:Create theReadFromTsv()
method, just after theDisplayResults()
method, using the following code:public static IEnumerable<ImageData> ReadFromTsv(string file, string folder) { }
Vyplňte text
ReadFromTsv
metody:Fill in the body of theReadFromTsv
method:return File.ReadAllLines(file) .Select(line => line.Split('\t')) .Select(line => new ImageData() { ImagePath = Path.Combine(folder, line[0]) });
Kód analyzuje soubor
tags.tsv
, aby přidal cestu souboru k názvu souboru obrázku pro vlastnostImagePath
a načetl ji aLabel
do objektuImageData
.The code parses through thetags.tsv
file to add the file path to the image file name for theImagePath
property and load it and theLabel
into anImageData
object.
Vytvoření metody pro předpověďCreate a method to make a prediction
Vytvořte metodu
ClassifySingleImage()
těsně před metodouDisplayResults()
pomocí následujícího kódu:Create theClassifySingleImage()
method, just before theDisplayResults()
method, using the following code:public static void ClassifySingleImage(MLContext mlContext, ITransformer model) { }
Vytvořte objekt
ImageData
, který obsahuje plně kvalifikovanou cestu a název souboru obrázku pro jedenImagePath
.Create anImageData
object that contains the fully qualified path and image file name for the singleImagePath
. Přidejte následující kód jako další řádky v metoděClassifySingleImage()
:Add the following code as the next lines in theClassifySingleImage()
method:var imageData = new ImageData() { ImagePath = _predictSingleImage };
Udělejte jednu předpověď přidáním následujícího kódu jako další řádek v metodě
ClassifySingleImage
:Make a single prediction, by adding the following code as the next line in theClassifySingleImage
method:// Make prediction function (input = ImageData, output = ImagePrediction) var predictor = mlContext.Model.CreatePredictionEngine<ImageData, ImagePrediction>(model); var prediction = predictor.Predict(imageData);
K získání předpovědi použijte metodu předpověď () .To get the prediction, use the Predict() method. PredictionEngine je praktické rozhraní API, které umožňuje provádět předpovědi pro jednu instanci dat.The PredictionEngine is a convenience API, which allows you to perform a prediction on a single instance of data.
PredictionEngine
není bezpečný pro přístup z více vláken.PredictionEngine
is not thread-safe. Je přijatelné pro použití v prostředích s jedním vláknem nebo prototypem.It's acceptable to use in single-threaded or prototype environments. Pro zvýšení výkonu a bezpečnosti vláken v produkčních prostředích použijte službuPredictionEnginePool
, která vytvoříObjectPool
objektůPredictionEngine
pro použití v celé aplikaci.For improved performance and thread safety in production environments, use thePredictionEnginePool
service, which creates anObjectPool
ofPredictionEngine
objects for use throughout your application. V této příručce najdete informace o tom, jak používatPredictionEnginePool
ve ASP.NET corem webovém rozhraní API.See this guide on how to usePredictionEnginePool
in an ASP.NET Core Web API.Poznámka
rozšíření služby
PredictionEnginePool
je aktuálně ve verzi Preview.PredictionEnginePool
service extension is currently in preview.Zobrazit výsledek předpovědi jako další řádek kódu v metodě
ClassifySingleImage()
:Display the prediction result as the next line of code in theClassifySingleImage()
method:Console.WriteLine($"Image: {Path.GetFileName(imageData.ImagePath)} predicted as: {prediction.PredictedLabelValue} with score: {prediction.Score.Max()} ");
Vytvoření kanálu modelu ML.NETConstruct the ML.NET model pipeline
Kanál ML.NET modelu je řetězec odhady.An ML.NET model pipeline is a chain of estimators. Všimněte si, že během vytváření kanálu nedojde k žádnému spuštění.Note that no execution happens during pipeline construction. Objekty Estimator jsou vytvořeny, ale nejsou spuštěny.The estimator objects are created but not executed.
Přidejte metodu pro vytvoření modeluAdd a method to generate the model
Tato metoda je srdcem kurzu.This method is the heart of the tutorial. Vytvoří kanál pro model a navlakuje kanál k vytvoření modelu ML.NET.It creates a pipeline for the model, and trains the pipeline to produce the ML.NET model. Vyhodnocuje také model proti dříve nezobrazeným datům testu.It also evaluates the model against some previously unseen test data.
Vytvořte metodu
GenerateModel()
hned poInceptionSettings
struktuře a těsně před metodouDisplayResults()
pomocí následujícího kódu:Create theGenerateModel()
method, just after theInceptionSettings
struct and just before theDisplayResults()
method, using the following code:public static ITransformer GenerateModel(MLContext mlContext) { }
Přidat odhady pro načtení, změnu velikosti a extrakci pixelů z dat obrázku:Add the estimators to load, resize and extract the pixels from the image data:
IEstimator<ITransformer> pipeline = mlContext.Transforms.LoadImages(outputColumnName: "input", imageFolder: _imagesFolder, inputColumnName: nameof(ImageData.ImagePath)) // The image transforms transform the images into the model's expected format. .Append(mlContext.Transforms.ResizeImages(outputColumnName: "input", imageWidth: InceptionSettings.ImageWidth, imageHeight: InceptionSettings.ImageHeight, inputColumnName: "input")) .Append(mlContext.Transforms.ExtractPixels(outputColumnName: "input", interleavePixelColors: InceptionSettings.ChannelsLast, offsetImage: InceptionSettings.Mean))
Data obrázku musí být zpracována ve formátu, který očekává model TensorFlow.The image data needs to be processed into the format that the TensorFlow model expects. V tomto případě jsou obrázky načteny do paměti, jsou změněna na konzistentní velikost a pixely jsou extrahovány do číselného vektoru.In this case, the images are loaded into memory, resized to a consistent size, and the pixels are extracted into a numeric vector.
Přidejte Estimator, abyste načetli model TensorFlow, a zadávejte skóre:Add the estimator to load the TensorFlow model, and score it:
.Append(mlContext.Model.LoadTensorFlowModel(_inceptionTensorFlowModel). ScoreTensorFlowModel(outputColumnNames: new[] { "softmax2_pre_activation" }, inputColumnNames: new[] { "input" }, addBatchDimensionInput: true))
Tato fáze v kanálu načte model TensorFlow do paměti a pak zpracovává vektor hodnot obrazových bodů prostřednictvím sítě modelu TensorFlow.This stage in the pipeline loads the TensorFlow model into memory, then processes the vector of pixel values through the TensorFlow model network. Použití vstupů na model hloubkového učení a generování výstupu pomocí modelu se označuje jako bodování.Applying inputs to a deep learning model, and generating an output using the model, is referred to as Scoring. Při použití modelu v celém rozsahu je bodování odvozeno nebo předpověď.When using the model in its entirety, scoring makes an inference, or prediction.
V tomto případě použijete všechen TensorFlow model kromě poslední vrstvy, což je vrstva, která provádí odvození.In this case, you use all of the TensorFlow model except the last layer, which is the layer that makes the inference. Výstup předposlední vrstvy je označený
softmax_2_preactivation
.The output of the penultimate layer is labeledsoftmax_2_preactivation
. Výstup této vrstvy je efektivně vektor funkcí, které charakterizují původní vstupní image.The output of this layer is effectively a vector of features that characterize the original input images.Tento vektor funkce generovaný modelem TensorFlow se použije jako vstup pro školicí algoritmus ML.NET.This feature vector generated by the TensorFlow model will be used as input to an ML.NET training algorithm.
Přidejte Estimator k namapování popisků řetězce v školicích datech na hodnoty celočíselného klíče:Add the estimator to map the string labels in the training data to integer key values:
.Append(mlContext.Transforms.Conversion.MapValueToKey(outputColumnName: "LabelKey", inputColumnName: "Label"))
ML.NET Trainer, který je připojen k dalšímu, vyžaduje, aby popisky byly v
key
formátu místo libovolných řetězců.The ML.NET trainer that is appended next requires its labels to be inkey
format rather than arbitrary strings. Klíč je číslo, které má jeden k jednomu mapování na hodnotu řetězce.A key is a number that has a one to one mapping to a string value.Přidejte ML.NET školicí algoritmus:Add the ML.NET training algorithm:
.Append(mlContext.MulticlassClassification.Trainers.LbfgsMaximumEntropy(labelColumnName: "LabelKey", featureColumnName: "softmax2_pre_activation"))
Přidejte Estimator k namapování hodnoty předpovězeného klíče zpátky do řetězce:Add the estimator to map the predicted key value back into a string:
.Append(mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabelValue", "PredictedLabel")) .AppendCacheCheckpoint(mlContext);
Trénování modeluTrain the model
Načtěte školicí data pomocí obálky LoadFromTextFile .Load the training data using the LoadFromTextFile wrapper. Přidejte následující kód jako další řádek v metodě
GenerateModel()
:Add the following code as the next line in theGenerateModel()
method:IDataView trainingData = mlContext.Data.LoadFromTextFile<ImageData>(path: _trainTagsTsv, hasHeader: false);
Data v ML.NET jsou reprezentována jako Třída IDataView.Data in ML.NET is represented as an IDataView class.
IDataView
je flexibilní a efektivní způsob popisující tabulková data (číselná a text).IDataView
is a flexible, efficient way of describing tabular data (numeric and text). Data je možné načíst z textového souboru nebo v reálném čase (například databáze SQL nebo soubory protokolu) do objektuIDataView
.Data can be loaded from a text file or in real time (for example, SQL database or log files) to anIDataView
object.Vyškolit model s daty načtenými výše:Train the model with the data loaded above:
ITransformer model = pipeline.Fit(trainingData);
Metoda
Fit()
navlakuje váš model použitím školicí datové sady na kanál.TheFit()
method trains your model by applying the training dataset to the pipeline.
Vyhodnotit přesnost modeluEvaluate the accuracy of the model
Načtěte a Transformujte testovací data přidáním následujícího kódu na další řádek metody
GenerateModel
:Load and transform the test data, by adding the following code to the next line of theGenerateModel
method:IDataView testData = mlContext.Data.LoadFromTextFile<ImageData>(path: _testTagsTsv, hasHeader: false); IDataView predictions = model.Transform(testData); // Create an IEnumerable for the predictions for displaying results IEnumerable<ImagePrediction> imagePredictionData = mlContext.Data.CreateEnumerable<ImagePrediction>(predictions, true); DisplayResults(imagePredictionData);
Existuje několik ukázkových imagí, které můžete použít k vyhodnocení modelu.There are a few sample images that you can use to evaluate the model. Podobně jako u školicích dat je potřeba je načíst do
IDataView
, aby je bylo možné transformovat podle modelu.Like the training data, these need to be loaded into anIDataView
, so that they can be transformed by the model.Přidejte následující kód do metody
GenerateModel()
pro vyhodnocení modelu:Add the following code to theGenerateModel()
method to evaluate the model:MulticlassClassificationMetrics metrics = mlContext.MulticlassClassification.Evaluate(predictions, labelColumnName: "LabelKey", predictedLabelColumnName: "PredictedLabel");
Jakmile máte předsadu předpovědi, metoda Evaluate () :Once you have the prediction set, the Evaluate() method:
- Vyhodnotí model (porovná předpovězené hodnoty s testovací datovou sadou
labels
).Assesses the model (compares the predicted values with the test datasetlabels
). - Vrátí metriku výkonu modelu.Returns the model performance metrics.
- Vyhodnotí model (porovná předpovězené hodnoty s testovací datovou sadou
Zobrazit metriky přesnosti modeluDisplay the model accuracy metrics
Použijte následující kód k zobrazení metrik, sdílení výsledků a pak jejich fungování:Use the following code to display the metrics, share the results, and then act on them:
Console.WriteLine($"LogLoss is: {metrics.LogLoss}"); Console.WriteLine($"PerClassLogLoss is: {String.Join(" , ", metrics.PerClassLogLoss.Select(c => c.ToString()))}");
Pro klasifikaci imagí jsou vyhodnocovány následující metriky:The following metrics are evaluated for image classification:
Log-loss
– viz prohra protokolu.Log-loss
- see Log Loss. Chcete, aby byla ztráta protokolu co nejblíže k nule.You want Log-loss to be as close to zero as possible.Per class Log-loss
.Per class Log-loss
. Požadujete, aby byla ztráta protokolu podle třídy co nejblíže k nule.You want per class Log-loss to be as close to zero as possible.
Přidejte následující kód, který vrátí vycvičený model jako další řádek:Add the following code to return the trained model as the next line:
return model;
Spusťte aplikaci!Run the application!
Přidejte volání
GenerateModel
v metoděMain
po vytvoření třídy MLContext:Add the call toGenerateModel
in theMain
method after the creation of the MLContext class:ITransformer model = GenerateModel(mlContext);
Přidejte volání metody
ClassifySingleImage()
jako další řádek kódu v metoděMain
:Add the call to theClassifySingleImage()
method as the next line of code in theMain
method:ClassifySingleImage(mlContext, model);
Spusťte konzolovou aplikaci (CTRL + F5).Run your console app (Ctrl + F5). Výsledky by měly být podobné následujícímu výstupu.Your results should be similar to the following output. Můžou se zobrazovat upozornění nebo zprávy o zpracování, ale tyto zprávy se z následujících výsledků odebraly z důvodu srozumitelnosti.You may see warnings or processing messages, but these messages have been removed from the following results for clarity.
=============== Training classification model =============== Image: broccoli2.jpg predicted as: food with score: 0.8955513 Image: pizza3.jpg predicted as: food with score: 0.9667718 Image: teddy6.jpg predicted as: toy with score: 0.9797683 =============== Classification metrics =============== LogLoss is: 0.0653774699265059 PerClassLogLoss is: 0.110315812569315 , 0.0204391272836966 , 0 =============== Making single image classification =============== Image: toaster3.jpg predicted as: appliance with score: 0.9646884
Blahopřejeme!Congratulations! Teď jste úspěšně vytvořili model strojového učení pro klasifikaci imagí tím, že použijete učení přenosu na TensorFlow
model v ML.NET.You've now successfully built a machine learning model for image classification by applying transfer learning to a TensorFlow
model in ML.NET.
Zdrojový kód pro tento kurz najdete v úložišti dotnet/Samples .You can find the source code for this tutorial at the dotnet/samples repository.
V tomto kurzu jste se naučili:In this tutorial, you learned how to:
- Pochopení problémuUnderstand the problem
- Zahrňte předem vyškolený model TensorFlow do kanálu ML.NETIncorporate the pre-trained TensorFlow model into the ML.NET pipeline
- Výuka a vyhodnocení modelu ML.NETTrain and evaluate the ML.NET model
- Klasifikace testovací imageClassify a test image
Podívejte se na úložiště GitHub Samples Machine Learning a prozkoumejte ukázku klasifikace rozbalené image.Check out the Machine Learning samples GitHub repository to explore an expanded image classification sample.
Váš názor
Načítání názorů...