# Introduction

Few weeks ago, I was doing research and I needed a fast program for Singular Value Decomposition. I have SVD implementation in my open source project called Daany which is using the SVD implementation of Accord.NET great Machine Learning Framework. However, the decomposition is working fine and smooth for small matrices with few hundreds rows/cols but for matrices with more than 500 rows and columns it is pretty slow. So I was forced to think about of using different library in order to speed up the SVD calculation. I could use some of python libraries eg. TensorFlow, PyTorch or SciPy or similar libraries from R and c++. I have used such libraries and I know how they are fast. But I still wanted to have approximately same speed on .NET as well.

Then I decided to look how can I use some of available c++ based libraries. Once I switch to c++ based project I would not be able to use .NET framework where other parts of my research are implemented. So only solution was to implement a wrapper around a c++ library and use pInvoke in order to expose required methods in C# code.

The first idea was to use LAPACK/BLAS numerical library to calculate not only SVD but whole set of Linear Algebra routines. LAPACK/BLAS libraries have long history back to 70s of the 20th century. They are proved to be very fast and reliable. However they are not supported for GPU.

Then I came to MAGMA which is nothing but LAPACK for GPU. MAGMA is very complex and fast library which requires CUDA. However if the machine has no CUDA, the library cannot be used.

The I decided to use hybrid approach and use MAGMA whenever the machine has CUDA, otherwise use LAPACK as computation engine. This approach is the most complex and required advance skills in C++ and C#. So after a more than a month of the implementation the MagmaSharp is published as GitHub open source project with the fist public release MagmaSharp 0.02.01 at Nuget.org.

# MagmaSharp v0.02.01

The first release of MagmaSharp supports MAGMA Device routines: Currently the library supports MAGMA driver routines for general rectangular matrix:

1. gesv – solve linear system, AX = B, A is general non-symetric matrix,
2. gels – least square solve, AX = B, A is rectangular,
3. geev – eigen value solver for non-symetric matrix, $AX = X \lambda$
4. gesvd– singular value decomposition (SVD), $A = U \sigma V^T$.

The library supports float and double value types.

# Software requirements

The project is build on .NET Core 3.1 and .NET Standard 2.1. It is built and tested on Windows 10 1909 only.

# Software (Native Libraries) requirements

In order to compile, build and use the library the following native libraries are needed to be installed.

However, if you install the MagmaSharp as Nuget package, both libraries are included, so you don’t have to install it.

# How to use MagmaSharp

MagmaSharp is packed as Nuget and can be added to your .NET project as ordinary .NET component. You don’t have to worry about native libraries and dependencies. Everything is included in the package. The package can be installed from this link, or just search for MagmaSharp.

# How to Build MagmaSharp from the source

1. Download the MagmaSharp source code from the GitHub page.

2. Reference Magma static library and put it to folder MagmaLib. Magma static library can be downloaded and built from the Official site.

3. Open ‘MagmaSharp.sln’ with Visual Studio 2019.

4. Make sure the building architecture is x64.

5. Restore Nuget packages.

6. Build and run the Solution.

# How to start with MagmaSharp

The best way to start with MahmaSharp is to take a look at the MagmaSharp.XUnit project, there is a small example how to use each of the implemented method with or without CUDA device.

# Building Predictive Maintenance Model Using ML.NET

## Summary

This C# notebook is a continuation from the previous blog post Predictive Maintenance on .NET Platform.

The notebook is completely implemented on .NET platform using C# Jupyter Notebook and Daany – C# data analytics library. There are small differences between this notebook and the notebooks at the official azure gallery portal, but in most cases, the code follows the steps defined there.

The notebook shows how to use .NET Jupyter Notebook with Daany.DataFrame and ML.NET in order to prepare the data and build the Predictive Maintenance Model on .NET platform.

## Description

In the previous post, we analyzed 5 data sets with information about telemetry, data, errors and maintenance as well as failure for 100 machines. The data were transformed and analyzed in order to create the final data set for building a machine learning model for Predictive maintenance.

Once we created all features from the data sets, as a final step we created the label column so that it describes if a certain machine will fail in the next 24 hours due to failure a component1, component2, component3, component4 or it will continue to work. . In this part, we are going to perform a part of the machine learning task and start training a machine learning model for predicting if a certain machine will fail in the next 24 hours due to failure, or it will be in functioning normal in that time period.

