Didacticiel : analyser le sentiment de commentaires de site Web avec classification binaire dans ML.NETTutorial: Analyze sentiment of website comments with binary classification in ML.NET

Ce tutoriel vous montre comment créer une application console .NET Core qui classifie les sentiments analysés dans les commentaires des sites web et qui exécute l’action appropriée.This tutorial shows you how to create a .NET Core console application that classifies sentiment from website comments and takes the appropriate action. Le classifieur binaire de sentiments utilise C# dans Visual Studio 2017.The binary sentiment classifier uses C# in Visual Studio 2017.

Dans ce tutoriel, vous allez apprendre à :In this tutorial, you learn how to:

  • Création d’une application consoleCreate a console application
  • Préparer les donnéesPrepare data
  • Chargement des donnéesLoad the data
  • Générer et entraîner le modèleBuild and train the model
  • Évaluer le modèleEvaluate the model
  • Utiliser le modèle pour effectuer une prédictionUse the model to make a prediction
  • Afficher les résultatsSee the results

Vous trouverez le code source de ce tutoriel dans le référentiel dotnet/samples.You can find the source code for this tutorial at the dotnet/samples repository.

PrérequisPrerequisites

Création d’une application consoleCreate a console application

  1. Créez une application console .NET Core appelée « SentimentAnalysis ».Create a .NET Core Console Application called "SentimentAnalysis".

  2. Créez un répertoire nommé Data dans votre projet pour enregistrer les fichiers de votre jeu de données.Create a directory named Data in your project to save your data set files.

  3. Installez le package NuGet Microsoft.ML :Install the Microsoft.ML NuGet Package:

    Notes

    Cet exemple utilise la dernière version stable des packages NuGet mentionnés, sauf indication contraire.This sample uses the latest stable version of the NuGet packages mentioned unless otherwise stated.

    Dans Explorateur de solutions, cliquez avec le bouton droit sur votre projet et sélectionnez gérer les packages NuGet.In Solution Explorer, right-click on your project and select Manage NuGet Packages. Choisissez « nuget.org » comme source du package, puis sélectionnez l’onglet Parcourir . recherchez Microsoft.ml, sélectionnez le package souhaité, puis cliquez sur le bouton installer .Choose "nuget.org" as the package source, and then select the Browse tab. Search for Microsoft.ML, select the package you want, and then select the Install button. Poursuivez l’installation en acceptant les termes du contrat de licence pour le package choisi.Proceed with the installation by agreeing to the license terms for the package you choose.

Préparer vos donnéesPrepare your data

Notes

