, ,

Sample code in c# for beginners to learning about programming with AI

Posted by

Here’s a simple C# program for beginners that demonstrates how to use an AI model to perform a task like text analysis. In this example, we’ll use the ML.NET library, which is Microsoft’s machine learning framework for .NET. This program will train a model to predict the sentiment (positive or negative) of a text input.

Prerequisites

To run this program, you’ll need:

  1. Visual Studio 2019 or later.
  2. .NET Core 3.1 SDK or later.
  3. ML.NET NuGet package.

You can install ML.NET by adding the NuGet package to your project:

Install-Package Microsoft.ML

Sample Code

Here’s the full sample code for a simple sentiment analysis application using ML.NET:

using System;
using Microsoft.ML;
using Microsoft.ML.Data;

namespace SimpleSentimentAnalysis
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new ML context, for ML.NET operations
            var mlContext = new MLContext();

            // Define data and load it into a DataView.
            var data = new[]
            {
                new SentimentData { Text = "This is a great product", Label = true },
                new SentimentData { Text = "I hate this thing", Label = false }
            };
            IDataView trainingDataView = mlContext.Data.LoadFromEnumerable(data);

            // Create a data processing pipeline
            var dataProcessingPipeline = mlContext.Transforms.Text.FeaturizeText(outputColumnName: "Features", inputColumnName: nameof(SentimentData.Text));

            // Set the training algorithm 
            var trainer = mlContext.BinaryClassification.Trainers.SdcaLogisticRegression(labelColumnName: "Label", featureColumnName: "Features");
            var trainingPipeline = dataProcessingPipeline.Append(trainer);

            // Train the model
            var trainedModel = trainingPipeline.Fit(trainingDataView);

            // Test the model with a new sample
            var predictionEngine = mlContext.Model.CreatePredictionEngine<SentimentData, SentimentPrediction>(trainedModel);
            var newSample = new SentimentData { Text = "This product is very nice!" };
            var prediction = predictionEngine.Predict(newSample);

            // Output the prediction
            Console.WriteLine($"Text: '{newSample.Text}' | Prediction: {(prediction.Prediction ? "Positive" : "Negative")}");
        }
    }

    // Data classes
    public class SentimentData
    {
        public bool Label { get; set; }
        public string Text { get; set; }
    }

    public class SentimentPrediction : SentimentData
    {
        [ColumnName("PredictedLabel")]
        public bool Prediction { get; set; }
    }
}

Explanation

  • ML Context: Initializes machine learning context.
  • Data: Simulated input data with labels for training.
  • Data Processing Pipeline: Prepares and transforms the text data for model training.
  • Training Algorithm: Uses a logistic regression algorithm, suitable for binary classification tasks.
  • Model Training: Trains the model using the defined pipeline and training data.
  • Prediction: Tests the trained model with new data and outputs predictions.

This example provides a good starting point for beginners to understand how data is used to train a model and how predictions are made with that model in C#.