The model which we are going to build is multi-class classification model sice it has 5 values to predict:

• component1,
• component2,
• component3,
• component4 or
• none – means it will continue to work.

# ML.NET framework as library for training

In order to train the model, we are going to use ML.NET – Microsoft open source framework for Machine Learning on .NET Platform. First we need to put some preparation codes like:

• Required Nuget packages,
• Set of using statements and code for formatting the output:

At the beggining of this notebook, we installed the several NugetPackages in order to complete this notebook. The following code shows using statements, and method for formatting the data from the DataFrame.

//using Microsoft.ML.Data;
using XPlot.Plotly;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;

//
using Microsoft.ML;
using Microsoft.ML;
using Microsoft.ML.Data;
using Microsoft.ML.Transforms;
using Microsoft.ML.Trainers.LightGbm;
//
using Daany;
using Daany.Ext;
//DataFrame formatter
using Microsoft.AspNetCore.Html;
Formatter.Register((df, writer) =&gt;
{
//renders the rows
var rows = new List&lt;List&gt;();
var take = 20;
//
for (var i = 0; i &lt; Math.Min(take, df.RowCount()); i++)
{
var cells = new List();
foreach (var obj in df[i]){
}
}
var t = table(
tbody(
rows.Select(
r =&gt; tr(r))));
writer.Write(t);
}, "text/html");


Once we install the Nuget packages and define using statements we are going to define a class we need to create an ML.NET pipeline.

The class PrMaintenanceClass – contains the features (properties) we build in the previous post. We need them to define features in the ML.NET pipeline. The second class we defined is PrMaintenancePrediction we used for prediction and model evaluation.

class PrMaintenancePrediction
{
[ColumnName("PredictedLabel")]
public string failure { get; set; }
}
class PrMaintenanceClass
{
public DateTime datetime { get; set; }
public int machineID { get; set; }
public float voltmean_3hrs { get; set; }
public float rotatemean_3hrs { get; set; }
public float pressuremean_3hrs { get; set; }
public float vibrationmean_3hrs { get; set; }
public float voltstd_3hrs { get; set; }
public float rotatestd_3hrs { get; set; }
public float pressurestd_3hrs { get; set; }
public float vibrationstd_3hrs { get; set; }
public float voltmean_24hrs { get; set; }
public float rotatemean_24hrs { get; set; }
public float pressuremean_24hrs { get; set; }
public float vibrationmean_24hrs { get; set; }
public float voltstd_24hrs { get; set; }
public float rotatestd_24hrs { get; set; }
public float pressurestd_24hrs { get; set; }
public float vibrationstd_24hrs { get; set; }
public float error1count { get; set; }
public float error2count { get; set; }
public float error3count { get; set; }
public float error4count { get; set; }
public float error5count { get; set; }
public float sincelastcomp1 { get; set; }
public float sincelastcomp2 { get; set; }
public float sincelastcomp3 { get; set; }
public float sincelastcomp4 { get; set; }
public string model { get; set; }
public float age { get; set; }
public string failure { get; set; }
}


Now that we have defined a class type, we are going to implement the pipeline for this ml model.First, we create MLContext with constant seed, so that the model can be reproduced by any user running this notebook. Then we load the data and split the data into train and test set.

MLContext mlContext= new MLContext(seed:88888);
var strPath="data/final_dataFrame.csv";
var mlDF= DataFrame.FromCsv(strPath);
//
//split data frame on training and testing part
//split at 2015-08-01 00:00:00, to train on the first 8 months and test on last 4 months
var trainDF = mlDF.Filter("datetime", new DateTime(2015, 08, 1, 1, 0, 0), FilterOperator.LessOrEqual);
var testDF = mlDF.Filter("datetime", new DateTime(2015, 08, 1, 1, 0, 0), FilterOperator.Greather);


The summary for the training set is show in the following tables:

Similarly the testing set has the following summary:

Once we have data into application memory, we can prepare the ML.NET pipeline. The pipeline consists of data transformation from the Daany.DataFrame type into collection IDataView. For this task, the LoadFromEnumerable method is used.

