You can perform sentiment analysis in C# with ML.NET by training a binary classification model that predicts whether a piece of text is positive or negative.
1. Install ML.NET
Create a console project and add the ML.NET package:
dotnet new console -n SentimentAnalysis
cd SentimentAnalysis
dotnet add package Microsoft.ML
2. Create the data model
Suppose your training data is a CSV file containing:
Sentiment,Text
true,I absolutely love this product!
false,This was a terrible experience.
true,The service was excellent.
false,I would not recommend this.
Define C# classes:
using Microsoft.ML.Data;
public class SentimentData
{
[LoadColumn(0)]
public bool Sentiment { get; set; }
[LoadColumn(1)]
public string Text { get; set; }
}
public class SentimentPrediction
{
[ColumnName("PredictedLabel")]
public bool Prediction { get; set; }
public float Probability { get; set; }
public float Score { get; set; }
}
3. Load and split the data
using Microsoft.ML;
MLContext mlContext = new MLContext();
IDataView data = mlContext.Data.LoadFromTextFile<SentimentData>(
"sentiment-data.csv",
hasHeader: true,
separatorChar: ',');
DataOperationsCatalog.TrainTestData split =
mlContext.Data.TrainTestSplit(data, testFraction: 0.2);
This keeps some data aside for evaluating the model after training.
4. Build the ML.NET pipeline
For text sentiment analysis, you can convert the text into numerical features and then train a binary classifier:
FeaturizeText performs the text-processing/feature-extraction step, while logistic regression learns how those features relate to positive or negative sentiment.
5. Train the model
ITransformer model = pipeline.Fit(split.TrainSet);
The evaluation metrics help determine whether the model generalizes well to text it hasn't seen during training.
7. Predict sentiment for new text
Create a prediction engine:
PredictionEngine<SentimentData, SentimentPrediction> engine =
mlContext.Model.CreatePredictionEngine<
SentimentData, SentimentPrediction>(model);
var input = new SentimentData
{
Text = "The product is fantastic and works perfectly!"
};
SentimentPrediction prediction = engine.Predict(input);
Console.WriteLine(
$"Sentiment: {(prediction.Prediction ? "Positive" : "Negative")}");
Console.WriteLine($"Probability: {prediction.Probability:P2}");
A complete minimal flow is therefore:
CSV training data
↓
Load with ML.NET
↓
Train/test split
↓
FeaturizeText
↓
Binary classifier
↓
Train
↓
Evaluate
↓
Predict new text
Improving the model
For a real application, the quality and diversity of your labeled training data are often more important than simply changing algorithms. You can improve the system by:
Using a substantially larger labeled dataset.
Including examples representative of your actual users and domain.
Handling class imbalance.
Comparing several ML.NET classifiers.
Performing cross-validation and hyperparameter tuning.
Cleaning or normalizing text when appropriate.
Tracking precision, recall, F1, and AUC rather than relying only on accuracy.
For production workloads, you can also save the trained model:
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
You can perform sentiment analysis in C# with ML.NET by training a binary classification model that predicts whether a piece of text is positive or negative.
1. Install ML.NET
Create a console project and add the ML.NET package:
2. Create the data model
Suppose your training data is a CSV file containing:
Define C# classes:
3. Load and split the data
This keeps some data aside for evaluating the model after training.
4. Build the ML.NET pipeline
For text sentiment analysis, you can convert the text into numerical features and then train a binary classifier:
FeaturizeTextperforms the text-processing/feature-extraction step, while logistic regression learns how those features relate to positive or negative sentiment.5. Train the model
6. Evaluate it
The evaluation metrics help determine whether the model generalizes well to text it hasn't seen during training.
7. Predict sentiment for new text
Create a prediction engine:
A complete minimal flow is therefore:
Improving the model
For a real application, the quality and diversity of your labeled training data are often more important than simply changing algorithms. You can improve the system by:
For production workloads, you can also save the trained model:
and load it later:
This lets you train the model separately from the application that performs predictions.