![.NET]()
Introduction
ML.NET is a tool for machine learning that was created by Microsoft. It’s designed for developers who are familiar with the .NET framework. With ML.NET, you can build, train, and deploy custom machine learning models without having to leave the .NET ecosystem. Thanks to the performance optimizations and seamless integration capabilities of .NET 9, ML.NET is an even better choice for adding intelligence to your applications. In this article, we’ll explore real-world use cases and provide sample code to help you implement them.
What Makes ML.NET Special?
- Native .NET Integration: You can write machine learning code in C# or F#, using familiar tools like Visual Studio.
- Wide Range of Algorithms: It supports classification, regression, clustering, anomaly detection, and more.
- Model Builder: A GUI tool to simplify model creation for beginners.
- It can also handle large data sets and works with cloud-based .NET 9 apps. Pre-trained models work with ONNX, TensorFlow, and Azure Cognitive Services for more complex situations.
Sentiment Analysis
Sentiment analysis is the process of determining the emotional tone behind the text. It’s a powerful tool for businesses and developers. It can be used to gauge customer feedback, analyze social media trends, or enhance user experiences. Sentiment analysis can unlock valuable insights. With .NET 9 and ML.NET, Microsoft’s machine learning framework, developers can seamlessly integrate this capability into their applications without leaving the .NET ecosystem. In this article, we’ll show you how to create a sentiment analysis API in .NET 9 using ML.NET. We’ll provide practical code examples and tips for optimization.
Project Overview: Sentiment Analysis API
We’ll build an ASP.NET Core Web API that predicts whether a piece of text expresses positive or negative sentiment. This example will use ML.NET to train a model and deploy it within a .NET 9 application, showing how simple and useful it is.
For complete source code: Click here
Step 1. Setting Up the Project.
Create a new ASP.NET Core Web API project.
dotnet new webapi -n dotnet9SentimentApi -f net9.0
cd dotnet9SentimentApi
Open the folder in VS code. The project should be as shown below.
![VS Code]()
Let’s add the ML.NET NuGet package.
You can either run the command or do it from VS code UI as illustrated below.
dotnet add package Microsoft.ML
![UI]()
Step 2. Define the Data Models.
Create a folder named Models and add two classes: SentimentData and SentimentPrediction.
- SentimentData.cs: Represents the input data for the model.
namespace dotnet9SentimentApi.Models;
public record SentimentData
{
public string Text { get; set; } = string.Empty;
}
- SentimentPrediction.cs: Represents the model’s output.
namespace dotnet9SentimentApi.Models;
public record SentimentPrediction
{
public bool Prediction { get; set; } // True = Positive, False = Negative
public float Probability { get; set; }
}
Step 3. Training a Simple Sentiment Model with ML.NET.
For simplicity, we’ll use a pre-trained model approach here, but ML.NET allows you to train your own model with a dataset. Create a SentimentModelTrainer.cs class in a Services folder to simulate model setup.
To train the model with your own data.
private void TrainModel()
{
// Simulated training data (in practice, load from a file or database)
var data = BuildTrainingData();
var dataView = _mlContext.Data.LoadFromEnumerable(data);
// Enhanced pipeline with text preprocessing
var pipeline = _mlContext.Transforms.Text.FeaturizeText(
"Features",
new Microsoft.ML.Transforms.Text.TextFeaturizingEstimator.Options
{
WordFeatureExtractor = new Microsoft.ML.Transforms.Text.WordBagEstimator.Options(),
StopWordsRemoverOptions = new Microsoft.ML.Transforms.Text.StopWordsRemovingEstimator.Options()
},
nameof(SentimentTrainingData.Text)
)
.Append(_mlContext.BinaryClassification.Trainers.LbfgsLogisticRegression(
labelColumnName: nameof(SentimentTrainingData.Sentiment)
));
// Train the model
_model = pipeline.Fit(dataView);
// Optional: Save the model for reuse
_mlContext.Model.Save(_model, dataView.Schema, "sentiment_model.zip");
}
Note. In a real-world scenario, you’d train with a larger dataset (e.g., from a CSV file) and save the model using _mlContext.Model.Save().
Complete SentimentModelTrainer.cs class.
using System;
using dotnet9SentimentApi.Models;
using Microsoft.ML;
namespace dotnet9SentimentApi.Services;
public class SentimentModelTrainer
{
private readonly MLContext _mlContext;
private ITransformer _model;
public SentimentModelTrainer()
{
_mlContext = new MLContext();
TrainModel();
}
private void TrainModel()
{
// Simulated training data (in practice, load from a file or database)
var data = BuildTrainingData();
var dataView = _mlContext.Data.LoadFromEnumerable(data);
// Enhanced pipeline with text preprocessing
var pipeline = _mlContext.Transforms.Text.FeaturizeText("Features",
new Microsoft.ML.Transforms.Text.TextFeaturizingEstimator.Options
{
WordFeatureExtractor = new Microsoft.ML.Transforms.Text.WordBagEstimator.Options(),
StopWordsRemoverOptions = new Microsoft.ML.Transforms.Text.StopWordsRemovingEstimator.Options()
}, nameof(SentimentTrainingData.Text))
.Append(_mlContext.BinaryClassification.Trainers.LbfgsLogisticRegression(
labelColumnName: nameof(SentimentTrainingData.Sentiment)));
// Train the model
_model = pipeline.Fit(dataView);
// Optional: Save the model for reuse
_mlContext.Model.Save(_model, dataView.Schema, "sentiment_model.zip");
}
public SentimentPrediction Predict(string text)
{
var predictionEngine = _mlContext.Model.CreatePredictionEngine<SentimentData, SentimentPrediction>(_model);
return predictionEngine.Predict(new SentimentData { Text = text });
}
// Build training data
private List<SentimentTrainingData> BuildTrainingData()
{
return new List<SentimentTrainingData>
{
new() { Text = "I love this product!", Sentiment = true },
new() { Text = "This is terrible.", Sentiment = false },
new() { Text = "The weather is nice!", Sentiment = true },
new() { Text = "Horrible service, never again.", Sentiment = false },
new() { Text = "Absolutely fantastic experience!", Sentiment = true },
new() { Text = "It’s a complete disaster.", Sentiment = false },
new() { Text = "I’m so happy with this!", Sentiment = true },
new() { Text = "Disappointing and awful.", Sentiment = false },
new() { Text = "I’m so impressed!", Sentiment = true },
new() { Text = "I’m never coming back.", Sentiment = false },
new() { Text = "I’m so excited!", Sentiment = true },
new() { Text = "I’m so disappointed.", Sentiment = false },
new() { Text = "I’m so pleased with this!", Sentiment = true },
new() { Text = "I’m so upset.", Sentiment = false },
new() { Text = "I’m so satisfied with this!", Sentiment = true },
new() { Text = "I’m so angry.", Sentiment = false },
new() { Text = "I’m so grateful for this!", Sentiment = true },
new() { Text = "I’m so annoyed.", Sentiment = false },
new() { Text = "I’m so thankful for this!", Sentiment = true }
};
}
}
public record SentimentTrainingData
{
public string Text { get; set; } = string.Empty;
public bool Sentiment { get; set; }
}
Step 4. Build the API Controller.
Create a SentimentController in the Controllers folder.
using dotnet9SentimentApi.Models;
using dotnet9SentimentApi.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace dotnet9SentimentApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class SentimentController : ControllerBase
{
private readonly SentimentModelTrainer _modelTrainer;
public SentimentController(SentimentModelTrainer modelTrainer)
{
_modelTrainer = modelTrainer;
}
[HttpPost("analyze")]
public ActionResult<SentimentPrediction> AnalyzeSentiment([FromBody] SentimentData input)
{
if (string.IsNullOrEmpty(input.Text))
return BadRequest("Text cannot be empty.");
var prediction = _modelTrainer.Predict(input.Text);
return Ok(new
{
Sentiment = prediction.Prediction ? "Positive" : "Negative",
Confidence = prediction.Probability
});
}
}
}
Step 5. Register Services in Program.cs.
Update Program.cs will use minimal APIs and register the service.
// Add services to the container
builder.Services.AddControllers();
builder.Services.AddSingleton<SentimentModelTrainer>();
// Configure the HTTP request pipeline
app.UseHttpsRedirection();
app.MapControllers();
Complete code for the Program.cs.
using dotnet9SentimentApi.Services;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
// Add services to the container
builder.Services.AddControllers();
builder.Services.AddSingleton<SentimentModelTrainer>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
// Configure the HTTP request pipeline
app.UseHttpsRedirection();
app.MapControllers();
app.Run();
Our solution is ready to test.
For complete source code: Click here
Test the API
dotnet run
You can use Postman to test the api or http file in VS code. I will test using VS code .http file.
@dotnet9SentimentApi_HostAddress = http://localhost:5288
# post analyze sentiment
POST {{dotnet9SentimentApi_HostAddress}}/api/sentiment/analyze
Content-Type: application/json
{
"text": "I am not happy with the result!"
}
###
The result is shown below.
![Result]()
The result is not as expected, which indicates an issue with the sentiment analysis model’s training or configuration. Given the tiny dataset and simplistic setup in the original sample, the model isn’t learning meaningful patterns.
However, we can improve the result with more training data and testing.
Enhancing the Project
- Scalability: Deploy to Azure with container support for cloud-native scaling.
- Model Accuracy: Use a real dataset (e.g., IMDB reviews) and train with more sophisticated algorithms like FastTree.
- Performance: Cache predictions for frequently analyzed text using MemoryCache.
- Integration: Extend with Azure Cognitive Services or TensorFlow.NET for advanced AI capabilities.
Conclusion
Sentiment analysis in .NET 9 using ML.NET is easy to use and powerful. It lets developers add intelligence to their applications with little complexity. This API shows the basics, but there are many possibilities. You can integrate it with real-time data, use .NET 9’s cloud-native features, or enhance it with pre-trained models. As you explore further, you will see that ML.NET and .NET 9 together offer a robust platform for sentiment analysis and more.
Reference: dotnetcopilot.com