//Load daany:DataFrame into ML.NET pipeline
public static IDataView loadFromDataFrame(MLContext mlContext,Daany.DataFrame df)
{
{
//convert row object array into PrManitenance row
var ooRow = oRow;
var prRow = new PrMaintenanceClass();
prRow.datetime = (DateTime)ooRow["datetime"];
prRow.machineID = (int)ooRow["machineID"];
prRow.voltmean_3hrs = Convert.ToSingle(ooRow["voltmean_3hrs"]);
prRow.rotatemean_3hrs = Convert.ToSingle(ooRow["rotatemean_3hrs"]);
prRow.pressuremean_3hrs = Convert.ToSingle(ooRow["pressuremean_3hrs"]);
prRow.vibrationmean_3hrs = Convert.ToSingle(ooRow["vibrationmean_3hrs"]);
prRow.voltstd_3hrs = Convert.ToSingle(ooRow["voltsd_3hrs"]);
prRow.rotatestd_3hrs = Convert.ToSingle(ooRow["rotatesd_3hrs"]);
prRow.pressurestd_3hrs = Convert.ToSingle(ooRow["pressuresd_3hrs"]);
prRow.vibrationstd_3hrs = Convert.ToSingle(ooRow["vibrationsd_3hrs"]);
prRow.voltmean_24hrs = Convert.ToSingle(ooRow["voltmean_24hrs"]);
prRow.rotatemean_24hrs = Convert.ToSingle(ooRow["rotatemean_24hrs"]);
prRow.pressuremean_24hrs = Convert.ToSingle(ooRow["pressuremean_24hrs"]);
prRow.vibrationmean_24hrs = Convert.ToSingle(ooRow["vibrationmean_24hrs"]);
prRow.voltstd_24hrs = Convert.ToSingle(ooRow["voltsd_24hrs"]);
prRow.rotatestd_24hrs = Convert.ToSingle(ooRow["rotatesd_24hrs"]);
prRow.pressurestd_24hrs = Convert.ToSingle(ooRow["pressuresd_24hrs"]);
prRow.vibrationstd_24hrs = Convert.ToSingle(ooRow["vibrationsd_24hrs"]);
prRow.error1count = Convert.ToSingle(ooRow["error1count"]);
prRow.error2count = Convert.ToSingle(ooRow["error2count"]);
prRow.error3count = Convert.ToSingle(ooRow["error3count"]);
prRow.error4count = Convert.ToSingle(ooRow["error4count"]);
prRow.error5count = Convert.ToSingle(ooRow["error5count"]);
prRow.sincelastcomp1 = Convert.ToSingle(ooRow["sincelastcomp1"]);
prRow.sincelastcomp2 = Convert.ToSingle(ooRow["sincelastcomp2"]);
prRow.sincelastcomp3 = Convert.ToSingle(ooRow["sincelastcomp3"]);
prRow.sincelastcomp4 = Convert.ToSingle(ooRow["sincelastcomp4"]);
prRow.model = (string)ooRow["model"];
prRow.age = Convert.ToSingle(ooRow["age"]);
prRow.failure = (string)ooRow["failure"];
//
return prRow;
}));

return dataView;
}


Load the data sets into the app memory:

//Split dataset in two parts: TrainingDataset  and TestDataset


Prior to start training we need to process that data, so that we encoded all non-numerical columns into numerical columns. Also we need to define which columns are going to be part of the Featuresand which one will be label. For this reason we define PrepareData method.

