Use Microsoft.ML.Net to predict when to send an email


The following code uses Microsoft.ML to predict the best time to send an email.

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

namespace ML_Net_Email
    public class EmailData
        public float TimeOfDay;

        public bool IsSent;

    public class EmailPrediction
        public float TimeOfDay;

    class Program
        static void Main(string[] args)
            // Create ML Context with seed for repeatable/deterministic results
            MLContext mlContext = new MLContext(seed: 0);
            // Load Data
            IDataView dataView = mlContext.Data.LoadFromTextFile<EmailData>(path: "email-data.csv", hasHeader: true, separatorChar: ',');
            // Data Process Pipelines
            // Transform any text data to numeric data
            var pipeline = mlContext.Transforms.Conversion.MapValueToKey("TimeOfDay")
            // Set the training algorithm 
            var trainingPipeline = pipeline.Append(mlContext.BinaryClassification.Trainers.FastTree(numLeaves: 50, numTrees: 50, minDatapointsInLeaves: 20));
            // Train Model
            Console.WriteLine("Training model...");
            var model = trainingPipeline.Fit(dataView);
            // Create prediction engine related to the loaded trained model
            Console.WriteLine("Creating prediction engine...");
            var predEngine = mlContext.Model.CreatePredictionEngine<EmailData, EmailPrediction>(model);
            // Use the model to predict the best time to send an email
            Console.WriteLine("Predicting the best time to send an email...");
            var resultprediction = predEngine.Predict(new EmailData() { TimeOfDay = 15 });
            Console.WriteLine("The best time to send an email is: " + resultprediction.TimeOfDay);

Leave a comment