Les jeux de données utilisés dans ce tutoriel proviennent de « From Group to Individual Labels using Deep Features » (Kotzias et.The datasets for this tutorial are from the 'From Group to Individual Labels using Deep Features', Kotzias et. al.,al,. KDD 2015 et hébergé dans le référentiel Machine Learning UCI-Dua, D. et karra Taniskidou, E. (2017).KDD 2015, and hosted at the UCI Machine Learning Repository - Dua, D. and Karra Taniskidou, E. (2017). Référentiel UCI Machine Learning [http://archive.ics.uci.edu/ml].UCI Machine Learning Repository [http://archive.ics.uci.edu/ml]. Irvine, CA: University of California, School of Information and Computer Science.Irvine, CA: University of California, School of Information and Computer Science.

  1. Téléchargez le fichier zip du jeu de données UCI Sentiment Labeled Sentences, puis décompressez-le.Download UCI Sentiment Labeled Sentences dataset ZIP file, and unzip.

  2. Copiez le fichier yelp_labelled.txt dans le répertoire Données que vous avez créé.Copy the yelp_labelled.txt file into the Data directory you created.

  3. Dans l’Explorateur de solutions, cliquez avec le bouton droit sur le fichier yelp_labeled.txt et sélectionnez Propriétés.In Solution Explorer, right-click the yelp_labeled.txt file and select Properties. Sous avancé, remplacez la valeur de copier dans le répertoire de sortie par copier si plus récent.Under Advanced, change the value of Copy to Output Directory to Copy if newer.

Créer des classes et définir des cheminsCreate classes and define paths

  1. Ajoutez les instructions using supplémentaires suivantes en haut du fichier Program.cs : Add the following additional using 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;
    using static Microsoft.ML.DataOperationsCatalog;
    using Microsoft.ML.Trainers;
    using Microsoft.ML.Transforms.Text;
    
  2. Ajoutez le code suivant à la ligne située juste au-dessus de la Main méthode, pour créer un champ qui contiendra le chemin d’accès au fichier de jeu de données téléchargé récemment :Add the following code to the line right above the Main method, to create a field to hold the recently downloaded dataset file path:

    static readonly string _dataPath = Path.Combine(Environment.CurrentDirectory, "Data", "yelp_labelled.txt");
    
  3. Créez ensuite des classes pour les données d’entrée et les prédictions.Next, create classes for your input data and predictions. Ajoutez une nouvelle classe à votre projet :Add a new class to your project:

    • Dans l’Explorateur de solutions, cliquez avec le bouton droit sur le projet, puis sélectionnez Ajouter > Nouvel élément.In Solution Explorer, right-click the project, and then select Add > New Item.

    • Dans la boîte de dialogue Ajouter un nouvel élément, sélectionnez Classe, puis remplacez la valeur du champ Nom par SentimentData.cs.In the Add New Item dialog box, select Class and change the Name field to SentimentData.cs. Ensuite, sélectionnez le bouton Ajouter.Then, select the Add button.

  4. Le fichier SentimentData.cs s’ouvre dans l’éditeur de code.The SentimentData.cs file opens in the code editor. Ajoutez l'instruction suivante using en haut du fichier SentimentData.cs :Add the following using statement to the top of SentimentData.cs:

    using Microsoft.ML.Data;
    
  5. Supprimez la définition de classe existante et ajoutez le code suivant, qui contient deux classes, SentimentData et SentimentPrediction, au fichier SentimentData.cs :Remove the existing class definition and add the following code, which has two classes SentimentData and SentimentPrediction, to the SentimentData.cs file:

    public class SentimentData
    {
        [LoadColumn(0)]
        public string SentimentText;
    
        [LoadColumn(1), ColumnName("Label")]
        public bool Sentiment;
    }
    
    public class SentimentPrediction : SentimentData
    {
    
        [ColumnName("PredictedLabel")]
        public bool Prediction { get; set; }
    
        public float Probability { get; set; }
    
        public float Score { get; set; }
    }
    

Comment les données ont-elles été préparées ?How the data was prepared

La classe du jeu de données d’entrée, SentimentData, a une valeur string pour les commentaires utilisateur (SentimentText) et une valeur bool (Sentiment) égale à 1 (sentiment positif) ou 0 (sentiment négatif).The input dataset class, SentimentData, has a string for user comments (SentimentText) and a bool (Sentiment) value of either 1 (positive) or 0 (negative) for sentiment. Les deux champs ont des attributs LoadColumn associés, qui spécifient l’ordre du fichier de données de chaque champ.Both fields have LoadColumn attributes attached to them, which describes the data file order of each field. Par ailleurs, la propriété Sentiment a un attribut ColumnName qui la désigne comme champ Label.In addition, the Sentiment property has a ColumnName attribute to designate it as the Label field. L’exemple de fichier suivant ne possède pas de ligne d’en-tête :The following example file doesn't have a header row, and looks like this:

SentimentTextSentimentText Sentiment (Label)Sentiment (Label)
La serveuse était un peu lente durant le service.Waitress was a little slow in service. 00
La pâte n’est pas bonne.Crust is not good. 00
... J’ai aimé cet endroit.Wow... Loved this place. 11
Le service a été très rapide.Service was very prompt. 11

SentimentPrediction est la classe de prédiction utilisée après l’entraînement du modèle.SentimentPrediction is the prediction class used after model training. Elle hérite de SentimentData afin que l’entrée SentimentText puisse être affichée en même temps que la prédiction de sortie.It inherits from SentimentData so that the input SentimentText can be displayed along with the output prediction. La valeur booléenne Prediction est la valeur que le modèle prédit quand la nouvelle entrée SentimentText lui est fournie.The Prediction boolean is the value that the model predicts when supplied with new input SentimentText.

La classe de sortie SentimentPrediction contient deux autres propriétés calculées par le modèle : Score, le score brut calculé par le modèle, et Probability, le score étalonné à la probabilité que le texte ait un sentiment positif.The output class SentimentPrediction contains two other properties calculated by the model: Score - the raw score calculated by the model, and Probability - the score calibrated to the likelihood of the text having positive sentiment.

Pour ce tutoriel, la propriété la plus importante est Prediction.For this tutorial, the most important property is Prediction.

Chargement des donnéesLoad the data

Les données dans ML.NET sont représentées en tant que classe IDataView.Data in ML.NET is represented as an IDataView class. IDataView est un moyen flexible et efficace de décrire des données tabulaires (numériques et texte).IDataView is a flexible, efficient way of describing tabular data (numeric and text). Les données peuvent être chargées à partir d’un fichier texte ou en temps réel (par exemple, fichiers journaux ou de base de données SQL) dans un objet IDataView.Data can be loaded from a text file or in real time (for example, SQL database or log files) to an IDataView object.

La classe MLContext constitue un point de départ pour toutes les opérations ML.NET.The MLContext class is a starting point for all ML.NET operations. L’initialisation de mlContext crée un environnement ML.NET qui peut être partagé par les objets du workflow de création de modèle.Initializing mlContext creates a new ML.NET environment that can be shared across the model creation workflow objects. Sur le plan conceptuel, elle est similaire à DBContext dans Entity Framework.It's similar, conceptually, to DBContext in Entity Framework.

Vous préparez l’application et chargez ensuite les données :You prepare the app, and then load data:

  1. Remplacez la ligne Console.WriteLine("Hello World!") dans la méthode Main par le code suivant pour déclarer et initialiser la variable mlContext :Replace the Console.WriteLine("Hello World!") line in the Main method with the following code to declare and initialize the mlContext variable:

    MLContext mlContext = new MLContext();
    
  2. Ajoutez le code suivant comme prochaine ligne dans la méthode Main() :Add the following as the next line of code in the Main() method:

    TrainTestData splitDataView = LoadData(mlContext);
    
  3. Créez la méthode LoadData() juste après la méthode Main(), en utilisant le code suivant :Create the LoadData() method, just after the Main() method, using the following code:

    public static TrainTestData LoadData(MLContext mlContext)
    {
    
    }
    

    La méthode LoadData() exécute les tâches suivantes :The LoadData() method executes the following tasks:

    • Charge les données.Loads the data.
    • Fractionne le jeu de données chargé en jeux de données d’apprentissage et de test.Splits the loaded dataset into train and test datasets.
    • Retourne les jeux de données d’apprentissage et de test fractionnés.Returns the split train and test datasets.
  4. Ajoutez le code suivant comme première ligne de la méthode LoadData() :Add the following code as the first line of the LoadData() method:

    IDataView dataView = mlContext.Data.LoadFromTextFile<SentimentData>(_dataPath, hasHeader: false);
    

    La méthode LoadFromTextFile () définit le schéma de données et lit le fichier.The LoadFromTextFile() method defines the data schema and reads in the file. Elle prend les variables de chemin de données et retourne un IDataView.It takes in the data path variables and returns an IDataView.

Fractionner le jeu de données pour l’apprentissage et le test du modèleSplit the dataset for model training and testing

Quand vous préparez un modèle, vous utilisez une partie du jeu de données pour entraîner le modèle et une partie du jeu de données pour tester la précision du modèle.When preparing a model, you use part of the dataset to train it and part of the dataset to test the model's accuracy.

  1. Pour fractionner les données chargées dans les jeux de données nécessaires, ajoutez le code suivant sur la ligne suivant la méthode LoadData() :To split the loaded data into the needed datasets, add the following code as the next line in the LoadData() method:

    TrainTestData splitDataView = mlContext.Data.TrainTestSplit(dataView, testFraction: 0.2);
    

    Le code précédent utilise la méthode TrainTestSplit () pour fractionner le DataSet chargé en jeux de données d’apprentissage et de test et les retourner dans la DataOperationsCatalog.TrainTestData classe.The previous code uses the TrainTestSplit() method to split the loaded dataset into train and test datasets and return them in the DataOperationsCatalog.TrainTestData class. Spécifiez le pourcentage de données du jeu de test avec le paramètre testFraction.Specify the test set percentage of data with the testFractionparameter. La valeur par défaut est 10 %, mais dans cet exemple, vous spécifiez 20 % pour évaluer davantage de données.The default is 10%, in this case you use 20% to evaluate more data.

  2. Retournez splitDataView à la fin de la méthode LoadData() :Return the splitDataView at the end of the LoadData() method:

    return splitDataView;
    

Générer et entraîner le modèleBuild and train the model

  1. Ajoutez l’appel suivant à la méthode BuildAndTrainModel comme prochaine ligne de code dans la méthode Main() :Add the following call to the BuildAndTrainModelmethod as the next line of code in the Main() method:

    ITransformer model = BuildAndTrainModel(mlContext, splitDataView.TrainSet);
    

    La méthode BuildAndTrainModel() exécute les tâches suivantes :The BuildAndTrainModel() method executes the following tasks:

    • Extrait et transforme les données.Extracts and transforms the data.
    • Effectue l’apprentissage du modèle.Trains the model.
    • Prédit les sentiments en fonction des données de test.Predicts sentiment based on test data.
    • Retourne le modèle.Returns the model.
  2. Créez la méthode BuildAndTrainModel() juste après la méthode Main(), en utilisant le code suivant :Create the BuildAndTrainModel() method, just after the Main() method, using the following code:

    public static ITransformer BuildAndTrainModel(MLContext mlContext, IDataView splitTrainSet)
    {
    
    }
    

Extraire et transformer les donnéesExtract and transform the data

  1. Appelez FeaturizeText sur la ligne de code suivante :Call FeaturizeText as the next line of code:

    var estimator = mlContext.Transforms.Text.FeaturizeText(outputColumnName: "Features", inputColumnName: nameof(SentimentData.SentimentText))
    

    La méthode FeaturizeText() dans le code précédent convertit la colonne de texte (SentimentText) en une colonne Features de type clé numérique, qui est utilisée par l’algorithme de machine learning, et l’ajoute comme nouvelle colonne au jeu de données :The FeaturizeText() method in the previous code converts the text column (SentimentText) into a numeric key type Features column used by the machine learning algorithm and adds it as a new dataset column:

    SentimentTextSentimentText SentimentsSentiment FonctionnalitésFeatures
    La serveuse était un peu lente durant le service.Waitress was a little slow in service. 00 [0.76, 0.65, 0.44, …][0.76, 0.65, 0.44, …]
    La pâte n’est pas bonne.Crust is not good. 00 [0.98, 0.43, 0.54, …][0.98, 0.43, 0.54, …]
    ... J’ai aimé cet endroit.Wow... Loved this place. 11 [0.35, 0.73, 0.46, …][0.35, 0.73, 0.46, …]
    Le service a été très rapide.Service was very prompt. 11 [0.39, 0, 0.75, …][0.39, 0, 0.75, …]

Ajouter un algorithme d’apprentissageAdd a learning algorithm

Cette application utilise un algorithme de classification qui classe les éléments ou lignes de données.This app uses a classification algorithm that categorizes items or rows of data. Elle classe les commentaires des sites web comme positifs ou négatifs. Vous devez donc utiliser la tâche de classification binaire.The app categorizes website comments as either positive or negative, so use the binary classification task.

Ajoutez la tâche de machine learning aux définitions de transformations des données en ajoutant la ligne de code suivante dans BuildAndTrainModel() :Append the machine learning task to the data transformation definitions by adding the following as the next line of code in BuildAndTrainModel():

.Append(mlContext.BinaryClassification.Trainers.SdcaLogisticRegression(labelColumnName: "Label", featureColumnName: "Features"));

SdcaLogisticRegressionBinaryTrainer est votre algorithme d’entraînement de classification.The SdcaLogisticRegressionBinaryTrainer is your classification training algorithm. Il est ajouté à estimator et accepte les caractéristiques SentimentText (Features) ainsi que les paramètres d’entrée Label pour apprendre à partir des données d’historique.This is appended to the estimator and accepts the featurized SentimentText (Features) and the Label input parameters to learn from the historic data.

Effectuer l’apprentissage du modèleTrain the model

Ajustez le modèle aux données splitTrainSet et retournez le modèle entraîné en ajoutant la ligne de code suivante dans la méthode BuildAndTrainModel() :Fit the model to the splitTrainSet data and return the trained model by adding the following as the next line of code in the BuildAndTrainModel() method:

Console.WriteLine("=============== Create and Train the Model ===============");
var model = estimator.Fit(splitTrainSet);
Console.WriteLine("=============== End of training ===============");
Console.WriteLine();

La méthode Fit() entraîne votre modèle en transformant le jeu de données et en appliquant l’entraînement.The Fit() method trains your model by transforming the dataset and applying the training.

Retourner le modèle entraîné à utiliser pour l’évaluationReturn the model trained to use for evaluation

Retournez le modèle à la fin de la méthode BuildAndTrainModel() :Return the model at the end of the BuildAndTrainModel() method:

return model;

Évaluer le modèleEvaluate the model

Une fois que votre modèle est entraîné, vérifiez ses performances avec vos données de test.After your model is trained, use your test data validate the model's performance.

  1. Créez la méthode Evaluate() juste après BuildAndTrainModel(), en utilisant le code suivant :Create the Evaluate() method, just after BuildAndTrainModel(), with the following code:

    public static void Evaluate(MLContext mlContext, ITransformer model, IDataView splitTestSet)
    {
    
    }
    

    La méthode Evaluate() exécute les tâches suivantes :The Evaluate() method executes the following tasks:

    • Charge le jeu de données de test.Loads the test dataset.
    • Crée l’évaluateur BinaryClassification.Creates the BinaryClassification evaluator.
    • Évalue le modèle et crée des métriques.Evaluates the model and creates metrics.
    • Affiche les métriques.Displays the metrics.
  2. Ajoutez un appel à la nouvelle méthode à partir de la méthode Main(), juste sous l’appel à la méthode BuildAndTrainModel(), en utilisant le code suivant :Add a call to the new method from the Main() method, right under the BuildAndTrainModel() method call, using the following code:

    Evaluate(mlContext, model, splitDataView.TestSet);
    
  3. Transformez les données splitTestSet en ajoutant le code suivant à Evaluate() :Transform the splitTestSet data by adding the following code to Evaluate():

    Console.WriteLine("=============== Evaluating Model accuracy with Test data===============");
    IDataView predictions = model.Transform(splitTestSet);
    

    Le code précédent utilise la méthode Transform() pour prédire plusieurs lignes d’entrée d’un jeu de données de test.The previous code uses the Transform() method to make predictions for multiple provided input rows of a test dataset.

  4. Évaluez le modèle en ajoutant la ligne de code suivante dans la méthode Evaluate() :Evaluate the model by adding the following as the next line of code in the Evaluate() method:

    CalibratedBinaryClassificationMetrics metrics = mlContext.BinaryClassification.Evaluate(predictions, "Label");
    

Une fois que vous avez le jeu de prédiction (predictions), la méthode Evaluate() évalue le modèle : elle compare les valeurs prédites aux valeurs Labels réelles dans le jeu de données de test et retourne un objet CalibratedBinaryClassificationMetrics contenant les métriques relatives aux performances du modèle.Once you have the prediction set (predictions), the Evaluate() method assesses the model, which compares the predicted values with the actual Labels in the test dataset and returns a CalibratedBinaryClassificationMetrics object on how the model is performing.

Affichage des métriques pour la validation du modèleDisplaying the metrics for model validation

Utilisez le code suivant pour afficher les métriques :Use the following code to display the metrics:

Console.WriteLine();
Console.WriteLine("Model quality metrics evaluation");
Console.WriteLine("--------------------------------");
Console.WriteLine($"Accuracy: {metrics.Accuracy:P2}");
Console.WriteLine($"Auc: {metrics.AreaUnderRocCurve:P2}");
Console.WriteLine($"F1Score: {metrics.F1Score:P2}");
Console.WriteLine("=============== End of model evaluation ===============");
  • La métrique Accuracy donne la précision du modèle, qui correspond à la proportion de prédictions correctes dans le jeu de test.The Accuracy metric gets the accuracy of a model, which is the proportion of correct predictions in the test set.

  • La métrique AreaUnderRocCurve indique le degré de confiance conféré aux résultats de la classification des classes positif/négatif.The AreaUnderRocCurve metric indicates how confident the model is correctly classifying the positive and negative classes. Vous voulez que la métrique AreaUnderRocCurve soit le plus proche possible de la valeur 1.You want the AreaUnderRocCurve to be as close to one as possible.

  • La métrique F1Score donne le score F1 du modèle, qui mesure l’équilibre entre la précision et le rappel.The F1Score metric gets the model's F1 score, which is a measure of balance between precision and recall. Vous voulez que la métrique F1Score soit le plus proche possible de la valeur 1.You want the F1Score to be as close to one as possible.

Prédire les résultats des données de testPredict the test data outcome

  1. Créez la méthode UseModelWithSingleItem() juste après la méthode Evaluate(), en utilisant le code suivant :Create the UseModelWithSingleItem() method, just after the Evaluate() method, using the following code:

    private static void UseModelWithSingleItem(MLContext mlContext, ITransformer model)
    {
    
    }
    

    La méthode UseModelWithSingleItem() exécute les tâches suivantes :The UseModelWithSingleItem() method executes the following tasks:

    • Crée un commentaire unique de données de test.Creates a single comment of test data.
    • Prédit les sentiments en fonction des données de test.Predicts sentiment based on test data.
    • Combine les données de test et les prédictions pour générer des rapports.Combines test data and predictions for reporting.
    • Affiche les résultats prédits.Displays the predicted results.
  2. Ajoutez un appel à la nouvelle méthode à partir de la méthode Main(), juste sous l’appel à la méthode Evaluate(), en utilisant le code suivant :Add a call to the new method from the Main() method, right under the Evaluate() method call, using the following code:

    UseModelWithSingleItem(mlContext, model);
    
  3. Ajoutez le code suivant comme première ligne dans la méthode UseModelWithSingleItem() :Add the following code to create as the first line in the UseModelWithSingleItem() Method:

    PredictionEngine<SentimentData, SentimentPrediction> predictionFunction = mlContext.Model.CreatePredictionEngine<SentimentData, SentimentPrediction>(model);
    

    Le PredictionEngine est une API pratique, qui vous permet d’effectuer une prédiction sur une seule instance de données.The PredictionEngine is a convenience API, which allows you to perform a prediction on a single instance of data. PredictionEnginen’est pas thread-safe.PredictionEngine is not thread-safe. Il est acceptable d’utiliser dans des environnements à thread unique ou prototype.It's acceptable to use in single-threaded or prototype environments. Pour améliorer les performances et la sécurité des threads dans les environnements de production, utilisez le PredictionEnginePool service, qui crée un ObjectPool d' PredictionEngine objets à utiliser dans votre application.For improved performance and thread safety in production environments, use the PredictionEnginePool service, which creates an ObjectPool of PredictionEngine objects for use throughout your application. Pour plus d’informations sur l' utilisation PredictionEnginePool de dans une API Web ASP.net Core, consultez ce guide.See this guide on how to use PredictionEnginePool in an ASP.NET Core Web API.

    Notes

    L’extension de service PredictionEnginePool est disponible en préversion.PredictionEnginePool service extension is currently in preview.

  4. Ajoutez un commentaire pour tester la prédiction du modèle formé dans la méthode UseModelWithSingleItem() en créant une instance de SentimentData :Add a comment to test the trained model's prediction in the UseModelWithSingleItem() method by creating an instance of SentimentData:

    SentimentData sampleStatement = new SentimentData
    {
        SentimentText = "This was a very bad steak"
    };
    
  5. Transmettez les données de commentaire de test au PredictionEngine en ajoutant le code suivant en tant que lignes de code suivantes dans la UseModelWithSingleItem() méthode :Pass the test comment data to the PredictionEngine by adding the following as the next lines of code in the UseModelWithSingleItem() method:

    var resultPrediction = predictionFunction.Predict(sampleStatement);
    

    La fonction Predict() effectue une prédiction sur une seule ligne de données.The Predict() function makes a prediction on a single row of data.

  6. Affichez SentimentText et la prédiction de sentiment correspondante en utilisant le code suivant :Display SentimentText and corresponding sentiment prediction using the following code:

    Console.WriteLine();
    Console.WriteLine("=============== Prediction Test of model with a single sample and test dataset ===============");
    
    Console.WriteLine();
    Console.WriteLine($"Sentiment: {resultPrediction.SentimentText} | Prediction: {(Convert.ToBoolean(resultPrediction.Prediction) ? "Positive" : "Negative")} | Probability: {resultPrediction.Probability} ");
    
    Console.WriteLine("=============== End of Predictions ===============");
    Console.WriteLine();
    

Utiliser le modèle pour la prédictionUse the model for prediction

Déployer et prédire des éléments par lotsDeploy and predict batch items

  1. Créez la méthode UseModelWithBatchItems() juste après la méthode UseModelWithSingleItem(), en utilisant le code suivant :Create the UseModelWithBatchItems() method, just after the UseModelWithSingleItem() method, using the following code:

    public static void UseModelWithBatchItems(MLContext mlContext, ITransformer model)
    {
    
    }
    

    La méthode UseModelWithBatchItems() exécute les tâches suivantes :The UseModelWithBatchItems() method executes the following tasks:

    • Crée les données de test par lots.Creates batch test data.
    • Prédit les sentiments en fonction des données de test.Predicts sentiment based on test data.
    • Combine les données de test et les prédictions pour générer des rapports.Combines test data and predictions for reporting.
    • Affiche les résultats prédits.Displays the predicted results.
  2. Ajoutez un appel à la nouvelle méthode à partir de la méthode Main, juste sous l’appel à la méthode UseModelWithSingleItem(), en utilisant le code suivant :Add a call to the new method from the Main method, right under the UseModelWithSingleItem() method call, using the following code:

    UseModelWithBatchItems(mlContext, model);
    
  3. Ajoutez des commentaires pour tester les prédictions du modèle formé dans la méthode UseModelWithBatchItems() :Add some comments to test the trained model's predictions in the UseModelWithBatchItems() method:

    IEnumerable<SentimentData> sentiments = new[]
    {
        new SentimentData
        {
            SentimentText = "This was a horrible meal"
        },
        new SentimentData
        {
            SentimentText = "I love this spaghetti."
        }
    };
    

Prédire le sentiment de commentairePredict comment sentiment

Utilisez le modèle pour prédire le sentiment de données de commentaire à l’aide de la méthode Transform() :Use the model to predict the comment data sentiment using the Transform() method:

IDataView batchComments = mlContext.Data.LoadFromEnumerable(sentiments);

IDataView predictions = model.Transform(batchComments);

// Use model to predict whether comment data is Positive (1) or Negative (0).
IEnumerable<SentimentPrediction> predictedResults = mlContext.Data.CreateEnumerable<SentimentPrediction>(predictions, reuseRowObject: false);

Combiner et afficher les prédictionsCombine and display the predictions

Créez un en-tête des prédictions à l’aide du code suivant :Create a header for the predictions using the following code:

Console.WriteLine();

Console.WriteLine("=============== Prediction Test of loaded model with multiple samples ===============");

Comme SentimentPrediction est hérité de SentimentData, la méthode Transform() a rempli SentimentText avec les champs prédits.Because SentimentPrediction is inherited from SentimentData, the Transform() method populated SentimentText with the predicted fields. À mesure que le processus ML.NET progresse, chaque composant ajoute des colonnes, ce qui rend l’affichage des résultats plus facile :As the ML.NET process processes, each component adds columns, and this makes it easy to display the results:

foreach (SentimentPrediction prediction  in predictedResults)
{
    Console.WriteLine($"Sentiment: {prediction.SentimentText} | Prediction: {(Convert.ToBoolean(prediction.Prediction) ? "Positive" : "Negative")} | Probability: {prediction.Probability} ");
}
Console.WriteLine("=============== End of predictions ===============");

RésultatsResults

Vos résultats doivent être similaires à ce qui suit.Your results should be similar to the following. Durant le processus, des messages sont affichés.During processing, messages are displayed. Vous pouvez voir des avertissements ou des messages de traitement.You may see warnings, or processing messages. Ils ont été supprimés des résultats ci-dessous par souci de clarté.These have been removed from the following results for clarity.

Model quality metrics evaluation
--------------------------------
Accuracy: 83.96%
Auc: 90.51%
F1Score: 84.04%

=============== End of model evaluation ===============

=============== Prediction Test of model with a single sample and test dataset ===============

Sentiment: This was a very bad steak | Prediction: Negative | Probability: 0.1027377
=============== End of Predictions ===============

=============== Prediction Test of loaded model with a multiple samples ===============

Sentiment: This was a horrible meal | Prediction: Negative | Probability: 0.1369192
Sentiment: I love this spaghetti. | Prediction: Positive | Probability: 0.9960636
=============== End of predictions ===============

=============== End of process ===============
Press any key to continue . . .

Félicitations !Congratulations! Vous venez de créer un modèle d’apprentissage automatique pour la classification et la prédiction des sentiments de messages.You've now successfully built a machine learning model for classifying and predicting messages sentiment.

La création de modèles efficaces est un processus itératif.Building successful models is an iterative process. Celui-ci présente une qualité initiale médiocre, car le tutoriel utilise de petits jeux de données pour permettre un apprentissage rapide du modèle.This model has initial lower quality as the tutorial uses small datasets to provide quick model training. Si vous n’êtes pas satisfait de la qualité du modèle, vous pouvez essayer de l’améliorer en fournissant des jeux de données d’apprentissage plus importants ou en choisissant différents algorithmes d’apprentissage avec des hyperparamètres différents pour chaque algorithme.If you aren't satisfied with the model quality, you can try to improve it by providing larger training datasets or by choosing different training algorithms with different hyper-parameters for each algorithm.

Vous trouverez le code source de ce tutoriel dans le référentiel dotnet/samples.You can find the source code for this tutorial at the dotnet/samples repository.

Étapes suivantesNext steps

Dans ce didacticiel, vous avez appris à :In this tutorial, you learned how to:

  • Création d’une application consoleCreate a console application
  • Préparer les donnéesPrepare data
  • Chargement des donnéesLoad the data
  • Générer et entraîner le modèleBuild and train the model
  • Évaluer le modèleEvaluate the model
  • Utiliser le modèle pour effectuer une prédictionUse the model to make a prediction
  • Afficher les résultatsSee the results

Passer au tutoriel suivant pour en savoir plusAdvance to the next tutorial to learn more