public static IEstimator PrepareData(MLContext mlContext)
{
//one hot encoding category column
IEstimator dataPipeline =

mlContext.Transforms.Conversion.MapValueToKey(outputColumnName: "Label", inputColumnName: nameof(PrMaintenanceClass.failure))
//encode model column
.Append(mlContext.Transforms.Categorical.OneHotEncoding("model",outputKind: OneHotEncodingEstimator.OutputKind.Indicator))

//define features column
.Append(mlContext.Transforms.Concatenate("Features",
//
nameof(PrMaintenanceClass.voltmean_3hrs), nameof(PrMaintenanceClass.rotatemean_3hrs),
nameof(PrMaintenanceClass.pressuremean_3hrs),nameof(PrMaintenanceClass.vibrationmean_3hrs),
nameof(PrMaintenanceClass.voltstd_3hrs), nameof(PrMaintenanceClass.rotatestd_3hrs),
nameof(PrMaintenanceClass.pressurestd_3hrs), nameof(PrMaintenanceClass.vibrationstd_3hrs),
nameof(PrMaintenanceClass.voltmean_24hrs),nameof(PrMaintenanceClass.rotatemean_24hrs),
nameof(PrMaintenanceClass.pressuremean_24hrs),nameof(PrMaintenanceClass.vibrationmean_24hrs),
nameof(PrMaintenanceClass.voltstd_24hrs),nameof(PrMaintenanceClass.rotatestd_24hrs),
nameof(PrMaintenanceClass.pressurestd_24hrs),nameof(PrMaintenanceClass.vibrationstd_24hrs),
nameof(PrMaintenanceClass.error1count), nameof(PrMaintenanceClass.error2count),
nameof(PrMaintenanceClass.error3count), nameof(PrMaintenanceClass.error4count),
nameof(PrMaintenanceClass.error5count), nameof(PrMaintenanceClass.sincelastcomp1),
nameof(PrMaintenanceClass.sincelastcomp2),nameof(PrMaintenanceClass.sincelastcomp3),
nameof(PrMaintenanceClass.sincelastcomp4),nameof(PrMaintenanceClass.model), nameof(PrMaintenanceClass.age) ));

return dataPipeline;
}


As can be seen, the method converts the label column failure which is a simple textual column into categorical columns containing numerical representation for each different category called Keys.

Now that we have finished with data transformation, we are going to define the Train method which is going to implement ML algorithm, hyper-parameters for it and training process. Once we call this method the method will return the trained model.

//train method
static public TransformerChain Train(MLContext mlContext, IDataView preparedData)
{
var transformationPipeline=PrepareData(mlContext);
//settings hyper parameters
var options = new LightGbmMulticlassTrainer.Options();
options.FeatureColumnName = "Features";
options.LearningRate = 0.005;
options.NumberOfLeaves = 70;
options.NumberOfIterations = 2000;
options.NumberOfLeaves = 50;
options.UnbalancedSets = true;
//
var boost = new DartBooster.Options();
boost.XgboostDartMode = true;
boost.MaximumTreeDepth = 25;
options.Booster = boost;

// Define LightGbm algorithm estimator
IEstimator lightGbm = mlContext.MulticlassClassification.Trainers.LightGbm(options);

//train the ML model
TransformerChain model = transformationPipeline.Append(lightGbm).Fit(preparedData);

//return trained model for evaluation
return model;
}


# Training process and model evaluation

Since we have all required methods, the main program structure looks like:

//prepare data transformation pipeline
var dataPipeline = PrepareData(mlContext);

//print prepared data
var pp = dataPipeline.Fit(trainData);
var transformedData = pp.Transform(trainData);

//train the model
var model = Train(mlContext, trainData);


Once the Train method returns the model, the evaluation phase started. In order to evaluate model, we perform full evaluation with training and testing data.

# Model Evaluation with train data set

The evaluation of the model will be performed for training and testing data sets:

//evaluate train set
var predictions = model.Transform(trainData);
var metricsTrain = mlContext.MulticlassClassification.Evaluate(predictions);

ConsoleHelper.PrintMultiClassClassificationMetrics("TRAIN DataSet", metricsTrain);
ConsoleHelper.ConsolePrintConfusionMatrix(metricsTrain.ConfusionMatrix);



The model evaluation output:

************************************************************
*    Metrics for TRAIN DataSet multi-class classification model
*-----------------------------------------------------------
AccuracyMacro = 0.9603, a value between 0 and 1, the closer to 1, the better
AccuracyMicro = 0.999, a value between 0 and 1, the closer to 1, the better
LogLoss = 0.0015, the closer to 0, the better
LogLoss for class 1 = 0, the closer to 0, the better
LogLoss for class 2 = 0.088, the closer to 0, the better
LogLoss for class 3 = 0.0606, the closer to 0, the better
************************************************************

Train DataSet Confusion Matrix
###############################

Confusion table
||========================================
PREDICTED ||  none | comp4 | comp1 | comp2 | comp3 | Recall
TRUTH     ||========================================
none || 165 371 |     0 |     0 |     0 |     0 | 1.0000
comp4 ||     0 |   772 |    16 |    25 |    11 | 0.9369
comp1 ||     0 |     8 |   884 |    26 |     4 | 0.9588
comp2 ||     0 |    31 |    22 | 1 097 |     8 | 0.9473
comp3 ||     0 |    13 |     4 |     8 |   576 | 0.9584
||========================================
Precision ||1.0000 |0.9369 |0.9546 |0.9490 |0.9616 |



