This repository demonstrates how to:
- Train a Sentiment Analysis model using ML.NET in a Console Application
- Save the trained model as a
.zipfile - Use the saved model to predict sentiment in an ASP.NET Core Web API
- Prerequisites
- Step 1: Train the Model (Console App)
- Step 2: Use the Model in Web API
- Step 3: Test the API
- Where is the Model Zip File?
- Notes
- .NET 6 SDK or later
- Visual Studio 2022 or VS Code (with C# extension)
- Basic knowledge of C# and ASP.NET Core
-
Open the
SentimentModelTrainerconsole app project. -
Add a CSV file
sentiment-data.csvin the root folder with the following format:Text,Label "I love this product",Positive "This is terrible",Negative "It was okay",Neutral -
Review
Program.cswhich:- Loads the data from CSV
- Builds and trains a multi-class classification pipeline
- Evaluates the model accuracy
- Saves the trained model as
SentimentModel.zip
-
Run the Console App:
dotnet run
-
After running, the
SentimentModel.zipfile will be created automatically in the output folder, depending on your build configuration:- For Debug builds:
bin/Debug/net6.0/SentimentModel.zip - For Release builds:
bin/Release/net6.0/SentimentModel.zip
- For Debug builds:
-
Open the
SentimentWebAPIproject. -
Copy the
SentimentModel.zipfile from the console app output folder to the Web API project folder (e.g., root or/MLModels). -
In the Web API, the model is loaded once and used to predict sentiment for incoming requests.
-
The API controller expects a JSON POST body like:
{ "Text": "This product is amazing!", "Label": "" // Label must be present but can be empty to satisfy ML.NET schema } -
The controller responds with the predicted sentiment label.
-
Run the Web API project.
-
Use Postman, curl, or any HTTP client to POST to:
POST https://localhost:<port>/api/sentiment Content-Type: application/json -
Example JSON body:
{ "Text": "I really enjoyed this movie!", "Label": "" } -
Example response:
{ "text": "I really enjoyed this movie!", "sentiment": "Positive" }
- The trained model file
SentimentModel.zipis generated by the console app after training. - Its location depends on the build configuration:
- Debug:
bin/Debug/net6.0/SentimentModel.zip - Release:
bin/Release/net6.0/SentimentModel.zip
- Debug:
- Make sure to copy this file into your Web API project folder to load and use the model.
- The
Labelproperty is required in the input class and must be present during prediction, even if its value is empty. This is because ML.NET expects the input schema to match exactly what was used during training. - You can customize the classes and API further to separate training input and prediction input if needed.
- For more advanced scenarios, consider using ML.NET's Model Builder tool or training on larger datasets.
Feel free to open issues or pull requests for suggestions or improvements!
Happy coding! 🚀

