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
Visual Studio 2017 version 15,6 ou ultérieure avec la charge de travail « développement multiplateforme .net Core » installéeVisual Studio 2017 version 15.6 or later with the ".NET Core cross-platform development" workload installed
Jeu de données « UCI Sentiment Labeled Sentences » (fichier zip)UCI Sentiment Labeled Sentences dataset (ZIP file)
Création d’une application consoleCreate a console application
Créez une application console .NET Core appelée « SentimentAnalysis ».Create a .NET Core Console Application called "SentimentAnalysis".
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.
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.
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.
Copiez le fichier
yelp_labelled.txtdans le répertoire Données que vous avez créé.Copy theyelp_labelled.txtfile into the Data directory you created.Dans l’Explorateur de solutions, cliquez avec le bouton droit sur le fichier
yelp_labeled.txtet sélectionnez Propriétés.In Solution Explorer, right-click theyelp_labeled.txtfile 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
Ajoutez les instructions
usingsupplémentaires suivantes en haut du fichier Program.cs : Add the following additionalusingstatements 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;Ajoutez le code suivant à la ligne située juste au-dessus de la
Mainmé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 theMainmethod, to create a field to hold the recently downloaded dataset file path:static readonly string _dataPath = Path.Combine(Environment.CurrentDirectory, "Data", "yelp_labelled.txt");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.
Le fichier SentimentData.cs s’ouvre dans l’éditeur de code.The SentimentData.cs file opens in the code editor. Ajoutez l'instruction suivante
usingen haut du fichier SentimentData.cs :Add the followingusingstatement to the top of SentimentData.cs:using Microsoft.ML.Data;Supprimez la définition de classe existante et ajoutez le code suivant, qui contient deux classes,
SentimentDataetSentimentPrediction, au fichier SentimentData.cs :Remove the existing class definition and add the following code, which has two classesSentimentDataandSentimentPrediction, 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:
Remplacez la ligne
Console.WriteLine("Hello World!")dans la méthodeMainpar le code suivant pour déclarer et initialiser la variable mlContext :Replace theConsole.WriteLine("Hello World!")line in theMainmethod with the following code to declare and initialize the mlContext variable:MLContext mlContext = new MLContext();Ajoutez le code suivant comme prochaine ligne dans la méthode
Main():Add the following as the next line of code in theMain()method:TrainTestData splitDataView = LoadData(mlContext);Créez la méthode
LoadData()juste après la méthodeMain(), en utilisant le code suivant :Create theLoadData()method, just after theMain()method, using the following code:public static TrainTestData LoadData(MLContext mlContext) { }La méthode
LoadData()exécute les tâches suivantes :TheLoadData()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.
Ajoutez le code suivant comme première ligne de la méthode
LoadData():Add the following code as the first line of theLoadData()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 anIDataView.
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.
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 theLoadData()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 thetestFractionparameter. 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.Retournez
splitDataViewà la fin de la méthodeLoadData():Return thesplitDataViewat the end of theLoadData()method:return splitDataView;
Générer et entraîner le modèleBuild and train the model
Ajoutez l’appel suivant à la méthode
BuildAndTrainModelcomme prochaine ligne de code dans la méthodeMain():Add the following call to theBuildAndTrainModelmethod as the next line of code in theMain()method:ITransformer model = BuildAndTrainModel(mlContext, splitDataView.TrainSet);La méthode
BuildAndTrainModel()exécute les tâches suivantes :TheBuildAndTrainModel()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.
Créez la méthode
BuildAndTrainModel()juste après la méthodeMain(), en utilisant le code suivant :Create theBuildAndTrainModel()method, just after theMain()method, using the following code:public static ITransformer BuildAndTrainModel(MLContext mlContext, IDataView splitTrainSet) { }
Extraire et transformer les donnéesExtract and transform the data
Appelez
FeaturizeTextsur la ligne de code suivante :CallFeaturizeTextas 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 colonneFeaturesde 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 :TheFeaturizeText()method in the previous code converts the text column (SentimentText) into a numeric key typeFeaturescolumn 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.
Créez la méthode
Evaluate()juste aprèsBuildAndTrainModel(), en utilisant le code suivant :Create theEvaluate()method, just afterBuildAndTrainModel(), with the following code:public static void Evaluate(MLContext mlContext, ITransformer model, IDataView splitTestSet) { }La méthode
Evaluate()exécute les tâches suivantes :TheEvaluate()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.
Ajoutez un appel à la nouvelle méthode à partir de la méthode
Main(), juste sous l’appel à la méthodeBuildAndTrainModel(), en utilisant le code suivant :Add a call to the new method from theMain()method, right under theBuildAndTrainModel()method call, using the following code:Evaluate(mlContext, model, splitDataView.TestSet);Transformez les données
splitTestSeten ajoutant le code suivant àEvaluate():Transform thesplitTestSetdata by adding the following code toEvaluate():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.
É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 theEvaluate()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
Accuracydonne la précision du modèle, qui correspond à la proportion de prédictions correctes dans le jeu de test.TheAccuracymetric gets the accuracy of a model, which is the proportion of correct predictions in the test set.La métrique
AreaUnderRocCurveindique le degré de confiance conféré aux résultats de la classification des classes positif/négatif.TheAreaUnderRocCurvemetric indicates how confident the model is correctly classifying the positive and negative classes. Vous voulez que la métriqueAreaUnderRocCurvesoit le plus proche possible de la valeur 1.You want theAreaUnderRocCurveto be as close to one as possible.La métrique
F1Scoredonne le score F1 du modèle, qui mesure l’équilibre entre la précision et le rappel.TheF1Scoremetric gets the model's F1 score, which is a measure of balance between precision and recall. Vous voulez que la métriqueF1Scoresoit le plus proche possible de la valeur 1.You want theF1Scoreto be as close to one as possible.
Prédire les résultats des données de testPredict the test data outcome
Créez la méthode
UseModelWithSingleItem()juste après la méthodeEvaluate(), en utilisant le code suivant :Create theUseModelWithSingleItem()method, just after theEvaluate()method, using the following code:private static void UseModelWithSingleItem(MLContext mlContext, ITransformer model) { }La méthode
UseModelWithSingleItem()exécute les tâches suivantes :TheUseModelWithSingleItem()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.
Ajoutez un appel à la nouvelle méthode à partir de la méthode
Main(), juste sous l’appel à la méthodeEvaluate(), en utilisant le code suivant :Add a call to the new method from theMain()method, right under theEvaluate()method call, using the following code:UseModelWithSingleItem(mlContext, model);Ajoutez le code suivant comme première ligne dans la méthode
UseModelWithSingleItem():Add the following code to create as the first line in theUseModelWithSingleItem()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.PredictionEngineis 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 lePredictionEnginePoolservice, qui crée unObjectPoold'PredictionEngineobjets à utiliser dans votre application.For improved performance and thread safety in production environments, use thePredictionEnginePoolservice, which creates anObjectPoolofPredictionEngineobjects for use throughout your application. Pour plus d’informations sur l' utilisationPredictionEnginePoolde dans une API Web ASP.net Core, consultez ce guide.See this guide on how to usePredictionEnginePoolin an ASP.NET Core Web API.Notes
L’extension de service
PredictionEnginePoolest disponible en préversion.PredictionEnginePoolservice extension is currently in preview.Ajoutez un commentaire pour tester la prédiction du modèle formé dans la méthode
UseModelWithSingleItem()en créant une instance deSentimentData:Add a comment to test the trained model's prediction in theUseModelWithSingleItem()method by creating an instance ofSentimentData:SentimentData sampleStatement = new SentimentData { SentimentText = "This was a very bad steak" };Transmettez les données de commentaire de test au
PredictionEngineen ajoutant le code suivant en tant que lignes de code suivantes dans laUseModelWithSingleItem()méthode :Pass the test comment data to thePredictionEngineby adding the following as the next lines of code in theUseModelWithSingleItem()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.
Affichez
SentimentTextet la prédiction de sentiment correspondante en utilisant le code suivant :DisplaySentimentTextand 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
Créez la méthode
UseModelWithBatchItems()juste après la méthodeUseModelWithSingleItem(), en utilisant le code suivant :Create theUseModelWithBatchItems()method, just after theUseModelWithSingleItem()method, using the following code:public static void UseModelWithBatchItems(MLContext mlContext, ITransformer model) { }La méthode
UseModelWithBatchItems()exécute les tâches suivantes :TheUseModelWithBatchItems()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.
Ajoutez un appel à la nouvelle méthode à partir de la méthode
Main, juste sous l’appel à la méthodeUseModelWithSingleItem(), en utilisant le code suivant :Add a call to the new method from theMainmethod, right under theUseModelWithSingleItem()method call, using the following code:UseModelWithBatchItems(mlContext, model);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 theUseModelWithBatchItems()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