As can be seen the model predict the values correctly in most cases in the train data set. Now lets see how the model predict the data which have not been part of the raining process.

# Model evaluation with test data set

//evaluate test set
var testPrediction = model.Transform(testData);
var metricsTest = mlContext.MulticlassClassification.Evaluate(testPrediction);
ConsoleHelper.PrintMultiClassClassificationMetrics("Test Dataset", metricsTest);

ConsoleHelper.ConsolePrintConfusionMatrix(metricsTest.ConfusionMatrix);

************************************************************
*    Metrics for Test Dataset multi-class classification model
*-----------------------------------------------------------
AccuracyMacro = 0.9505, a value between 0 and 1, the closer to 1, the better
AccuracyMicro = 0.9986, a value between 0 and 1, the closer to 1, the better
LogLoss = 0.0033, the closer to 0, the better
LogLoss for class 1 = 0.0012, the closer to 0, the better
LogLoss for class 2 = 0.1075, the closer to 0, the better
LogLoss for class 3 = 0.1886, the closer to 0, the better
************************************************************

Test DataSet Confusion Matrix
##############################

Confusion table
||========================================
PREDICTED ||  none | comp4 | comp1 | comp2 | comp3 | Recall
TRUTH     ||========================================
none || 120 313 |     6 |    15 |     0 |     0 | 0.9998
comp4 ||     1 |   552 |    10 |    17 |     4 | 0.9452
comp1 ||     2 |    14 |   464 |    24 |    24 | 0.8788
comp2 ||     0 |    39 |     0 |   835 |    16 | 0.9382
comp3 ||     0 |     4 |     0 |     0 |   412 | 0.9904
||========================================
Precision ||1.0000 |0.8976 |0.9489 |0.9532 |0.9035 |


We can see, that the model has overall accuracy 99%, and 95% average per class accuracy. The complete nptebook of this blog post can be found here.

# Create CIFAR-10 Deep Learning Model With ANNdotNET GUI Tool

With ANNdotNET 1.2 the user is able to create and train deep learning models for image classification. Image classification module provides minimum of GUI actions in order to fully prepare data set. In this post, we are going to create and train deep learning model for CIFAR-10 data set, and see how it easy to do that with ANNdotNET v1.2.

In order to prepare data we have to download CIFAR-10 data set from official web site . The CIFAR-10 data set is provided in 6 binary batch files that should be extracted and persisted on your local machine. Number 10 in the name means that data set is created for 10 labels.The following image shows 10 labels of CIFAR-10 data set each label with few sample images.

The data set contains 60 000 (50 000 for training and validation, and 10 000 for test) tinny colored images dimensions of 32×32. There is also bigger version of the data set CIFAR-100 with 100 labels. Our task is to create deep learning model capable of recognizing only one of 10 predefined labels from each image.

## Data preparation

In order to prepare images, we need to do the following:

The following image shows extracted data set persisted in 10 label folders. The bird folder is opened and shows all images labeled for bird. The test folder contains all images created for testing the model once the model is trained.

In order to properly save all images, we need to create simple C# Console application which should extract and save all 60 000 images. Complete C# program can be downloaded from here.

In order to successfully extract the images, we have to see how those images are stored in binary files. From the official site we can see that there are 5 for training and 1 for test binary files: data_batch_1.bin, data_batch_2.bin, …, data_batch_5.bin, as well as test_batch.bin.

Each of these files is formatted as follows so that the first byte of the array is label index, and the next 3072 bytes represent the image. Each batch contains 10 000 images.

Important to know is that images are stored in CHW format which means that 1d image array is created so that the first 1024 bytes are the red channel values, the next 1024 the green, and the final 1024 the blue. The values are stored in row-major order, so the first 32 bytes are the red channel values of the first row of the image. To end this, all those information have been carried out when implementing the Extractor application. The most important methods are reshaping the 1D byte array into [3, height, width] image tensor, and creating the image from the byte tensor. The following implementation shows how 1D byte array is transformed into 3channel bitmap tensor.

