Click here to Skip to main content
15,885,435 members
Articles / Programming Languages / C#

Deploy CNTK Model to Excel using C#

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
28 Nov 2017CPOL2 min read 5.9K  
How to deploy CNTK model to Excel using C#

In the last blog post, we saw how to save model state (checkpoint) in order to load it and train again. Also, we have seen how to save model for the evaluation and testing. In fact, we have seen how to prepare the model to be production ready.

Once we finish with the modeling process, we enter into production phase, to install the model on place where we can use it for solving real world problems. This blog post is going to describe the process how deployed CNTK model can be exported to Excel like an AddIn and be used like ordinary Excel formula.

Preparing and Deploying CNTK Model

From the previous posts, we saw how to train and save the model. This will be our starting point for this post.

Assume we trained and saved the model for evaluation from the previous blog post with file name as “IrisModel.model”. The model calculates Iris flower based on 4 input parameters, as we saw earlier.

  1. The first step is to create a .NET Class Library and install the following Nugget packages:
    1. CNTK CPU Only ver. 2.3
    2. Excel Dna Addin
    3. Include saved IrisModel.model file in the project as Content and should be copied in Debug folder of the application.

As we can see, for this export, we need Excel Dna Addin, a fantastic library for making anything as Excel Addin. It can be installed as Nuget package, and more information can be found here.

The following picture shows the above 3 actions:

Image 1

Once we prepare everything, we can start with the implementation of the Excel Addin.

  1. Change the Class.cs name into IrisModel.cs, and implement two methods:
    1. public static string IrisEval(object arg) and
    2. private static float EvaluateModel(float[] vector)

The first method is direct Excel function which will be called in the Excel, and the second method is similar to the previous blog post for model evaluation. The following code snippet shows the implementation for the methods:

C#
[ExcelFunction(Description = "IrisEval - Prediction for the Iris flower based on 4 input values.")]
public static string IrisEval(object arg)
{
    try
    {
        //First convert object in to array
        object[,] obj = (object[,])arg;

        //create list to convert values
        List<float> calculatedOutput = new List<float>();
        //
        foreach (var s in obj)
        {
            var ss = float.Parse(s.ToString(), CultureInfo.InvariantCulture);
            calculatedOutput.Add(ss);
        }
        if (calculatedOutput.Count != 4)
            throw new Exception("Incorrect number of input variables. It must be 4!");
        return EvaluateModel(calculatedOutput.ToArray());
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
}
private static string EvaluateModel(float[] vector)
{
    //load the model from disk
    var ffnn_model = Function.Load(@"IrisModel.model", DeviceDescriptor.CPUDevice);

    //extract features and label from the model
    Variable feature = ffnn_model.Arguments[0];
    Variable label = ffnn_model.Output;

    Value xValues = Value.CreateBatch<float>(new int[] { feature.Shape[0] }, 
                    vector, DeviceDescriptor.CPUDevice);
    //Value yValues = - we don't need it, because we are going to calculate it

    //map the variables and values
    var inputDataMap = new Dictionary<Variable, Value>();
    inputDataMap.Add(feature, xValues);
    var outputDataMap = new Dictionary<Variable, Value>();
    outputDataMap.Add(label, null);

    //evaluate the model
    ffnn_model.Evaluate(inputDataMap, outputDataMap, DeviceDescriptor.CPUDevice);
    //extract the result  as one hot vector
    var outputData = outputDataMap[label].GetDenseData<float>(label);
    var actualLabels = outputData.Select(l => l.IndexOf(l.Max())).ToList();
    var flower = actualLabels.FirstOrDefault();
    var strFlower = flower == 0 ? "setosa" : flower == 1 ? "versicolor" : "virginica";
    return strFlower;
}

That is all we need for model evaluation in Excel.

Notice that the project must be build with the x64 architecture, and also installed Excel must be in x64 version. This demo will not work in Excel 32 bits.

Rebuild the project and open Excel file with Iris Data set. You can use the file included in the demo project, especially prepared for this blog post.

  • Got to Excel – > Options -> Addins,
    • Install the ExportCNTKToExcel-AddIn64-packed addin file.

    Image 2

  • Start typing the Excel formula:
    • IrisEval(A1:D1) and press Enter. And the magic happens.

    Image 3

The complete source code for this blog post can be found here.

Filed under: .NET, C#, CNTK, CodeProject
Tagged: C#, CNTK, Code Project, CodeProject, Excel, Machine Learning, ML
Image 4 Image 5

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Bosnia and Herzegovina Bosnia and Herzegovina
Bahrudin Hrnjica holds a Ph.D. degree in Technical Science/Engineering from University in Bihać.
Besides teaching at University, he is in the software industry for more than two decades, focusing on development technologies e.g. .NET, Visual Studio, Desktop/Web/Cloud solutions.

He works on the development and application of different ML algorithms. In the development of ML-oriented solutions and modeling, he has more than 10 years of experience. His field of interest is also the development of predictive models with the ML.NET and Keras, but also actively develop two ML-based .NET open source projects: GPdotNET-genetic programming tool and ANNdotNET - deep learning tool on .NET platform. He works in multidisciplinary teams with the mission of optimizing and selecting the ML algorithms to build ML models.

He is the author of several books, and many online articles, writes a blog at http://bhrnjica.net, regularly holds lectures at local and regional conferences, User groups and Code Camp gatherings, and is also the founder of the Bihac Developer Meetup Group. Microsoft recognizes his work and awarded him with the prestigious Microsoft MVP title for the first time in 2011, which he still holds today.

Comments and Discussions

 
-- There are no messages in this forum --