static int[][][] reshape(int channel, int height, int width,  byte[] img)
{
var data = new int[channel][][];
int counter = 0;
for(int c = 0; c < channel; c++)
{
data[c] = new int[height][];
for (int y = 0; y < height; y++)
{
data[c][y] = new int[width];
for (int x = 0; x < width; x++)
{
data[c][y][x] = img[counter];
counter++;
}
}
}
return data;
}

Once the 1D byte array is transformed into tensor, the image can be created and persisted on disk. The following method iterates through all 10000 images in one batch file, extract them and persist on disk.

public static void extractandSave(byte[] batch, string destImgFolder, ref int imgCounter)
{
var nStep = 3073;//1 for label and 3072 for image
//
for (int i = 0; i < batch.Length; i += nStep)
{
var l = (int)batch[i];
var img = new ArraySegment<byte>(batch, i + 1, nStep - 1).ToArray();
// data in CIFAR-10 dataset is in CHW format, which means CHW: RR...R, GG..G, BB..B;

// while HWC: RGB, RGB, ... RGB
var reshaped = reshape(3, 32, 32, img);
var image = ArrayToImg(reshaped);
//check if folder exist
var currentFolder = destImgFolder + classNames[l];

if (!Directory.Exists(currentFolder))
Directory.CreateDirectory(currentFolder);

//save image to specified folder
image.Save(currentFolder + "\\" + imgCounter.ToString() + ".png");

imgCounter++;
}
}

Run Cifar-Extractor console application and the process of downloading, extracting and saving images will be finished in few minutes. The most important is that CIFAR-10 data set will be stored in c://sc/datasets/cifar-10 path. This is important later, when we create image classifier.

Now that we have 60000 tiny images on disk arranged by labels we can start creating deep learning model.

## Create new image classification project file in ANNdotNET

Open the latest ANNdotNET v1.2 and select New-> Image Classification project. Enter CIFAR project name and press save button. The following image shows CIFAR new ann-project:

Once we have new project, we can start defining image labels by pressing Add button. For each 10 labels we need to add new label item in the list. In each item the following fields should be defined:

• Image label
• Path to images with the label.
• Query – in case we need to get all images within the specified path with certain part of the name. In case all images withing the specified path are images that indicate one label, query should be empty string.

Beside Label item, image transformation should be defined in order to define the size of the images, as well as how many images create validation/test data set.

Assuming the CIFAR-10 data set is extracted at c:/sc/datasets/cifar-10 folder, the following image shows how label items should be defined:

In case label item should be removed from the list, this is done by selecting the item, and then pressing Remove button. Beside image properties, we should defined how many images belong to validation data set. As can be seen 20% of all extracted images will be created validation data set. Notice that images from the test folder are not part of those two data set. they will be used for testing phase once the model is trained. Now that we done with data preparation we can move to the next step: creating mlconifg file.

## Create mlconfig in ANNdotNET

By selecting New MLConfig command the new mlconfig file is created within the project explorer. Moreover by pressing F2 key on selected mlconfig tree item, we can easily change the name into “CIRAF-10-ConvNet”. The reason why we gave such name is because we are going to use convolution neural networks.

In order to define mlconfig file we need to define the following:

• Network configuration using Visual Network Designer
• Define Learning parameters
• Define training parameters

## Create Network configuration

By using Visual Network Designer (VND) we can quickly create network model. For this CIFAR-10 data set we are going to create 11 layers model with 4 Constitutional, 2 Pooling, 1 DropOut and 3 Dense layer, all followed by Scale layer:

Scale (1/255)->Conv2D(32,[3,3])->Conv2D(32,[3,3])->Pooling2d([2,2],2)->Conv2D(64,[3,3])->Conv2D(64,[3,3])->Pooling2d([2,2],2)->DropOut(0.5)->Dense(64, TanH)->Dense(32, TanH)->Dense(10,Softmax)

This network can be created so that we select appropriate layer from the VND combo box and click on Add button. The first layer is Scale layer, since we need to normalize the input values to be in interval (0,1). Then we created two sequence of Convolution, Pooling layers. Once we done with that, we can add two Dense layers with 64 and 32 neurons with TanH activation function. The last layer is output layer that must follow the output dimension, and Softmax activation function.

Once network model is defined, we can move to the next step: Setting learning and training parameters.

Learning parameters can be defined through the Learning parameters interface: For this model we can select:

• AdamLearner with 0.005 rate and 0.9 momentum value. Loss function is Classification Error, and the evaluation function is Classification Accuracy

In order to define the training parameters we switch to Training tab page and setup:

• Number of epoch
• Minibatch size
• Progress frequency
• Randomize minibatch during training

Now we have enough information to start model training. The training process is started by selecting Run command from the application ribbon. In order to get good model we need to train the model at least few thousands epoch. The following image shows trained model with training history charts.

The model is trained with exactly of 4071 epochs, with network parameters mentioned above. As can be seen from the upper chart, mini-batch loss function was CrossEntropyWithSoftmax, while the evaluation function was classification accuracy.  The bottom chart shows performance of the training and validation data sets for each 4071 epoch. We can also recognize that validation data set has roughly the same accuracy as training data set which indicates the model is trained well.  More details about model performance can be seen on the next image:

Upper charts of the image above show actual and predicted values for training (left) and validation (right). Most of the point values are blue and overlap the orange which indicates that most of value are correctly predicted. The charts can be zoomed and view details of each value.The bottom part of the evaluation show performance parameters of the model for corresponded data set. As can be seen the trained model has 0.91 overall accuracy for training data set and 0.826 overall accuracy for validation data set, which indicate pretty good accuracy of the model. Moreover, the next two images shows confusion matrix for the both data sets, which in details shows how model predict all 10 labels.

The last part of the post is testing model for test data set. For that purpose we selected 10 random images from each label of the test set, and evaluate the model. The following images shows the model correctly predicted all 10 images.

## Conclusion

ANNdotNET v1.2 image classification module offers complete data preparation and model development for image classification. The user can prepare data for training, create network model with Neural Network Designer, and perform set of statistical tools against trained model in order to validate and evaluate model. The important note is that the data set of images must be stored on specific location in order to use this trained model shown in the blog post. The trained model, as well as mlcofig files, can be load directly into ANNdotNET project explorer by doublick on CIFAR-10.zip feed example.

ANNdotNET as open source project provides outstanding way in complete development of deep learning model.

# Brief Introduction to ANNdotNET

ANNdotNET – is an open source project for deep learning on .NET platform (.NET Framework and .NET Core). The project is hosted at http://github.com/bhrnjica/anndotnet with more information at the http://bhrnjica.net/anndotnet.

The project comes in two versions: GUI and CMD tool. The main purpose of the project is focus on building deep learning models without to be distracted with debugging the source code and installing/updating missing packages and environments. The user should no worry which version of ML Engine the application is using. In other words, the ANNdotNET is ideal in several scenarios:

1. more focus on network development and training process using classic desktop approach, instead of focusing on coding,
2. less time spending on debugging source code, more focusing on different configuration and parameter variants,
3. ideal for engineers/users who are not familiar with supported programming languages,
4. in case the problem requires coding more advanced custom models, or training process, ANNdotNET CMD provides high level of API for such implementation,
5. all ml configurations files generated with GUI tool, can be handled with CMD tool and vice versa.

With ANNdotNET GUI Tool the user can prepare data for training, by performing several actions: data cleaning, feature selection, category encoding, missing values handling, and create training and validation dataset prior to start building deep neural network. Once the data is prepared, the user can create Machine Learning Configuration (mlconfig) file in order to start building and training deep neural network. All previous actions user can handle using GUI tool implemented in the application.

For persisting information about data preparation and transformation actions, the application uses annproject file type which consists information about raw dataset, metadata information and information about mlconfig files.

The machine learning configurations are stored in separated files with mlconfig file extension. For more information about files in ANNdotNET the reader may open this link. The following image shows how ANNdotNET handles annproject and corresponded machine learning configurations within the annproject:

As can be seen the annproject can be consisted of arbitrary number of mlconfigs, which is typical scenario when working on ML Project. User can switch between mlconfigs any time except when the application is in training or evaluation mode.

# ANNdotNET ML Engine

ANNdotNET introduces the ANNdotNET Machine Learning Engine (MLEngine) which is responsible for training and evaluation models defined in the mlconfig files.The ML Engine relies on Microsoft Cognitive Toolkit, CNTK open source library which is proved to be one of the best open source library for deep learning. Through all application ML Engine exposed all great features of the CNTK e.g. GPU support for training and evaluation, different kind of learners, but also extends CNTK features with more Evaluation functions (RMSE, MSE, Classification Accuracy, Coefficient of Determination, etc.), Extended Mini-batch Sources, Trainer and Evaluaton models.

ML Engine also contains the implementation of neural network layers which supposed to be high level CNTK API very similar as layer implementation in Keras and other python based deep learning APIs. With this implementation the ANNdotNET implements the Visual Neural Network Designer called ANNdotNET NNDesigner which allows the user to design neural network configuration of any size with any type of the layers. In the first release the following layers are implemented:

• Normalization Layer – takes the numerical features and normalizes its values before getting to the network. More information can be found here.
• Dense – classic neural network layer with activation function
• LSTM – LSTM layer with option for peephole and self-stabilization.
• Embedding – Embedding layer,
• Drop – drop layer.

More layer types will be added in the future release.

Designing the neural network can be simplify by using pre-defined layer. So on this way we can implement almost any network we usually implement through the source code.

# How to use ANNdotNET NNDesigner

Once the MLConfig is created user can open it and start building neural network. NNDesigner is placed in the Network Setting tab page. The following image shows the Network Setting tab page.

NNetwork Designer contains combo box with supported NN layers, and two action buttons for adding and removing layers in/from the network. Adding and removing layers is simple as adding and removing items in/from the list box. In order to add a layer, select the item from the combo box, and press Add button. In order to remove the layer form the network, click the layer in the listbox and press Remove button, then confirm deletion. In order to successfully create the network, the last layer in the list must be created with the same output dimension as the Output layer shown on the left side of the window, otherwise the warning messages will appear about this information once the training is stared.

Once the layer is added to the list it must be configured. The layer configuration depends of its type . The main parameter for each layer is output dimension and activation function, except the drop and normalization layer. The following text explains parameters for all supported layers:

Normalization layer – does not require any parameter. The following image shows the normalization item in the NNDesigner. You can insert only one normalization layer, and it is positioned at the first place.

Drop layer – requires percentage drop value which is integer value. The following image shows how drop layer looks in the NNDesigner. There is no any constrains for this layer.

Embedding layer – requires only output dimension to be configured. There is no any constrains for the layer. The following image shows how it looks in the NNDesigner:

Dense layer – requires output dimension and activation function to be configured. There is no any constrains for the layer.

LSTM layer – requires: output and cell dimension, activation function, and two Boolean parameters to enable peephole and self-stabilization variant in the layer. The following image shows how LSTM item looks in the NNDesigner.

The LSTM layer has some constrains which is already implemented in the code. In case two LSTM layers are added in the network, the network becomes the Stacked LSTM which should be treated differently. Also all LSTM layers are inserted as stack, and they cannot be inserted on different places in the list. The implementation of the Stacked LSTM layer will be shown later.

# Different network configurations

In this section, various network configuration will be listed, in order to show how easy is to use NNDesigner to create very complex neural network configurations. Network examples are implemented in pre-calculated examples which come with default ANNdotNET installation package.

# Feed Forward network

This example shows how to implement Feed Forward network, with one hidden and one output layer which is the last layer in the NNDesinger. The example is part of the ANNdotNET installation package.

# Feed Forward with Normalization layer

This example shows feed forward network with normalization layer as the first layer. The example of this configuration can be found in the installation package of the ANNdotNET.

# Feed Forward Network with Embedding layers

In this example embedding layers are used in order to reduce the dimensions of the input layer. Network is configured with 3 embedding layers, one hidden and output layer. The example is part of the ANNdotNET installation package.

# Deep Neural Network

This example shows deep neural network with three kind of layers: Embedding, Drop and Dense layers. The project is part of the ANNdotNET installation package.

# LSTM Deep Neural Network

This example shows how to configure LSTM based network. The network consist of normalization, embedding, drop, dense and LSTM layers. The project is part of the ANNdotNET installation package.

# Stacked LSTM Neural Network

This is example of Stacked LSTM network, consist of multiple LSTM layers connected into stack. The example is part of the installation package.

The complete list of examples can be seen at the ANNdotNET Start Page. In order to open the example, the user just need to click the link. Hope this project will be useful for many ml scenarios.