ML.Net
ML.Net
ML.NET
Overview
Model Builder & CLI
The ML.NET Model Builder tool
The ML.NET Command-Line interface
API
The ML.NET API
Tutorials
Model Builder & CLI
Predict prices (Model Builder & regression)
Analyze sentiment using the ML.NET CLI
Analyze sentiment in Razor Pages (Model Builder & binary classification)
Categorize health violations (Model Builder & multiclass classification)
API
Overview
Analyze sentiment (binary classification)
Categorize support issues (multiclass classification)
Predict prices (regression)
Categorize iris flowers (k-means clustering)
Recommend movies (matrix factorization)
Image Classification (transfer learning)
Classify images (model composition)
Forecast bike rental demand (time series)
Call-volume spikes (anomaly detection)
Product Sales Analysis (anomaly detection)
Detect objects in images (object detection)
Classify sentiment using TensorFlow (text classification)
Infer.NET
Probabilistic programming with Infer.NET
Concepts
ML.NET tasks
Algorithms
Data transforms
Model evaluation metrics
Improve model accuracy
How-to guides
Model Builder & CLI
Load data into Model Builder
Install Model Builder
Install GPU in Model Builder
Install the CLI
Use the automated ML API
API
Install extra dependencies
Load data
Prepare data
Train, evaluate, and explain the model
Train and evaluate a model
Train a model using cross-validation
Inspect intermediate pipeline data values
Determine model feature importance with PFI
Use the trained model
Save and load a model
Use a model to make predictions
Re-train a model
Deploy a model to Azure Functions
Deploy a model to a web API
Consume Azure Machine Learning ONNX model
Reference
ML.NET API Reference
ML.NET API Preview API Reference
CLI reference
Resources
Overview
Glossary
Azure training resources
CLI telemetry
What is Model Builder and how does it work?
11/2/2020 • 8 minutes to read • Edit Online
ML.NET Model Builder is an intuitive graphical Visual Studio extension to build, train, and deploy custom
machine learning models.
Model Builder uses automated machine learning (AutoML) to explore different machine learning algorithms and
settings to help you find the one that best suits your scenario.
You don't need machine learning expertise to use Model Builder. All you need is some data, and a problem to
solve. Model Builder generates the code to add the model to your .NET application.
NOTE
Model Builder is currently in Preview.
Scenario
You can bring many different scenarios to Model Builder, to generate a machine learning model for your
application.
A scenario is a description of the type of prediction you want to make using your data. For example:
predict future product sales volume based on historical sales data
classify sentiments as positive or negative based on customer reviews
detect whether a banking transaction is fraudulent
route customer feedback issues to the correct team in your company
Which machine learning scenario is right for me?
In Model Builder, you need to select a scenario. The type of scenario depends on what type of prediction you are
trying to make.
Text classification
Classification is used to categorize data into categories.
Value prediction
Regression is used to predict numbers.
Image classification
Image classification is used to identify images of different categories. For example, different types of terrain or
animals or manufacturing defects.
You can use the image classification scenario if you have a set of images, and you want to classify the images
into different categories.
Object detection
Object detection is used to locate and categorize entities within images. For example, locating and identifying
cars and people in an image.
You can use object detection when images contain multiple objects of different types.
Recommendation
The recommendation scenario predicts a list of suggested items for a particular user, based on how similar their
likes and dislikes are to other users'.
You can use the recommendation scenario when you have a set of users and a set of "products", such as items to
purchase, movies, books, or TV shows, along with a set of users' "ratings" of those products.
Environment
You can train your machine learning model locally on your machine or in the cloud on Azure, depending on the
scenario.
When you train locally, you work within the constraints of your computer resources (CPU, memory, and disk).
When you train in the cloud, you can scale up your resources to meet the demands of your scenario, especially
for large datasets.
Local CPU training is supported for all scenarios except Object Detection.
Local GPU training is supported for Image Classification.
Azure training is supported for Image Classification and Object Detection.
Data
Once you have chosen your scenario, Model Builder asks you to provide a dataset. The data is used to train,
evaluate, and choose the best model for your scenario.
Model Builder supports datasets in .tsv, .csv, .txt formats, as well as SQL database format. If you have a .txt file,
columns should be separated with , , ; or /t and the file must have a header row.
If the dataset is made up of images, the supported file types are .jpg and .png .
For more information, see Load training data into Model Builder.
Choose the output to predict (label)
A dataset is a table of rows of training examples, and columns of attributes. Each row has:
a label (the attribute that you want to predict)
features (attributes that are used as inputs to predict the label).
For the house-price prediction scenario, the features could be:
the square footage of the house
the number of bedrooms and bathrooms
the zip code
The label is the historical house price for that row of square footage, bedroom, and bathroom values and zip
code.
Example datasets
If you don't have your own data yet, try out one of these datasets:
Value prediction Predict taxi fare price taxi fare data Fare Trip time, distance
Image classification Predict the category flower images The type of flower: The image data itself
of a flower daisy, dandelion,
roses, sunflowers,
tulips
Train
Once you select your scenario, environment, data, and label, Model Builder trains the model.
What is training?
Training is an automatic process by which Model Builder teaches your model how to answer questions for your
scenario. Once trained, your model can make predictions with input data that it has not seen before. For
example, if you are predicting house prices and a new house comes on the market, you can predict its sale price.
Because Model Builder uses automated machine learning (AutoML), it does not require any input or tuning from
you during training.
How long should I train for?
Model Builder uses AutoML to explore multiple models to find you the best performing model.
Longer training periods allow AutoML to explore more models with a wider range of settings.
The table below summarizes the average time taken to get good performance for a suite of example datasets, on
a local machine.
0 - 10 MB 10 sec
10 - 100 MB 10 min
500 - 1 GB 60 min
1 GB+ 3+ hours
These numbers are a guide only. The exact length of training is dependent on:
the number of features (columns) being used to as input to the model
the type of columns
the ML task
the CPU, disk, and memory performance of the machine used for training
It's generally advised that you use more than 100 rows as datasets with less than that may not produce any
results and may take a significantly longer time to train.
Evaluate
Evaluation is the process of measuring how good your model is. Model Builder uses the trained model to make
predictions with new test data, and then measures how good the predictions are.
Model Builder splits the training data into a training set and a test set. The training data (80%) is used to train
your model and the test data (20%) is held back to evaluate your model.
How do I understand my model performance?
A scenario maps to a machine learning task. Each ML task has its own set of evaluation metrics.
Value prediction
The default metric for value prediction problems is RSquared, the value of RSquared ranges between 0 and 1. 1
is the best possible value or in other words the closer the value of RSquared to 1 the better your model is
performing.
Other metrics reported such as absolute-loss, squared-loss, and RMS loss are additional metrics, which can be
used to understand how your model is performing and comparing it against other value prediction models.
Classification (2 categories )
The default metric for classification problems is accuracy. Accuracy defines the proportion of correct predictions
your model is making over the test dataset. The closer to 100% or 1.0 the better it is.
Other metrics reported such as AUC (Area under the curve), which measures the true positive rate vs. the false
positive rate should be greater than 0.50 for models to be acceptable.
Additional metrics like F1 score can be used to control the balance between Precision and Recall.
Classification (3+ categories )
The default metric for Multi-class classification is Micro Accuracy. The closer the Micro Accuracy to 100% or 1.0
the better it is.
Another important metric for Multi-class classification is Macro-accuracy, similar to Micro-accuracy the closer to
1.0 the better it is. A good way to think about these two types of accuracy is:
Micro-accuracy: How often does an incoming ticket get classified to the right team?
Macro-accuracy: For an average team, how often is an incoming ticket correct for their team?
More information on evaluation metrics
For more information, see model evaluation metrics.
Improve
If your model performance score is not as good as you want it to be, you can:
Train for a longer period of time. With more time, the automated machine learning engine experiments
with more algorithms and settings.
Add more data. Sometimes the amount of data is not sufficient to train a high-quality machine learning
model.This is especially true with datasets that have a small number of examples.
Balance your data. For classification tasks, make sure that the training set is balanced across the
categories. For example, if you have four classes for 100 training examples, and the two first classes (tag1
and tag2) are used for 90 records, but the other two (tag3 and tag4) are only used on the remaining 10
records, the lack of balanced data may cause your model to struggle to correctly predict tag3 or tag4.
Code
After the evaluation phase, Model Builder outputs a model file, and code that you can use to add the model to
your application. ML.NET models are saved as a zip file. The code to load and use your model is added as a new
project in your solution. Model Builder also adds a sample console app that you can run to see your model in
action.
In addition, Model Builder outputs the code that generated the model, so that you can understand the steps used
to generate the model. You can also use the model training code to retrain your model with new data.
What's next?
Install the Model Builder Visual Studio extension
Try price prediction or any regression scenario
Automate model training with the ML.NET CLI
11/2/2020 • 3 minutes to read • Edit Online
NOTE
This topic refers to ML.NET CLI and ML.NET AutoML , which are currently in Preview, and material may be subject to
change.
You can generate those assets from your own datasets without coding by yourself, so it also improves your
productivity even if you already know ML.NET.
Currently, the ML Tasks supported by the ML.NET CLI are:
classification (binary and multi-class)
regression
recommendation
Future: other machine learning tasks such as image-classification, ranking, anomaly-detection, clustering
Example of usage (classification scenario):
You can run it the same way on Windows PowerShell, macOS/Linux bash, or Windows CMD. However, tabular
auto-completion (parameter suggestions) won't work on Windows CMD.
Accuracy is a popular metric for classification problems, however accuracy isn't always the best metric to select
the best model from as explained in the following references. There are cases where you need to evaluate the
quality of your model with additional metrics.
To explore and understand the metrics that are output by the CLI, see Evaluation metrics for classification.
Metrics for Regression and Recommendation models
A regression model fits the data well if the differences between the observed values and the model's predicted
values are small and unbiased. Regression can be evaluated with certain metrics.
You'll see a similar list of metrics for the best top five quality models found by the CLI. In this particular case
related to a regression ML task:
To explore and understand the metrics that are output by the CLI, see Evaluation metrics for regression.
See also
How to install the ML.NET CLI tool
Tutorial: Analyze sentiment using the ML.NET CLI
ML.NET CLI command reference
Telemetry in ML.NET CLI
What is ML.NET and how does it work?
1/25/2021 • 9 minutes to read • Edit Online
ML.NET gives you the ability to add machine learning to .NET applications, in either online or offline scenarios.
With this capability, you can make automatic predictions using the data available to your application. Machine
learning applications make use of patterns in the data to make predictions rather than needing to be explicitly
programmed.
Central to ML.NET is a machine learning model . The model specifies the steps needed to transform your input
data into a prediction. With ML.NET, you can train a custom model by specifying an algorithm, or you can import
pre-trained TensorFlow and ONNX models.
Once you have a model, you can add it to your application to make the predictions.
ML.NET runs on Windows, Linux, and macOS using .NET Core, or Windows using .NET Framework. 64 bit is
supported on all platforms. 32 bit is supported on Windows, except for TensorFlow, LightGBM, and ONNX-
related functionality.
Examples of the type of predictions that you can make with ML.NET:
Regression/Predict continuous values Predict the price of houses based on size and location
class Program
{
public class HouseData
{
public float Size { get; set; }
public float Price { get; set; }
}
// 3. Train model
var model = pipeline.Fit(trainingData);
// 4. Make a prediction
var size = new HouseData() { Size = 2.5F };
var price = mlContext.Model.CreatePredictionEngine<HouseData, Prediction>(model).Predict(size);
Code workflow
The following diagram represents the application code structure, as well as the iterative process of model
development:
Collect and load training data into an IDataView object
Specify a pipeline of operations to extract features and apply a machine learning algorithm
Train a model by calling Fit() on the pipeline
Evaluate the model and iterate to improve
Save the model into binary format, for use in an application
Load the model back into an ITransformer object
Make predictions by calling CreatePredictionEngine.Predict()
Let's dig a little deeper into those concepts.
The model is simply: $Price = b + Size * w$. The parameters $b$ and $w$ are estimated by fitting a line on a set
of (size, price) pairs. The data used to find the parameters of the model is called training data . The inputs of a
machine learning model are called features . In this example, $Size$ is the only feature. The ground-truth values
used to train a machine learning model are called labels . Here, the $Price$ values in the training data set are the
labels.
More complex
A more complex model classifies financial transactions into categories using the transaction text description.
Each transaction description is broken down into a set of features by removing redundant words and characters,
and counting word and character combinations. The feature set is used to train a linear model based on the set
of categories in the training data. The more similar a new description is to the ones in the training set, the more
likely it will be assigned to the same category.
Both the house price model and the text classification model are linear models. Depending on the nature of
your data and the problem you are solving, you can also use decision tree models, generalized additive
models, and others. You can find out more about the models in Tasks.
Data preparation
In most cases, the data that you have available isn't suitable to be used directly to train a machine learning
model. The raw data needs to be prepared, or pre-processed, before it can be used to find the parameters of
your model. Your data may need to be converted from string values to a numerical representation. You might
have redundant information in your input data. You may need to reduce or expand the dimensions of your input
data. Your data might need to be normalized or scaled.
The ML.NET tutorials teach you about different data processing pipelines for text, image, numerical, and time-
series data used for specific machine learning tasks.
How to prepare your data shows you how to apply data preparation more generally.
You can find an appendix of all of the available transformations in the resources section.
Model evaluation
Once you have trained your model, how do you know how well it will make future predictions? With ML.NET,
you can evaluate your model against some new test data.
Each type of machine learning task has metrics used to evaluate the accuracy and precision of the model against
the test data set.
For our house price example, we used the Regression task. To evaluate the model, add the following code to
the original sample.
HouseData[] testHouseData =
{
new HouseData() { Size = 1.1F, Price = 0.98F },
new HouseData() { Size = 1.9F, Price = 2.1F },
new HouseData() { Size = 2.8F, Price = 2.9F },
new HouseData() { Size = 3.4F, Price = 3.6F }
};
Console.WriteLine($"R^2: {metrics.RSquared:0.##}");
Console.WriteLine($"RMS error: {metrics.RootMeanSquaredError:0.##}");
// R^2: 0.96
// RMS error: 0.19
The evaluation metrics tell you that the error is low-ish, and that correlation between the predicted output and
the test output is high. That was easy! In real examples, it takes more tuning to achieve good model metrics.
ML.NET architecture
In this section, we go through the architectural patterns of ML.NET. If you are an experienced .NET developer,
some of these patterns will be familiar to you, and some will be less familiar. Hold tight, while we dive in!
An ML.NET application starts with an MLContext object. This singleton object contains catalogs . A catalog is a
factory for data loading and saving, transforms, trainers, and model operation components. Each catalog object
has methods to create the different types of components:
Clustering ClusteringCatalog
Forecasting ForecastingCatalog
Ranking RankingCatalog
Regression RegressionCatalog
You can navigate to the creation methods in each of the above categories. Using Visual Studio, the catalogs show
up via IntelliSense.
In the snippet, Concatenate and Sdca are both methods in the catalog. They each create an IEstimator object
that is appended to the pipeline.
At this point, the objects are created only. No execution has happened.
Train the model
Once the objects in the pipeline have been created, data can be used to train the model.
Calling Fit() uses the input training data to estimate the parameters of the model. This is known as training
the model. Remember, the linear regression model above had two model parameters: bias and weight . After
the Fit() call, the values of the parameters are known. Most models will have many more parameters than
this.
You can learn more about model training in How to train your model.
The resulting model object implements the ITransformer interface. That is, the model transforms input data into
predictions.
The CreatePredictionEngine() method takes an input class and an output class. The field names and/or code
attributes determine the names of the data columns used during model training and prediction. For more
information, see Make predictions with a trained model.
Data models and schema
At the core of an ML.NET machine learning pipeline are DataView objects.
Each transformation in the pipeline has an input schema (data names, types, and sizes that the transform
expects to see on its input); and an output schema (data names, types, and sizes that the transform produces
after the transformation).
If the output schema from one transform in the pipeline doesn't match the input schema of the next transform,
ML.NET will throw an exception.
A data view object has columns and rows. Each column has a name and a type and a length. For example, the
input columns in the house price example are Size and Price . They are both type and they are scalar quantities
rather than vector ones.
All ML.NET algorithms look for an input column that is a vector. By default this vector column is called Features .
This is why we concatenated the Size column into a new column called Features in our house price example.
All algorithms also create new columns after they have performed a prediction. The fixed names of these new
columns depend on the type of machine learning algorithm. For the regression task, one of the new columns is
called Score . This is why we attributed our price data with this name.
public class Prediction
{
[ColumnName("Score")]
public float Price { get; set; }
}
You can find out more about output columns of different machine learning tasks in the Machine Learning Tasks
guide.
An important property of DataView objects is that they are evaluated lazily . Data views are only loaded and
operated on during model training and evaluation, and data prediction. While you are writing and testing your
ML.NET application, you can use the Visual Studio debugger to take a peek at any data view object by calling the
Preview method.
You can watch the debug variable in the debugger and examine its contents. Do not use the Preview method in
production code, as it significantly degrades performance.
Model Deployment
In real-life applications, your model training and evaluation code will be separate from your prediction. In fact,
these two activities are often performed by separate teams. Your model development team can save the model
for use in the prediction application.
mlContext.Model.Save(model, trainingData.Schema,"model.zip");
Next steps
Learn how to build applications using different machine learning tasks with more realistic data sets in the
tutorials.
Learn about specific topics in more depth in the How To Guides.
If you're super keen, you can dive straight into the API Reference documentation.
Tutorial: Predict prices using regression with Model
Builder
3/31/2020 • 6 minutes to read • Edit Online
Learn how to use ML.NET Model Builder to build a regression model to predict prices. The .NET console app that
you develop in this tutorial predicts taxi fares based on historical New York taxi fare data.
The Model Builder price prediction template can be used for any scenario requiring a numerical prediction value.
Example scenarios include: house price prediction, demand prediction, and sales forecasting.
In this tutorial, you learn how to:
Prepare and understand the data
Choose a scenario
Load the data
Train the model
Evaluate the model
Use the model for predictions
NOTE
Model Builder is currently in Preview.
Pre-requisites
For a list of pre-requisites and installation instructions, visit the Model Builder installation guide.
Choose a scenario
To train your model, you need to select from the list of available machine learning scenarios provided by Model
Builder. In this case, the scenario is Price Prediction .
1. In Solution Explorer , right-click the TaxiFarePrediction project, and select Add > Machine Learning .
2. In the scenario step of the Model Builder tool, select Price Prediction scenario.
using System;
using TaxiFarePredictionML.Model;
4. To make a prediction on new data using the model, create a new instance of the ModelInput class inside
the Main method of your application. Notice that the fare amount is not part of the input. This is because
the model will generate the prediction for it.
5. Use the Predict method from the ConsumeModel class. The Predict method loads the trained model,
create a PredictionEngine for the model and uses it to make predictions on new data.
// Make prediction
ModelOutput prediction = ConsumeModel.Predict(input);
// Print Prediction
Console.WriteLine($"Predicted Fare: {prediction.Score}");
Console.ReadKey();
If you need to reference the generated projects at a later time inside of another solution, you can find them
inside the C:\Users\%USERNAME%\AppData\Local\Temp\MLVSTools directory.
Next Steps
In this tutorial, you learned how to:
Prepare and understand the data
Choose a scenario
Load the data
Train the model
Evaluate the model
Use the model for predictions
Additional Resources
To learn more about topics mentioned in this tutorial, visit the following resources:
Model Builder Scenarios
Regression
Regression Model Metrics
NYC TLC Taxi Trip data set
Analyze sentiment using the ML.NET CLI
11/2/2020 • 11 minutes to read • Edit Online
Learn how to use ML.NET CLI to automatically generate an ML.NET model and underlying C# code. You provide
your dataset and the machine learning task you want to implement, and the CLI uses the AutoML engine to
create model generation and deployment source code, as well as the classification model.
In this tutorial, you will do the following steps:
Prepare your data for the selected machine learning task
Run the 'mlnet classification' command from the CLI
Review the quality metric results
Understand the generated C# code to use the model in your application
Explore the generated C# code that was used to train the model
NOTE
This topic refers to the ML.NET CLI tool, which is currently in Preview, and material may be subject to change. For more
information, visit the ML.NET page.
The ML.NET CLI is part of ML.NET and its main goal is to "democratize" ML.NET for .NET developers when
learning ML.NET so you don't need to code from scratch to get started.
You can run the ML.NET CLI on any command-prompt (Windows, Mac, or Linux) to generate good quality
ML.NET models and source code based on training datasets you provide.
Pre-requisites
.NET Core 3.1 SDK or later
(Optional) Visual Studio 2019
ML.NET CLI
You can either run the generated C# code projects from Visual Studio or with dotnet run (.NET Core CLI).
NOTE
The datasets this tutorial uses a dataset from the 'From Group to Individual Labels using Deep Features', Kotzias
et al,. KDD 2015, and hosted at the UCI Machine Learning Repository - Dua, D. and Karra Taniskidou, E. (2017).
UCI Machine Learning Repository [http://archive.ics.uci.edu/ml]. Irvine, CA: University of California, School of
Information and Computer Science.
2. Copy the yelp_labelled.txt file into any folder you previously created (such as /cli-test ).
3. Open your preferred command prompt and move to the folder where you copied the dataset file. For
example:
cd /cli-test
Using any text editor such as Visual Studio Code, you can open, and explore the yelp_labelled.txt
dataset file. You can see that the structure is:
The file has no header. You will use the column's index.
There are just two columns:
Make sure you close the dataset file from the editor.
Now, you are ready to start using the CLI for this 'Sentiment Analysis' scenario.
NOTE
After finishing this tutorial you can also try with your own datasets as long as they are ready to be used for any of
the ML tasks currently supported by the ML.NET CLI Preview which are 'Binary Classification', 'Classification',
'Regression', and 'Recommendation'.
NOTE
You can try this very same dataset and specify a few minutes for --max-exploration-time (for instance three
minutes so you specify 180 seconds) which will find a better "best model" for you with a different training pipeline
configuration for this dataset (which is pretty small, 1000 rows).
In order to find a "best/good quality" model that is a "production-ready model" targeting larger datasets,
you should make experiments with the CLI usually specifying much more exploration time depending on
the size of the dataset. In fact, in many cases you might require multiple hours of exploration time
especially if the dataset is large on rows and columns.
2. The previous command execution has generated the following assets:
A serialized model .zip ("best model") ready to use.
C# code to run/score that generated model (To make predictions in your end-user apps with that
model).
C# training code used to generate that model (Learning purposes).
A log file with all the iterations explored having specific detailed information about each algorithm
tried with its combination of hyper-parameters and data transformations.
The first two assets (.ZIP file model and C# code to run that model) can directly be used in your end-user
apps (ASP.NET Core web app, services, desktop app, etc.) to make predictions with that generated ML
model.
The third asset, the training code, shows you what ML.NET API code was used by the CLI to train the
generated model, so you can investigate what specific trainer/algorithm and hyper-parameters were
selected by the CLI.
Those enumerated assets are explained in the following steps of the tutorial.
Explore the generated C# code to use for running the model to make
predictions
1. In Visual Studio (2017 or 2019) open the solution generated in the folder named SampleClassification
within your original destination folder (in the tutorial was named /cli-test ). You should see a solution
similar to:
NOTE
In the tutorial we suggest to use Visual Studio, but you can also explore the generated C# code (two projects) with
any text editor and run the generated console app with the dotnet CLI on macOS, Linux or Windows machine.
The generated class librar y containing the serialized ML model (.zip file) and the data classes (data
models) is something you can directly use in your end-user application, even by directly referencing
that class library (or moving the code, as you prefer).
The generated console app contains execution code that you must review and then you usually reuse
the 'scoring code' (code that runs the ML model to make predictions) by moving that simple code ( just
a few lines) to your end-user application where you want to make the predictions.
2. Open the ModelInput.cs and ModelOutput.cs class files within the class library project. You will see
that these classes are 'data classes' or POCO classes used to hold data. It is 'boilerplate code' but useful to
have it generated if your dataset has tens or even hundreds of columns.
The ModelInput class is used when reading data from the dataset.
The ModelOutput class is used to get the prediction result (prediction data).
3. Open the Program.cs file and explore the code. In just a few lines, you are able to run the model and
make a sample prediction.
static void Main(string[] args)
{
// Create single instance of sample data from first line of dataset for model input
ModelInput sampleData = new ModelInput()
{
Col0 = @"Wow... Loved this place.",
};
Console.WriteLine("Using model to make single prediction -- Comparing actual Col1 with predicted
Col1 from sample data...\n\n");
Console.WriteLine($"Col0: {sampleData.Col0}");
Console.WriteLine($"\n\nPredicted Col1 value {predictionResult.Prediction} \nPredicted Col1
scores: [{String.Join(",", predictionResult.Score)}]\n\n");
Console.WriteLine("=============== End of process, hit any key to finish ===============");
Console.ReadKey();
}
The first lines of code create a single sample data, in this case based on the first row of your
dataset to be used for the prediction. You can also create you own 'hard-coded' data by updating
the code:
The next line of code uses the ConsumeModel.Predict() method on the specified input data to make
a prediction and return the results (based on the ModelOutput.cs schema).
The last lines of code print out the properties of the sample data (in this case the Comment) as
well as the Sentiment prediction and corresponding Scores for positive sentiment (1) and negative
sentiment (2).
4. Run the project, either using the original sample data loaded from the first row of the dataset or by
providing your own custom hard-coded sample data. You should get a prediction comparable to:
)
1. Try changing the hard-coded sample data to other sentences with different sentiment and see how the model
predicts positive or negative sentiment.
Explore the generated C# code that was used to train the "best
quality" model
For more advanced learning purposes, you can also explore the generated C# code that was used by the CLI tool
to train the generated model.
That 'training model code' is currently generated in the custom class generated named ModelBuilder so you can
investigate that training code.
More importantly, for this particular scenario (Sentiment Analysis model) you can also compare that generated
training code with the code explained in the following tutorial:
Compare: Tutorial: Use ML.NET in a sentiment analysis binary classification scenario.
It is interesting to compare the chosen algorithm and pipeline configuration in the tutorial with the code
generated by the CLI tool. Depending on how much time you spend iterating and searching for better models,
the chosen algorithm might be different along with its particular hyper-parameters and pipeline configuration.
In this tutorial, you learned how to:
Prepare your data for the selected ML task (problem to solve)
Run the 'mlnet classification' command in the CLI tool
Review the quality metric results
Understand the generated C# code to run the model (Code to use in your end-user app)
Explore the generated C# code that was used to train the "best quality" model (earning purposes)
See also
Automate model training with the ML.NET CLI
Tutorial: Running ML.NET models on scalable ASP.NET Core web apps and WebAPIs
Sample: Scalable ML.NET model on ASP.NET Core WebAPI
ML.NET CLI auto-train command reference guide
Telemetry in ML.NET CLI
Tutorial: Analyze sentiment of website comments in
a web application using ML.NET Model Builder
4/14/2020 • 9 minutes to read • Edit Online
Learn how to analyze sentiment from comments in real time inside a web application.
This tutorial shows you how to create an ASP.NET Core Razor Pages application that classifies sentiment from
website comments in real time.
In this tutorial, you learn how to:
Create an ASP.NET Core Razor Pages application
Prepare and understand the data
Choose a scenario
Load the data
Train the model
Evaluate the model
Use the model for predictions
NOTE
Model Builder is currently in Preview.
You can find the source code for this tutorial at the dotnet/machinelearning-samples repository.
Pre-requisites
For a list of pre-requisites and installation instructions, visit the Model Builder installation guide.
Choose a scenario
To train your model, you need to select from the list of available machine learning scenarios provided by Model
Builder.
1. In Solution Explorer , right-click the SentimentRazor project, and select Add > Machine Learning .
2. For this sample, the scenario is sentiment analysis. In the scenario step of the Model Builder tool, select the
Sentiment Analysis scenario.
using System.IO;
using Microsoft.Extensions.ML;
using SentimentRazorML.Model;
4. Create a global variable to store the location of the trained model file.
5. The model file is stored in the build directory alongside the assembly files of your application. To make it
easier to access, create a helper method called GetAbsolutePath after the Configure method
6. Use the GetAbsolutePath method in the Startup class constructor to set the _modelPath .
_modelPath = GetAbsolutePath("MLModel.zip");
using Microsoft.Extensions.ML;
using SentimentRazorML.Model;
In order to use the PredictionEnginePool configured in the Startup class, you have to inject it into the
constructor of the model where you want to use it.
2. Add a variable to reference the PredictionEnginePool inside the IndexModel class.
3. Create a constructor in the IndexModel class and inject the PredictionEnginePool service into it.
4. Create a method handler that uses the PredictionEnginePool to make predictions from user input
received from the web page.
a. Below the OnGet method, create a new method called OnGetAnalyzeSentiment
b. Inside the OnGetAnalyzeSentiment method, return Neutral sentiment if the input from the user is
blank or null.
e. Convert the predicted bool value into toxic or not toxic with the following code.
var sentiment = Convert.ToBoolean(prediction.Prediction) ? "Toxic" : "Not Toxic";
return Content(sentiment);
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<div class="text-center">
<h2>Live Sentiment</h2>
<div class="sentiment">
<h4>Your sentiment is...</h4>
<p> </p>
<div class="marker">
<div id="markerPosition" style="left: 45%;">
<div>▲</div>
<label id="markerValue">Neutral</label>
</div>
</div>
</div>
</div>
2. Next, add css styling code to the end of the site.css page in the wwwroot\css directory:
/* Style for sentiment display */
.sentiment {
background-color: #eee;
position: relative;
display: inline-block;
padding: 1rem;
padding-bottom: 0;
border-radius: 1rem;
}
.sentiment h4 {
font-size: 16px;
text-align: center;
margin: 0;
padding: 0;
}
.sentiment p {
font-size: 50px;
}
.sentiment .marker {
position: relative;
left: 22px;
width: calc(100% - 68px);
}
3. After that, add code to send inputs from the web page to the OnGetAnalyzeSentiment handler.
a. In the site.js file located in the wwwroot\js directory, create a function called getSentiment to make
a GET HTTP request with the user input to the OnGetAnalyzeSentiment handler.
function getSentiment(userInput) {
return fetch(`Index?handler=AnalyzeSentiment&text=${userInput}`)
.then((response) => {
return response.text();
})
}
b. Below that, add another function called updateMarker to dynamically update the position of the
marker on the web page as sentiment is predicted.
function updateMarker(markerPosition, sentiment) {
$("#markerPosition").attr("style", `left:${markerPosition}%`);
$("#markerValue").text(sentiment);
}
c. Create an event handler function called updateSentiment to get the input from the user, send it to
the OnGetAnalyzeSentiment function using the getSentiment function and update the marker with
the updateMarker function.
function updateSentiment() {
getSentiment(userInput)
.then((sentiment) => {
switch (sentiment) {
case "Not Toxic":
updateMarker(100.0,sentiment);
break;
case "Toxic":
updateMarker(0.0,sentiment);
break;
default:
updateMarker(45.0, "Neutral");
}
});
}
d. Finally, register the event handler and bind it to the textarea element with the id=Message
attribute.
Next steps
In this tutorial, you learned how to:
Create an ASP.NET Core Razor Pages application
Prepare and understand the data
Choose a scenario
Load the data
Train the model
Evaluate the model
Use the model for predictions
Additional Resources
To learn more about topics mentioned in this tutorial, visit the following resources:
Model Builder Scenarios
Binary Classification
Binary Classification Model Metrics
Tutorial: Classify the severity of restaurant health
violations with Model Builder
3/31/2020 • 6 minutes to read • Edit Online
Learn how to build a multiclass classification model using Model Builder to categorize the risk level of restaurant
violations found during health inspections.
In this tutorial, you learn how to:
Prepare and understand the data
Choose a scenario
Load data from a database
Train the model
Evaluate the model
Use the model for predictions
NOTE
Model Builder is currently in Preview.
Prerequisites
For a list of prerequisites and installation instructions, visit the Model Builder installation guide.
InspectionType : the type of inspection. This can either be a first-time inspection for a new establishment, a
routine inspection, a complaint inspection, and many other types.
ViolationDescription : a description of the violation found during inspection.
RiskCategor y : the risk severity a violation poses to public health and safety.
The label is the column you want to predict. When performing a classification task, the goal is to assign a
category (text or numerical). In this classification scenario, the severity of the violation is assigned the value of
low, moderate, or high risk. Therefore, the RiskCategor y is the label. The features are the inputs you give the
model to predict the label . In this case, the InspectionType and ViolationDescription are used as features
or inputs to predict the RiskCategor y .
Choose a scenario
To train your model, select from the list of available machine learning scenarios provided by Model Builder. In
this case, the scenario is Issue Classification.
1. In Solution Explorer , right-click the RestaurantViolations project, and select Add > Machine Learning .
2. For this sample, the scenario is multiclass classification. In the Scenario step of Model Builder, select the Issue
Classification scenario.
1. In the code step of Model Builder, select Add Projects to add the autogenerated projects to the solution.
2. Open the Program.cs file in the RestaurantViolations project.
3. Add the following using statement to reference the RestaurantViolationsML.Model project:
using RestaurantViolationsML.Model;
4. To make a prediction on new data using the model, create a new instance of the ModelInput class inside
the Main method of your application. Notice that the risk category is not part of the input. This is
because the model generates the prediction for it.
5. Use the Predict method from the ConsumeModel class. The Predict method loads the trained model,
creates a PredictionEngine for the model, and uses it to make predictions on new data.
// Make prediction
ModelOutput result = ConsumeModel.Predict(input);
// Print Prediction
Console.WriteLine($"Inspection type: {input.InspectionType}");
Console.WriteLine($"Violation description: {input.ViolationDescription}");
Console.WriteLine($"Predicted risk category: {result.Prediction}");
Console.ReadKey();
If you need to reference the generated projects at a later time inside of another solution, you can find them
inside the C:\Users\%USERNAME%\AppData\Local\Temp\MLVSTools directory.
Congratulations! You've successfully built a machine learning model to categorize the risk of health violations
using Model Builder. You can find the source code for this tutorial at the dotnet/machinelearning-samples
GitHub repository.
Additional resources
To learn more about topics mentioned in this tutorial, visit the following resources:
Model Builder Scenarios
Multiclass Classification
Multiclass Classification Model Metrics
ML.NET tutorials
1/7/2020 • 2 minutes to read • Edit Online
The following tutorials enable you to understand how to use ML.NET to build custom machine learning
solutions and integrate them into your .NET applications:
Sentiment analysis: demonstrates how to apply a binar y classification task using ML.NET.
GitHub issue classification: demonstrates how to apply a multiclass classification task using ML.NET.
Price predictor: demonstrates how to apply a regression task using ML.NET.
Iris clustering: demonstrates how to apply a clustering task using ML.NET.
Recommendation: generate movie recommendations based on previous user ratings
Image classification: demonstrates how to retrain an existing TensorFlow model to create a custom image
classifier using ML.NET.
Anomaly detection: demonstrates how to build an anomaly detection application for product sales data
analysis.
Detect objects in images: demonstrates how to detect objects in images using a pre-trained ONNX model.
Classify sentiment of movie reviews: learn to load a pre-trained TensorFlow model to classify the sentiment
of movie reviews.
Next Steps
For more examples that use ML.NET, check out the dotnet/machinelearning-samples GitHub repository.
Tutorial: Analyze sentiment of website comments
with binary classification in ML.NET
11/2/2020 • 12 minutes to read • Edit Online
This tutorial shows you how to create a .NET Core console application that classifies sentiment from website
comments and takes the appropriate action. The binary sentiment classifier uses C# in Visual Studio 2017.
In this tutorial, you learn how to:
Create a console application
Prepare data
Load the data
Build and train the model
Evaluate the model
Use the model to make a prediction
See the results
You can find the source code for this tutorial at the dotnet/samples repository.
Prerequisites
Visual Studio 2017 version 15.6 or later with the ".NET Core cross-platform development" workload
installed
UCI Sentiment Labeled Sentences dataset (ZIP file)
NOTE
This sample uses the latest stable version of the NuGet packages mentioned unless otherwise stated.
In Solution Explorer, right-click on your project and select Manage NuGet Packages . Choose
"nuget.org" as the package source, and then select the Browse tab. Search for Microsoft.ML , select the
package you want, and then select the Install button. Proceed with the installation by agreeing to the
license terms for the package you choose.
1. Download UCI Sentiment Labeled Sentences dataset ZIP file, and unzip.
2. Copy the yelp_labelled.txt file into the Data directory you created.
3. In Solution Explorer, right-click the yelp_labeled.txt file and select Proper ties . Under Advanced ,
change the value of Copy to Output Director y to Copy if newer .
Create classes and define paths
1. Add the following additional using statements to the top of the Program.cs file:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.ML;
using Microsoft.ML.Data;
using static Microsoft.ML.DataOperationsCatalog;
using Microsoft.ML.Trainers;
using Microsoft.ML.Transforms.Text;
2. Add the following code to the line right above the Main method, to create a field to hold the recently
downloaded dataset file path:
3. Next, create classes for your input data and predictions. Add a new class to your project:
In Solution Explorer , right-click the project, and then select Add > New Item .
In the Add New Item dialog box, select Class and change the Name field to SentimentData.cs.
Then, select the Add button.
4. The SentimentData.cs file opens in the code editor. Add the following using statement to the top of
SentimentData.cs:
using Microsoft.ML.Data;
5. Remove the existing class definition and add the following code, which has two classes SentimentData
and SentimentPrediction , to the SentimentData.cs file:
public class SentimentData
{
[LoadColumn(0)]
public string SentimentText;
[LoadColumn(1), ColumnName("Label")]
public bool Sentiment;
}
[ColumnName("PredictedLabel")]
public bool Prediction { get; set; }
SentimentPrediction is the prediction class used after model training. It inherits from SentimentData so that the
input SentimentText can be displayed along with the output prediction. The Prediction boolean is the value
that the model predicts when supplied with new input SentimentText .
The output class SentimentPrediction contains two other properties calculated by the model: Score - the raw
score calculated by the model, and Probability - the score calibrated to the likelihood of the text having
positive sentiment.
For this tutorial, the most important property is Prediction .
2. Add the following as the next line of code in the Main() method:
3. Create the LoadData() method, just after the Main() method, using the following code:
The LoadFromTextFile() method defines the data schema and reads in the file. It takes in the data path
variables and returns an IDataView .
Split the dataset for model training and testing
When preparing a model, you use part of the dataset to train it and part of the dataset to test the model's
accuracy.
1. To split the loaded data into the needed datasets, add the following code as the next line in the
LoadData() method:
The previous code uses the TrainTestSplit() method to split the loaded dataset into train and test datasets
and return them in the DataOperationsCatalog.TrainTestData class. Specify the test set percentage of data
with the testFraction parameter. The default is 10%, in this case you use 20% to evaluate more data.
2. Return the splitDataView at the end of the LoadData() method:
return splitDataView;
The FeaturizeText() method in the previous code converts the text column ( SentimentText ) into a
numeric key type Features column used by the machine learning algorithm and adds it as a new dataset
column:
.Append(mlContext.BinaryClassification.Trainers.SdcaLogisticRegression(labelColumnName: "Label",
featureColumnName: "Features"));
The Fit() method trains your model by transforming the dataset and applying the training.
Return the model trained to use for evaluation
Return the model at the end of the BuildAndTrainModel() method:
return model;
The previous code uses the Transform() method to make predictions for multiple provided input rows of
a test dataset.
4. Evaluate the model by adding the following as the next line of code in the Evaluate() method:
Once you have the prediction set ( predictions ), the Evaluate() method assesses the model, which compares the
predicted values with the actual Labels in the test dataset and returns a CalibratedBinaryClassificationMetrics
object on how the model is performing.
Displaying the metrics for model validation
Use the following code to display the metrics:
Console.WriteLine();
Console.WriteLine("Model quality metrics evaluation");
Console.WriteLine("--------------------------------");
Console.WriteLine($"Accuracy: {metrics.Accuracy:P2}");
Console.WriteLine($"Auc: {metrics.AreaUnderRocCurve:P2}");
Console.WriteLine($"F1Score: {metrics.F1Score:P2}");
Console.WriteLine("=============== End of model evaluation ===============");
The Accuracy metric gets the accuracy of a model, which is the proportion of correct predictions in the
test set.
The AreaUnderRocCurve metric indicates how confident the model is correctly classifying the positive and
negative classes. You want the AreaUnderRocCurve to be as close to one as possible.
The F1Score metric gets the model's F1 score, which is a measure of balance between precision and
recall. You want the F1Score to be as close to one as possible.
Predict the test data outcome
1. Create the UseModelWithSingleItem() method, just after the Evaluate() method, using the following
code:
UseModelWithSingleItem(mlContext, model);
3. Add the following code to create as the first line in the UseModelWithSingleItem() Method:
The PredictionEngine is a convenience API, which allows you to perform a prediction on a single instance
of data. PredictionEngine is not thread-safe. It's acceptable to use in single-threaded or prototype
environments. For improved performance and thread safety in production environments, use the
PredictionEnginePool service, which creates an ObjectPool of PredictionEngine objects for use
throughout your application. See this guide on how to use PredictionEnginePool in an ASP.NET Core Web
API.
NOTE
PredictionEnginePool service extension is currently in preview.
4. Add a comment to test the trained model's prediction in the UseModelWithSingleItem() method by
creating an instance of SentimentData :
5. Pass the test comment data to the PredictionEngine by adding the following as the next lines of code in
the UseModelWithSingleItem() method:
Console.WriteLine();
Console.WriteLine("=============== Prediction Test of model with a single sample and test dataset
===============");
Console.WriteLine();
Console.WriteLine($"Sentiment: {resultPrediction.SentimentText} | Prediction:
{(Convert.ToBoolean(resultPrediction.Prediction) ? "Positive" : "Negative")} | Probability:
{resultPrediction.Probability} ");
3. Add some comments to test the trained model's predictions in the UseModelWithBatchItems() method:
// Use model to predict whether comment data is Positive (1) or Negative (0).
IEnumerable<SentimentPrediction> predictedResults = mlContext.Data.CreateEnumerable<SentimentPrediction>
(predictions, reuseRowObject: false);
Console.WriteLine();
Results
Your results should be similar to the following. During processing, messages are displayed. You may see
warnings, or processing messages. These have been removed from the following results for clarity.
Model quality metrics evaluation
--------------------------------
Accuracy: 83.96%
Auc: 90.51%
F1Score: 84.04%
=============== Prediction Test of model with a single sample and test dataset ===============
Sentiment: This was a very bad steak | Prediction: Negative | Probability: 0.1027377
=============== End of Predictions ===============
Congratulations! You've now successfully built a machine learning model for classifying and predicting
messages sentiment.
Building successful models is an iterative process. This model has initial lower quality as the tutorial uses small
datasets to provide quick model training. If you aren't satisfied with the model quality, you can try to improve it
by providing larger training datasets or by choosing different training algorithms with different hyper-
parameters for each algorithm.
You can find the source code for this tutorial at the dotnet/samples repository.
Next steps
In this tutorial, you learned how to:
Create a console application
Prepare data
Load the data
Build and train the model
Evaluate the model
Use the model to make a prediction
See the results
Advance to the next tutorial to learn more
Issue Classification
Tutorial: Categorize support issues using multiclass
classification with ML.NET
11/2/2020 • 13 minutes to read • Edit Online
This sample tutorial illustrates using ML.NET to create a GitHub issue classifier to train a model that classifies
and predicts the Area label for a GitHub issue via a .NET Core console application using C# in Visual Studio.
In this tutorial, you learn how to:
Prepare your data
Transform the data
Train the model
Evaluate the model
Predict with the trained model
Deploy and Predict with a loaded model
You can find the source code for this tutorial at the dotnet/samples repository.
Prerequisites
Visual Studio 2019 or later or Visual Studio 2017 version 15.6 or later with the ".NET Core cross-platform
development" workload installed.
The GitHub issues tab separated file (issues_train.tsv).
The GitHub issues test tab separated file (issues_test.tsv).
NOTE
This sample uses the latest stable version of the NuGet packages mentioned unless otherwise stated.
In Solution Explorer, right-click on your project and select Manage NuGet Packages . Choose
"nuget.org" as the Package source, select the Browse tab, search for Microsoft.ML and select the Install
button. Select the OK button on the Preview Changes dialog and then select the I Accept button on the
License Acceptance dialog if you agree with the license terms for the packages listed.
Prepare your data
1. Download the issues_train.tsv and the issues_test.tsv data sets and save them to the Data folder
previously created. The first dataset trains the machine learning model and the second can be used to
evaluate how accurate your model is.
2. In Solution Explorer, right-click each of the *.tsv files and select Proper ties . Under Advanced , change the
value of Copy to Output Director y to Copy if newer .
Create classes and define paths
Add the following additional using statements to the top of the Program.cs file:
using System;
using System.IO;
using System.Linq;
using Microsoft.ML;
Create three global fields to hold the paths to the recently downloaded files, and global variables for the
MLContext , DataView , and PredictionEngine :
_trainDataPath has the path to the dataset used to train the model.
_testDataPath has the path to the dataset used to evaluate the model.
_modelPath has the path where the trained model is saved.
_mlContext is the MLContext that provides processing context.
_trainingDataView is the IDataView used to process the training dataset.
_predEngine is the PredictionEngine<TSrc,TDst> used for single predictions.
Add the following code to the line directly above the Main method to specify those paths and the other
variables:
Create some classes for your input data and predictions. Add a new class to your project:
1. In Solution Explorer , right-click the project, and then select Add > New Item .
2. In the Add New Item dialog box, select Class and change the Name field to GitHubIssueData.cs. Then,
select the Add button.
The GitHubIssueData.cs file opens in the code editor. Add the following using statement to the top of
GitHubIssueData.cs:
using Microsoft.ML.Data;
Remove the existing class definition and add the following code, which has two classes GitHubIssue and
IssuePrediction , to the GitHubIssueData.cs file:
The label is the column you want to predict. The identified Features are the inputs you give the model to
predict the Label.
Use the LoadColumnAttribute to specify the indices of the source columns in the data set.
GitHubIssue is the input dataset class and has the following String fields:
the first column ID (GitHub Issue ID)
the second column Area (the prediction for training)
the third column Title (GitHub issue title) is the first feature used for predicting the Area
the fourth column Description is the second feature used for predicting the Area
IssuePrediction is the class used for prediction after the model has been trained. It has a single string ( Area )
and a PredictedLabel ColumnName attribute. The PredictedLabel is used during prediction and evaluation. For
evaluation, an input with training data, the predicted values, and the model are used.
All ML.NET operations start in the MLContext class. Initializing mlContext creates a new ML.NET environment
that can be shared across the model creation workflow objects. It's similar, conceptually, to DBContext in
Entity Framework .
The LoadFromTextFile() defines the data schema and reads in the file. It takes in the data path variables and
returns an IDataView .
Add the following as the next line of code in the Main method:
Next, call mlContext.Transforms.Text.FeaturizeText , which transforms the text ( Title and Description )
columns into a numeric vector for each called TitleFeaturized and DescriptionFeaturized . Append the
featurization for both columns to the pipeline with the following code:
The last step in data preparation combines all of the feature columns into the Features column using the
Concatenate() method. By default, a learning algorithm processes only features from the Features column.
Append this transformation to the pipeline with the following code:
Next, append a AppendCacheCheckpoint to cache the DataView so when you iterate over the data multiple
times using the cache might get better performance, as with the following code:
.AppendCacheCheckpoint(_mlContext);
WARNING
Use AppendCacheCheckpoint for small/medium datasets to lower training time. Do NOT use it (remove
.AppendCacheCheckpoint()) when handling very large datasets.
return pipeline;
This step handles preprocessing/featurization. Using additional components available in ML.NET can enable
better results with your model.
var trainingPipeline =
pipeline.Append(_mlContext.MulticlassClassification.Trainers.SdcaMaximumEntropy("Label", "Features"))
.Append(_mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel"));
The SdcaMaximumEntropy is your multiclass classification training algorithm. This is appended to the pipeline
and accepts the featurized Title and Description ( Features ) and the Label input parameters to learn from
the historic data.
Train the model
Fit the model to the splitTrainSet data and return the trained model by adding the following as the next line of
code in the BuildAndTrainModel() method:
_trainedModel = trainingPipeline.Fit(trainingDataView);
The Fit() method trains your model by transforming the dataset and applying the training.
The PredictionEngine is a convenience API, which allows you to pass in and then perform a prediction on a
single instance of data. Add this as the next line in the BuildAndTrainModel() method:
return trainingPipeline;
Evaluate(_trainingDataView.Schema);
As you did previously with the training dataset, load the test dataset by adding the following code to the
Evaluate method:
The Evaluate() method computes the quality metrics for the model using the specified dataset. It returns a
MulticlassClassificationMetrics object that contains the overall metrics computed by multiclass classification
evaluators. To display the metrics to determine the quality of the model, you need to get them first. Notice the
use of the Transform() method of the machine learning _trainedModel global variable (an ITransformer) to input
the features and return predictions. Add the following code to the Evaluate method as the next line:
Add the following code to your SaveModelAsFile method. This code uses the Save method to serialize and store
the trained model as a zip file.
PredictIssue();
Create the PredictIssue method, just after the Evaluate method (and just before the SaveModelAsFile
method), using the following code:
Add a GitHub issue to test the trained model's prediction in the Predict method by creating an instance of
GitHubIssue :
GitHubIssue singleIssue = new GitHubIssue() { Title = "Entity Framework crashes", Description = "When
connecting to the database, EF is crashing" };
As you did previously, create a PredictionEngine instance with the following code:
The PredictionEngine is a convenience API, which allows you to perform a prediction on a single instance of
data. PredictionEngine is not thread-safe. It's acceptable to use in single-threaded or prototype environments.
For improved performance and thread safety in production environments, use the PredictionEnginePool
service, which creates an ObjectPool of PredictionEngine objects for use throughout your application. See this
guide on how to use PredictionEnginePool in an ASP.NET Core Web API.
NOTE
PredictionEnginePool service extension is currently in preview.
Use the PredictionEngine to predict the Area GitHub label by adding the following code to the PredictIssue
method for the prediction:
Results
Your results should be similar to the following. As the pipeline processes, it displays messages. You may see
warnings, or processing messages. These messages have been removed from the following results for clarity.
=============== Single Prediction just-trained-model - Result: area-System.Net ===============
************************************************************************************************************
*
* Metrics for Multi-class Classification model - Test Data
*-----------------------------------------------------------------------------------------------------------
-
* MicroAccuracy: 0.738
* MacroAccuracy: 0.668
* LogLoss: .919
* LogLossReduction: .643
************************************************************************************************************
*
=============== Single Prediction - Result: area-System.Data ===============
Congratulations! You've now successfully built a machine learning model for classifying and predicting an Area
label for a GitHub issue. You can find the source code for this tutorial at the dotnet/samples repository.
Next steps
In this tutorial, you learned how to:
Prepare your data
Transform the data
Train the model
Evaluate the model
Predict with the trained model
Deploy and Predict with a loaded model
Advance to the next tutorial to learn more
Taxi Fare Predictor
Tutorial: Predict prices using regression with ML.NET
11/2/2020 • 10 minutes to read • Edit Online
This tutorial illustrates how to build a regression model using ML.NET to predict prices, specifically, New York
City taxi fares.
In this tutorial, you learn how to:
Prepare and understand the data
Load and transform the data
Choose a learning algorithm
Train the model
Evaluate the model
Use the model for predictions
Prerequisites
Visual Studio 2019 or later or Visual Studio 2017 version 15.6 or later with the ".NET Core cross-platform
development" workload installed.
NOTE
This sample uses the latest stable version of the NuGet packages mentioned unless otherwise stated.
In Solution Explorer , right-click the project and select Manage NuGet Packages . Choose "nuget.org"
as the Package source, select the Browse tab, search for Microsoft.ML , select the package in the list, and
select the Install button. Select the OK button on the Preview Changes dialog and then select the I
Accept button on the License Acceptance dialog if you agree with the license terms for the packages
listed. Do the same for the Microsoft.ML.FastTree NuGet package.
using Microsoft.ML.Data;
Remove the existing class definition and add the following code, which has two classes TaxiTrip and
TaxiTripFarePrediction , to the TaxiTrip.cs file:
[LoadColumn(1)]
public string RateCode;
[LoadColumn(2)]
public float PassengerCount;
[LoadColumn(3)]
public float TripTime;
[LoadColumn(4)]
public float TripDistance;
[LoadColumn(5)]
public string PaymentType;
[LoadColumn(6)]
public float FareAmount;
}
NOTE
Use the float type to represent floating-point values in the input and prediction data classes.
using System;
using System.IO;
using Microsoft.ML;
You need to create three fields to hold the paths to the files with data sets and the file to save the model:
_trainDataPath contains the path to the file with the data set used to train the model.
_testDataPath contains the path to the file with the data set used to evaluate the model.
_modelPath contains the path to the file where the trained model is stored.
Add the following code right above the Main method to specify those paths and for the _textLoader variable:
All ML.NET operations start in the MLContext class. Initializing mlContext creates a new ML.NET environment
that can be shared across the model creation workflow objects. It's similar, conceptually, to DBContext in Entity
Framework.
Initialize variables in Main
Replace the Console.WriteLine("Hello World!") line in the Main method with the following code to declare and
initialize the mlContext variable:
Add the following as the next line of code in the Main method to call the Train method:
As you want to predict the taxi trip fare, the FareAmount column is the Label that you will predict (the output of
the model). Use the CopyColumnsEstimator transformation class to copy FareAmount , and add the following code:
The algorithm that trains the model requires numeric features, so you have to transform the categorical data (
VendorId , RateCode , and PaymentType ) values into numbers ( VendorIdEncoded , RateCodeEncoded , and
PaymentTypeEncoded ). To do that, use the OneHotEncodingTransformer transformation class, which assigns
different numeric key values to the different values in each of the columns, and add the following code:
.Append(mlContext.Transforms.Categorical.OneHotEncoding(outputColumnName: "VendorIdEncoded",
inputColumnName:"VendorId"))
.Append(mlContext.Transforms.Categorical.OneHotEncoding(outputColumnName: "RateCodeEncoded",
inputColumnName: "RateCode"))
.Append(mlContext.Transforms.Categorical.OneHotEncoding(outputColumnName: "PaymentTypeEncoded",
inputColumnName: "PaymentType"))
The last step in data preparation combines all of the feature columns into the Features column using the
mlContext.Transforms.Concatenate transformation class. By default, a learning algorithm processes only features
from the Features column. Add the following code:
.Append(mlContext.Regression.Trainers.FastTree());
Train the model
Fit the model to the training dataview and return the trained model by adding the following line of code in the
Train() method:
The Fit() method trains your model by transforming the dataset and applying the training.
Return the trained model with the following line of code in the Train() method:
return model;
Evaluate(mlContext, model);
Load the test dataset using the LoadFromTextFile() method. Evaluate the model using this dataset as a quality
check by adding the following code in the Evaluate method:
Next, transform the Test data by adding the following code to Evaluate() :
The Transform() method makes predictions for the test dataset input rows.
The RegressionContext.Evaluate method computes the quality metrics for the PredictionModel using the
specified dataset. It returns a RegressionMetrics object that contains the overall metrics computed by regression
evaluators.
To display these to determine the quality of the model, you need to get the metrics first. Add the following code
as the next line in the Evaluate method:
Once you have the prediction set, the Evaluate() method assesses the model, which compares the predicted
values with the actual Labels in the test dataset and returns metrics on how the model is performing.
Add the following code to evaluate the model and produce the evaluation metrics:
Console.WriteLine();
Console.WriteLine($"*************************************************");
Console.WriteLine($"* Model quality metrics evaluation ");
Console.WriteLine($"*------------------------------------------------");
RSquared is another evaluation metric of the regression models. RSquared takes values between 0 and 1. The
closer its value is to 1, the better the model is. Add the following code into the Evaluate method to display the
RSquared value:
RMS is one of the evaluation metrics of the regression model. The lower it is, the better the model is. Add the
following code into the Evaluate method to display the RMS value:
TestSinglePrediction(mlContext, model);
Use the PredictionEngine to predict the fare by adding the following code to TestSinglePrediction() :
The PredictionEngine is a convenience API, which allows you to perform a prediction on a single instance of
data. PredictionEngine is not thread-safe. It's acceptable to use in single-threaded or prototype environments.
For improved performance and thread safety in production environments, use the PredictionEnginePool
service, which creates an ObjectPool of PredictionEngine objects for use throughout your application. See this
guide on how to use PredictionEnginePool in an ASP.NET Core Web API.
NOTE
PredictionEnginePool service extension is currently in preview.
This tutorial uses one test trip within this class. Later you can add other scenarios to experiment with the model.
Add a trip to test the trained model's prediction of cost in the TestSinglePrediction() method by creating an
instance of TaxiTrip :
Next, predict the fare based on a single instance of the taxi trip data and pass it to the PredictionEngine by
adding the following as the next lines of code in the TestSinglePrediction() method:
Console.WriteLine($"**********************************************************************");
Console.WriteLine($"Predicted fare: {prediction.FareAmount:0.####}, actual fare: 15.5");
Console.WriteLine($"**********************************************************************");
Run the program to see the predicted taxi fare for your test case.
Congratulations! You've now successfully built a machine learning model for predicting taxi trip fares, evaluated
its accuracy, and used it to make predictions. You can find the source code for this tutorial at the dotnet/samples
GitHub repository.
Next steps
In this tutorial, you learned how to:
Prepare and understand the data
Create a learning pipeline
Load and transform the data
Choose a learning algorithm
Train the model
Evaluate the model
Use the model for predictions
Advance to the next tutorial to learn more.
Iris clustering
Tutorial: Categorize iris flowers using k-means
clustering with ML.NET
11/2/2020 • 7 minutes to read • Edit Online
This tutorial illustrates how to use ML.NET to build a clustering model for the iris flower data set.
In this tutorial, you learn how to:
Understand the problem
Select the appropriate machine learning task
Prepare the data
Load and transform the data
Choose a learning algorithm
Train the model
Use the model for predictions
Prerequisites
Visual Studio 2019 or later or Visual Studio 2017 version 15.6 or later with the ".NET Core cross-platform
development" workload installed.
NOTE
This sample uses the latest stable version of the NuGet packages mentioned unless otherwise stated.
In Solution Explorer , right-click the project and select Manage NuGet Packages . Choose "nuget.org"
as the Package source, select the Browse tab, search for Microsoft.ML and select the Install button.
Select the OK button on the Preview Changes dialog and then select the I Accept button on the
License Acceptance dialog if you agree with the license terms for the packages listed.
using Microsoft.ML.Data;
Remove the existing class definition and add the following code, which defines the classes IrisData and
ClusterPrediction , to the IrisData.cs file:
public class IrisData
{
[LoadColumn(0)]
public float SepalLength;
[LoadColumn(1)]
public float SepalWidth;
[LoadColumn(2)]
public float PetalLength;
[LoadColumn(3)]
public float PetalWidth;
}
[ColumnName("Score")]
public float[] Distances;
}
IrisData is the input data class and has definitions for each feature from the data set. Use the LoadColumn
attribute to specify the indices of the source columns in the data set file.
The ClusterPrediction class represents the output of the clustering model applied to an IrisData instance. Use
the ColumnName attribute to bind the PredictedClusterId and Distances fields to the PredictedLabel and
Score columns respectively. In case of the clustering task those columns have the following meaning:
PredictedLabel column contains the ID of the predicted cluster.
Score column contains an array with squared Euclidean distances to the cluster centroids. The array length is
equal to the number of clusters.
NOTE
Use the float type to represent floating-point values in the input and prediction data classes.
Add the following code right above the Main method to specify those paths:
To make the preceding code compile, add the following using directives at the top of the Program.cs file:
using System;
using System.IO;
Create ML context
Add the following additional using directives to the top of the Program.cs file:
using Microsoft.ML;
using Microsoft.ML.Data;
In the Main method, replace the Console.WriteLine("Hello World!"); line with the following code:
The Microsoft.ML.MLContext class represents the machine learning environment and provides mechanisms for
logging and entry points for data loading, model training, prediction, and other tasks. This is comparable
conceptually to using DbContext in Entity Framework.
The generic MLContext.Data.LoadFromTextFile extension method infers the data set schema from the provided
IrisData type and returns IDataView which can be used as input for transformers.
The code specifies that the data set should be split in three clusters.
The PredictionEngine is a convenience API, which allows you to perform a prediction on a single instance of
data. PredictionEngine is not thread-safe. It's acceptable to use in single-threaded or prototype environments.
For improved performance and thread safety in production environments, use the PredictionEnginePool
service, which creates an ObjectPool of PredictionEngine objects for use throughout your application. See this
guide on how to use PredictionEnginePool in an ASP.NET Core Web API.
NOTE
PredictionEnginePool service extension is currently in preview.
This tutorial introduces one iris data instance within this class. You can add other scenarios to experiment with
the model. Add the following code into the TestIrisData class:
To find out the cluster to which the specified item belongs to, go back to the Program.cs file and add the
following code into the Main method:
var prediction = predictor.Predict(TestIrisData.Setosa);
Console.WriteLine($"Cluster: {prediction.PredictedClusterId}");
Console.WriteLine($"Distances: {string.Join(" ", prediction.Distances)}");
Run the program to see which cluster contains the specified data instance and squared distances from that
instance to the cluster centroids. Your results should be similar to the following:
Cluster: 2
Distances: 11.69127 0.02159119 25.59896
Congratulations! You've now successfully built a machine learning model for iris clustering and used it to make
predictions. You can find the source code for this tutorial at the dotnet/samples GitHub repository.
Next steps
In this tutorial, you learned how to:
Understand the problem
Select the appropriate machine learning task
Prepare the data
Load and transform the data
Choose a learning algorithm
Train the model
Use the model for predictions
Check out our GitHub repository to continue learning and find more samples.
dotnet/machinelearning GitHub repository
Tutorial: Build a movie recommender using matrix
factorization with ML.NET
11/2/2020 • 17 minutes to read • Edit Online
This tutorial shows you how to build a movie recommender with ML.NET in a .NET Core console application. The
steps use C# and Visual Studio 2019.
In this tutorial, you learn how to:
Select a machine learning algorithm
Prepare and load your data
Build and train a model
Evaluate a model
Deploy and consume a model
You can find the source code for this tutorial at the dotnet/samples repository.
Prerequisites
Visual Studio 2019 or later or Visual Studio 2017 version 15.6 or later with the ".NET Core cross-platform
development" workload installed.
In Solution Explorer , right-click the project and select Manage NuGet Packages . Choose "nuget.org"
as the Package source, select the Browse tab, search for Microsoft.ML , select the package in the list, and
select the Install button. Select the OK button on the Preview Changes dialog and then select the I
Accept button on the License Acceptance dialog if you agree with the license terms for the packages
listed. Repeat these steps for Microsoft.ML.Recommender .
4. Add the following using statements at the top of your Program.cs file:
using System;
using System.IO;
using Microsoft.ML;
using Microsoft.ML.Trainers;
In machine learning, the columns that are used to make a prediction are called Features, and the column with
the returned prediction is called the Label.
You want to predict movie ratings, so the rating column is the Label . The other three columns, userId ,
movieId , and timestamp are all Features used to predict the Label .
F EAT URES L A B EL
userId rating
movieId
timestamp
It's up to you to decide which Features are used to predict the Label . You can also use methods like
permutation feature importance to help with selecting the best Features .
In this case, you should eliminate the timestamp column as a Feature because the timestamp does not really
affect how a user rates a given movie and thus would not contribute to making a more accurate prediction:
F EAT URES L A B EL
userId rating
movieId
Next you must define your data structure for the input class.
Add a new class to your project:
1. In Solution Explorer , right-click the project, and then select Add > New Item .
2. In the Add New Item dialog box , select Class and change the Name field to MovieRatingData.cs.
Then, select the Add button.
The MovieRatingData.cs file opens in the code editor. Add the following using statement to the top of
MovieRatingData.cs:
using Microsoft.ML.Data;
Create a class called MovieRating by removing the existing class definition and adding the following code in
MovieRatingData.cs:
MovieRating specifies an input data class. The LoadColumn attribute specifies which columns (by column index)
in the dataset should be loaded. The userId and movieId columns are your Features (the inputs you will give
the model to predict the Label ), and the rating column is the Label that you will predict (the output of the
model).
Create another class, MovieRatingPrediction , to represent predicted results by adding the following code after
the MovieRating class in MovieRatingData.cs:
In Program.cs, replace the Console.WriteLine("Hello World!") with the following code inside Main() :
The MLContext class is a starting point for all ML.NET operations, and initializing mlContext creates a new
ML.NET environment that can be shared across the model creation workflow objects. It's similar, conceptually, to
DBContext in Entity Framework.
NOTE
This method will give you an error until you add a return statement in the following steps.
Initialize your data path variables, load the data from the *.csv files, and return the Train and Test data as
IDataView objects by adding the following as the next line of code in LoadData() :
var trainingDataPath = Path.Combine(Environment.CurrentDirectory, "Data", "recommendation-ratings-
train.csv");
var testDataPath = Path.Combine(Environment.CurrentDirectory, "Data", "recommendation-ratings-test.csv");
Data in ML.NET is represented as an IDataView class. IDataView is a flexible, efficient way of describing tabular
data (numeric and text). Data can be loaded from a text file or in real time (for example, SQL database or log
files) to an IDataView object.
The LoadFromTextFile() defines the data schema and reads in the file. It takes in the data path variables and
returns an IDataView . In this case, you provide the path for your Test and Train files and indicate both the
text file header (so it can use the column names properly) and the comma character data separator (the default
separator is a tab).
Add the following code in the Main() method to call your LoadData() method and return the Train and Test
data:
You create Transformers in ML.NET by creating Estimators . Estimators take in data and return Transformers .
The recommendation training algorithm you will use for training your model is an example of an Estimator .
Build an Estimator with the following steps:
Create the BuildAndTrainModel() method, just after the LoadData() method, using the following code:
NOTE
This method will give you an error until you add a return statement in the following steps.
Since userId and movieId represent users and movie titles, not real values, you use the MapValueToKey()
method to transform each userId and each movieId into a numeric key type Feature column (a format
accepted by recommendation algorithms) and add them as new dataset columns:
1 1 4 userKey1 movieKey1
1 3 4 userKey1 movieKey2
1 6 4 userKey1 movieKey3
Choose the machine learning algorithm and append it to the data transformation definitions by adding the
following as the next line of code in BuildAndTrainModel() :
User 1 Watched and liked movie Watched and liked movie Watched and liked movie
User 2 Watched and liked movie Watched and liked movie Has not watched --
RECOMMEND movie
The Matrix Factorization trainer has several Options, which you can read more about in the Algorithm
hyperparameters section below.
Fit the model to the Train data and return the trained model by adding the following as the next line of code in
the BuildAndTrainModel() method:
return model;
The Fit() method trains your model with the provided training dataset. Technically, it executes the Estimator
definitions by transforming the data and applying the training, and it returns back the trained model, which is a
Transformer .
Add the following as the next line of code in the Main() method to call your BuildAndTrainModel() method and
return the trained model:
The Transform() method makes predictions for multiple provided input rows of a test dataset.
Evaluate the model by adding the following as the next line of code in the EvaluateModel() method:
Once you have the prediction set, the Evaluate() method assesses the model, which compares the predicted
values with the actual Labels in the test dataset and returns metrics on how the model is performing.
Print your evaluation metrics to the console by adding the following as the next line of code in the
EvaluateModel() method:
Add the following as the next line of code in the Main() method to call your EvaluateModel() method:
In this output, there are 20 iterations. In each iteration, the measure of error decreases and converges closer and
closer to 0.
The root of mean squared error (RMS or RMSE) is used to measure the differences between the model
predicted values and the test dataset observed values. Technically it's the square root of the average of the
squares of the errors. The lower it is, the better the model is.
R Squared indicates how well data fits a model. Ranges from 0 to 1. A value of 0 means that the data is random
or otherwise can't be fit to the model. A value of 1 means that the model exactly matches the data. You want
your R Squared score to be as close to 1 as possible.
Building successful models is an iterative process. This model has initial lower quality as the tutorial uses small
datasets to provide quick model training. If you aren't satisfied with the model quality, you can try to improve it
by providing larger training datasets or by choosing different training algorithms with different hyper-
parameters for each algorithm. For more information, check out the Improve your model section below.
Use the PredictionEngine to predict the rating by adding the following code to UseModelForSinglePrediction() :
The PredictionEngine is a convenience API, which allows you to perform a prediction on a single instance of
data. PredictionEngine is not thread-safe. It's acceptable to use in single-threaded or prototype environments.
For improved performance and thread safety in production environments, use the PredictionEnginePool
service, which creates an ObjectPool of PredictionEngine objects for use throughout your application. See this
guide on how to use PredictionEnginePool in an ASP.NET Core Web API.
NOTE
PredictionEnginePool service extension is currently in preview.
Create an instance of MovieRating called testInput and pass it to the Prediction Engine by adding the
following as the next lines of code in the UseModelForSinglePrediction() method:
Add the following as the next line of code in the Main() method to call your UseModelForSinglePrediction()
method:
UseModelForSinglePrediction(mlContext, model);
The output of this method should look similar to the following text:
=============== Making a prediction ===============
Movie 10 is recommended for user 6
Save your trained model by adding the following code in the SaveModel() method:
This method saves your trained model to a .zip file (in the "Data" folder), which can then be used in other .NET
applications to make predictions.
Add the following as the next line of code in the Main() method to call your SaveModel() method:
Results
After following the steps above, run your console app (Ctrl + F5). Your results from the single prediction above
should be similar to the following. You may see warnings or processing messages, but these messages have
been removed from the following results for clarity.
=============== Training the model ===============
iter tr_rmse obj
0 1.5382 3.1213e+05
1 0.9223 1.6051e+05
2 0.8691 1.5050e+05
3 0.8413 1.4576e+05
4 0.8145 1.4208e+05
5 0.7848 1.3895e+05
6 0.7552 1.3613e+05
7 0.7259 1.3357e+05
8 0.6987 1.3121e+05
9 0.6747 1.2949e+05
10 0.6533 1.2766e+05
11 0.6353 1.2636e+05
12 0.6209 1.2561e+05
13 0.6072 1.2462e+05
14 0.5965 1.2394e+05
15 0.5868 1.2352e+05
16 0.5782 1.2279e+05
17 0.5713 1.2227e+05
18 0.5637 1.2190e+05
19 0.5604 1.2178e+05
=============== Evaluating the model ===============
Rms: 0.977175077487166
RSquared: 0.43233349213192
=============== Making a prediction ===============
Movie 10 is recommended for user 6
=============== Saving the model to a file ===============
Congratulations! You've now successfully built a machine learning model for recommending movies. You can
find the source code for this tutorial at the dotnet/samples repository.
A L GO RIT H M SC EN A RIO SA M P L E
One Class Matrix Factorization Use this when you only have userId >Try it out
and movieId. This style of
recommendation is based upon the
co-purchase scenario, or products
frequently bought together, which
means it will recommend to customers
a set of products based upon their
own purchase order history.
Field Aware Factorization Machines Use this to make recommendations >Try it out
when you have more Features beyond
userId, productId, and rating (such as
product description or product price).
This method also uses a collaborative
filtering approach.
Resources
The data used in this tutorial is derived from MovieLens Dataset.
Next steps
In this tutorial, you learned how to:
Select a machine learning algorithm
Prepare and load your data
Build and train a model
Evaluate a model
Deploy and consume a model
Advance to the next tutorial to learn more
Sentiment Analysis
Tutorial: Automated visual inspection using transfer
learning with the ML.NET Image Classification API
11/2/2020 • 16 minutes to read • Edit Online
Learn how to train a custom deep learning model using transfer learning, a pretrained TensorFlow model and
the ML.NET Image Classification API to classify images of concrete surfaces as cracked or uncracked.
In this tutorial, you learn how to:
Understand the problem
Learn about ML.NET Image Classification API
Understand the pretrained model
Use transfer learning to train a custom TensorFlow image classification model
Classify images with the custom model
Prerequisites
Visual Studio 2019 or later or Visual Studio 2017 version 15.6 or later with the ".NET Core cross-platform
development" workload installed.
Training process
The Image Classification API starts the training process by loading a pretrained TensorFlow model. The training
process consists of two steps:
1. Bottleneck phase
2. Training phase
Bottleneck phase
During the bottleneck phase, the set of training images is loaded and the pixel values are used as input, or
features, for the frozen layers of the pretrained model. The frozen layers include all of the layers in the neural
network up to the penultimate layer, informally known as the bottleneck layer. These layers are referred to as
frozen because no training will occur on these layers and operations are pass-through. It's at these frozen layers
where the lower-level patterns that help a model differentiate between the different classes are computed. The
larger the number of layers, the more computationally intensive this step is. Fortunately, since this is a one-time
calculation, the results can be cached and used in later runs when experimenting with different parameters.
Training phase
Once the output values from the bottleneck phase are computed, they are used as input to retrain the final layer
of the model. This process is iterative and runs for the number of times specified by model parameters. During
each run, the loss and accuracy are evaluated. Then, the appropriate adjustments are made to improve the
model with the goal of minimizing the loss and maximizing the accuracy. Once training is finished, two model
formats are output. One of them is the .pb version of the model and the other is the .zip ML.NET serialized
version of the model. When working in environments supported by ML.NET, it is recommended to use the .zip
version of the model. However, in environments where ML.NET is not supported, you have the option of using
the .pb version.
NOTE
This sample uses the latest stable version of the NuGet packages mentioned unless otherwise stated.
a. In Solution Explorer, right-click on your project and select Manage NuGet Packages .
b. Choose "nuget.org" as the Package source.
c. Select the Browse tab.
d. Check the Include prerelease checkbox.
e. Search for Microsoft.ML .
f. Select the Install button.
g. Select the OK button on the Preview Changes dialog and then select the I Accept button on the
License Acceptance dialog if you agree with the license terms for the packages listed.
h. Repeat these steps for the Microsoft.ML.Vision , SciSharp.TensorFlow.Redist , and
Microsoft.ML.ImageAnalytics NuGet packages.
Prepare and understand the data
NOTE
The datasets for this tutorial are from Maguire, Marc; Dorafshan, Sattar; and Thomas, Robert J., "SDNET2018: A concrete
crack image dataset for machine learning applications" (2018). Browse all Datasets. Paper 48.
https://digitalcommons.usu.edu/all_datasets/48
SDNET2018 is an image dataset that contains annotations for cracked and non-cracked concrete structures
(bridge decks, walls, and pavement).
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using Microsoft.ML;
using static Microsoft.ML.DataOperationsCatalog;
using Microsoft.ML.Vision;
2. Below the Program class in Program.cs, create a class called ImageData . This class is used to represent the
initially loaded data.
{
public string ImagePath { get; set; }
{
public byte[] Image { get; set; }
{
public string ImagePath { get; set; }
The MLContext class is a starting point for all ML.NET operations, and initializing mlContext creates a new
ML.NET environment that can be shared across the model creation workflow objects. It's similar,
conceptually, to DbContext in Entity Framework.
Load the data
Create data loading utility method
The images are stored in two subdirectories. Before loading the data, it needs to be formatted into a list of
ImageData objects. To do so, create the LoadImagesFromDirectory method below the Main method.
1. Inside the LoadImagesFromDirectory , add the following code to get all of the file paths from the
subdirectories:
searchOption: SearchOption.AllDirectories);
3. Inside the foreach statement, check that the file extensions are supported. The Image Classification API
supports JPEG and PNG formats.
continue;
4. Then, get the label for the file. If the useFolderNameAsLabel parameter is set to true , then the parent
directory where the file is saved is used as the label. Otherwise, it expects the label to be a prefix of the
file name or the file name itself.
if (useFolderNameAsLabel)
label = Directory.GetParent(file).Name;
else
{
for (int index = 0; index < label.Length; index++)
{
if (!char.IsLetter(label[index]))
{
label = label.Substring(0, index);
break;
}
}
}
2. Then, load the images into an IDataView using the LoadFromEnumerable method.
3. The data is loaded in the order it was read from the directories. To balance the data, shuffle it using the
ShuffleRows method.
4. Machine learning models expect input to be in numerical format. Therefore, some preprocessing needs to
be done on the data prior to training. Create an EstimatorChain made up of the MapValueToKey and
LoadRawImageBytes transforms. The MapValueToKey transform takes the categorical value in the Label
column, converts it to a numerical KeyType value and stores it in a new column called LabelAsKey . The
LoadImages takes the values from the ImagePath column along with the imageFolder parameter to load
images for training.
5. Use the Fitmethod to apply the data to the preprocessingPipeline EstimatorChain followed by the
Transform method, which returns an IDataView containing the pre-processed data.
6. To train a model, it's important to have a training dataset as well as a validation dataset. The model is
trained on the training set. How well it makes predictions on unseen data is measured by the
performance against the validation set. Based on the results of that performance, the model makes
adjustments to what it has learned in an effort to improve. The validation set can come from either
splitting your original dataset or from another source that has already been set aside for this purpose. In
this case, the pre-processed dataset is split into training, validation and test sets.
TrainTestData trainSplit = mlContext.Data.TrainTestSplit(data: preProcessedData, testFraction: 0.3);
TrainTestData validationTestSplit = mlContext.Data.TrainTestSplit(trainSplit.TestSet);
The code sample above performs two splits. First, the pre-processed data is split and 70% is used for
training while the remaining 30% is used for validation. Then, the 30% validation set is further split into
validation and test sets where 90% is used for validation and 10% is used for testing.
A way to think about the purpose of these data partitions is taking an exam. When studying for an exam,
you review your notes, books, or other resources to get a grasp on the concepts that are on the exam.
This is what the train set is for. Then, you might take a mock exam to validate your knowledge. This is
where the validation set comes in handy. You want to check whether you have a good grasp of the
concepts before taking the actual exam. Based on those results, you take note of what you got wrong or
didn't understand well and incorporate your changes as you review for the real exam. Finally, you take the
exam. This is what the test set is used for. You've never seen the questions that are on the exam and now
use what you learned from training and validation to apply your knowledge to the task at hand.
7. Assign the partitions their respective values for the train, validation and test data.
1. Create a new variable to store a set of required and optional parameters for an
ImageClassificationTrainer .
.Append(mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel"));
{
string imageName = Path.GetFileName(prediction.ImagePath);
Console.WriteLine($"Image: {imageName} | Actual Value: {prediction.Label} | Predicted Value:
{prediction.PredictedLabel}");
}
3. To access a single ModelInputinstance, convert the data IDataView into an IEnumerable using the
CreateEnumerable method and then get the first observation.
4. Use the Predict method to classify the image.
OutputPrediction(prediction);
}
6. Inside the Main method, call ClassifySingleImage using the test set of images.
2. Create an IDataView containing the predictions by using the Transform method. Add the following code
inside the ClassifyImages method.
3. In order to iterate over the predictions, convert the predictionData IDataView into an IEnumerable
using the CreateEnumerable method and then get the first 10 observations.
4. Iterate and output the original and predicted labels for the predictions.
5. Finally, inside the Main method, call ClassifyImages using the test set of images.
Training phase
Phase: Training, Dataset used: Validation, Batch Processed Count: 6, Epoch: 21, Accuracy: 0.6797619
Phase: Training, Dataset used: Validation, Batch Processed Count: 6, Epoch: 22, Accuracy: 0.7642857
Phase: Training, Dataset used: Validation, Batch Processed Count: 6, Epoch: 23, Accuracy: 0.7916667
Upon inspection of the 7001-220.jpg image, you can see that it in fact is not cracked.
Congratulations! You've now successfully built a deep learning model for classifying images.
Improve the model
If you're not satisfied with the results of your model, you can try to improve its performance by trying some of
the following approaches:
More Data : The more examples a model learns from, the better it performs. Download the full SDNET2018
dataset and use it to train.
Augment the data : A common technique to add variety to the data is to augment the data by taking an
image and applying different transforms (rotate, flip, shift, crop). This adds more varied examples for the
model to learn from.
Train for a longer time : The longer you train, the more tuned the model will be. Increasing the number of
epochs may improve the performance of your model.
Experiment with the hyper-parameters : In addition to the parameters used in this tutorial, other
parameters can be tuned to potentially improve performance. Changing the learning rate, which determines
the magnitude of updates made to the model after each epoch may improve performance.
Use a different model architecture : Depending on what your data looks like, the model that can best
learn its features may differ. If you're not satisfied with the performance of your model, try changing the
architecture.
Additional Resources
Deep Learning vs Machine Learning.
Next steps
In this tutorial, you learned how to build a custom deep learning model using transfer learning, a pretrained
image classification TensorFlow model and the ML.NET Image Classification API to classify images of concrete
surfaces as cracked or uncracked.
Advance to the next tutorial to learn more.
Object Detection
Tutorial: Generate an ML.NET image classification
model from a pre-trained TensorFlow model
11/2/2020 • 13 minutes to read • Edit Online
Learn how to transfer the knowledge from an existing TensorFlow model into a new ML.NET image classification
model.
The TensorFlow model was trained to classify images into a thousand categories. The ML.NET model makes use
of part of the TensorFlow model in its pipeline to train a model to classify images into 3 categories.
Training an Image Classification model from scratch requires setting millions of parameters, a ton of labeled
training data and a vast amount of compute resources (hundreds of GPU hours). While not as effective as
training a custom model from scratch, transfer learning allows you to shortcut this process by working with
thousands of images vs. millions of labeled images and build a customized model fairly quickly (within an hour
on a machine without a GPU). This tutorial scales that process down even further, using only a dozen training
images.
In this tutorial, you learn how to:
Understand the problem
Incorporate the pre-trained TensorFlow model into the ML.NET pipeline
Train and evaluate the ML.NET model
Classify a test image
You can find the source code for this tutorial at the dotnet/samples repository. Note that by default, the .NET
project configuration for this tutorial targets .NET core 2.2.
Prerequisites
Visual Studio 2019 or later or Visual Studio 2017 version 15.6 or later with the ".NET Core cross-platform
development" workload installed.
The tutorial assets directory .ZIP file
The InceptionV1 machine learning model
NOTE
The preceding images belong to Wikimedia Commons and are attributed as follows:
"220px-Pepperoni_pizza.jpg" Public Domain, https://commons.wikimedia.org/w/index.php?curid=79505,
"119px-Nalle_-_a_small_brown_teddy_bear.jpg" By Jonik - Self-photographed, CC BY-SA 2.0,
https://commons.wikimedia.org/w/index.php?curid=48166.
"193px-Broodrooster.jpg" By M.Minderhoud - Own work, CC BY-SA 3.0, https://commons.wikimedia.org/w/index.php?
curid=27403
The Inception model is trained to classify images into a thousand categories, but for this tutorial, you need to
classify images in a smaller category set, and only those categories. Enter the transfer part of
transfer learning . You can transfer the Inception model 's ability to recognize and classify images to the new
limited categories of your custom image classifier.
Food
Toy
Appliance
This tutorial uses the TensorFlow Inception model deep learning model, a popular image recognition model
trained on the ImageNet dataset. The TensorFlow model classifies entire images into a thousand classes, such as
“Umbrella”, “Jersey”, and “Dishwasher”.
Because the Inception model has already been pre trained on thousands of different images, internally it
contains the image features needed for image identification. We can make use of these internal image features
in the model to train a new model with far fewer classes.
As shown in the following diagram, you add a reference to the ML.NET NuGet packages in your .NET Core or
.NET Framework applications. Under the covers, ML.NET includes and references the native TensorFlow library
that allows you to write code that loads an existing trained TensorFlow model file.
Multiclass classification
After using the TensorFlow inception model to extract features suitable as input for a classical machine learning
algorithm, we add an ML.NET multi-class classifier.
The specific trainer used in this case is the multinomial logistic regression algorithm.
The algorithm implemented by this trainer performs well on problems with a large number of features, which is
the case for a deep learning model operating on image data.
Data
There are two data sources: the .tsv file, and the image files. The tags.tsv file contains two columns: the first
one is defined as ImagePath and the second one is the Label corresponding to the image. The following
example file doesn't have a header row, and looks like this:
broccoli.jpg food
pizza.jpg food
pizza2.jpg food
teddy2.jpg toy
teddy3.jpg toy
teddy4.jpg toy
toaster.jpg appliance
toaster2.png appliance
The training and testing images are located in the assets folders that you'll download in a zip file. These images
belong to Wikimedia Commons.
Wikimedia Commons, the free media repository. Retrieved 10:48, October 17, 2018 from:
https://commons.wikimedia.org/wiki/Pizza https://commons.wikimedia.org/wiki/Toaster
https://commons.wikimedia.org/wiki/Teddy_bear
Setup
Create a project
1. Create a .NET Core Console Application called "TransferLearningTF".
2. Install the Microsoft.ML NuGet Package :
NOTE
This sample uses the latest stable version of the NuGet packages mentioned unless otherwise stated.
In Solution Explorer, right-click on your project and select Manage NuGet Packages .
Choose "nuget.org" as the Package source, select the Browse tab, search for Microsoft.ML .
Select the Install button.
Select the OK button on the Preview Changes dialog.
Select the I Accept button on the License Acceptance dialog if you agree with the license terms for
the packages listed.
Repeat these steps for Microsoft.ML.ImageAnalytics , SciSharp.TensorFlow.Redist and
Microsoft.ML.TensorFlow .
Download assets
1. Download The project assets directory zip file, and unzip.
2. Copy the assets directory into your TransferLearningTF project directory. This directory and its
subdirectories contain the data and support files (except for the Inception model, which you'll download
and add in the next step) needed for this tutorial.
3. Download the Inception model, and unzip.
4. Copy the contents of the inception5h directory just unzipped into your TransferLearningTF project
assets/inception directory. This directory contains the model and additional support files needed for
this tutorial, as shown in the following image:
5. In Solution Explorer, right-click each of the files in the asset directory and subdirectories and select
Proper ties . Under Advanced , change the value of Copy to Output Director y to Copy if newer .
Create classes and define paths
1. Add the following additional using statements to the top of the Program.cs file:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.ML;
using Microsoft.ML.Data;
2. Add the following code to the line right above the Main method to specify the asset paths:
static readonly string _assetsPath = Path.Combine(Environment.CurrentDirectory, "assets");
static readonly string _imagesFolder = Path.Combine(_assetsPath, "images");
static readonly string _trainTagsTsv = Path.Combine(_imagesFolder, "tags.tsv");
static readonly string _testTagsTsv = Path.Combine(_imagesFolder, "test-tags.tsv");
static readonly string _predictSingleImage = Path.Combine(_imagesFolder, "toaster3.jpg");
static readonly string _inceptionTensorFlowModel = Path.Combine(_assetsPath, "inception",
"tensorflow_inception_graph.pb");
[LoadColumn(1)]
public string Label;
}
ImageData is the input image data class and has the following String fields:
ImagePath contains the image file name.
Label contains a value for the image label.
4. Add a new class to your project for ImagePrediction :
ImagePrediction is the image prediction class and has the following fields:
Score contains the confidence percentage for a given image classification.
PredictedLabelValue contains a value for the predicted image classification label.
ImagePrediction is the class used for prediction after the model has been trained. It has a string (
ImagePath ) for the image path. The Label is used to reuse and train the model. The PredictedLabelValue
is used during prediction and evaluation. For evaluation, an input with training data, the predicted values,
and the model are used.
Initialize variables in Main
1. Initialize the mlContext variable with a new instance of MLContext . Replace the
Console.WriteLine("Hello World!") line with the following code in the Main method:
The MLContext class is a starting point for all ML.NET operations, and initializing mlContext creates a
new ML.NET environment that can be shared across the model creation workflow objects. It's similar,
conceptually, to DBContext in Entity Framework.
Create a struct for Inception model parameters
1. The Inception model has several parameters you need to pass in. Create a struct to map the parameter
values to friendly names with the following code, just after the Main() method:
private struct InceptionSettings
{
public const int ImageHeight = 224;
public const int ImageWidth = 224;
public const float Mean = 117;
public const float Scale = 1;
public const bool ChannelsLast = true;
}
return File.ReadAllLines(file)
.Select(line => line.Split('\t'))
.Select(line => new ImageData()
{
ImagePath = Path.Combine(folder, line[0])
});
The code parses through the tags.tsv file to add the file path to the image file name for the ImagePath
property and load it and the Label into an ImageData object.
Create a method to make a prediction
1. Create the ClassifySingleImage() method, just before the DisplayResults() method, using the following
code:
public static void ClassifySingleImage(MLContext mlContext, ITransformer model)
{
2. Create an ImageDataobject that contains the fully qualified path and image file name for the single
ImagePath . Add the following code as the next lines in the ClassifySingleImage() method:
3. Make a single prediction, by adding the following code as the next line in the ClassifySingleImage
method:
To get the prediction, use the Predict() method. The PredictionEngine is a convenience API, which allows
you to perform a prediction on a single instance of data. PredictionEngine is not thread-safe. It's
acceptable to use in single-threaded or prototype environments. For improved performance and thread
safety in production environments, use the PredictionEnginePool service, which creates an ObjectPool
of PredictionEngine objects for use throughout your application. See this guide on how to use
PredictionEnginePool in an ASP.NET Core Web API.
NOTE
PredictionEnginePool service extension is currently in preview.
4. Display the prediction result as the next line of code in the ClassifySingleImage() method:
2. Add the estimators to load, resize and extract the pixels from the image data:
The image data needs to be processed into the format that the TensorFlow model expects. In this case, the
images are loaded into memory, resized to a consistent size, and the pixels are extracted into a numeric
vector.
3. Add the estimator to load the TensorFlow model, and score it:
.Append(mlContext.Model.LoadTensorFlowModel(_inceptionTensorFlowModel).
ScoreTensorFlowModel(outputColumnNames: new[] { "softmax2_pre_activation" }, inputColumnNames:
new[] { "input" }, addBatchDimensionInput: true))
This stage in the pipeline loads the TensorFlow model into memory, then processes the vector of pixel
values through the TensorFlow model network. Applying inputs to a deep learning model, and generating
an output using the model, is referred to as Scoring . When using the model in its entirety, scoring makes
an inference, or prediction.
In this case, you use all of the TensorFlow model except the last layer, which is the layer that makes the
inference. The output of the penultimate layer is labeled softmax_2_preactivation . The output of this layer
is effectively a vector of features that characterize the original input images.
This feature vector generated by the TensorFlow model will be used as input to an ML.NET training
algorithm.
4. Add the estimator to map the string labels in the training data to integer key values:
The ML.NET trainer that is appended next requires its labels to be in key format rather than arbitrary
strings. A key is a number that has a one to one mapping to a string value.
5. Add the ML.NET training algorithm:
.Append(mlContext.MulticlassClassification.Trainers.LbfgsMaximumEntropy(labelColumnName: "LabelKey",
featureColumnName: "softmax2_pre_activation"))
6. Add the estimator to map the predicted key value back into a string:
.Append(mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabelValue", "PredictedLabel"))
.AppendCacheCheckpoint(mlContext);
Train the model
1. Load the training data using the LoadFromTextFile wrapper. Add the following code as the next line in the
GenerateModel() method:
Data in ML.NET is represented as an IDataView class. IDataView is a flexible, efficient way of describing
tabular data (numeric and text). Data can be loaded from a text file or in real time (for example, SQL
database or log files) to an IDataView object.
2. Train the model with the data loaded above:
The Fit() method trains your model by applying the training dataset to the pipeline.
There are a few sample images that you can use to evaluate the model. Like the training data, these need
to be loaded into an IDataView , so that they can be transformed by the model.
2. Add the following code to the GenerateModel() method to evaluate the model:
MulticlassClassificationMetrics metrics =
mlContext.MulticlassClassification.Evaluate(predictions,
labelColumnName: "LabelKey",
predictedLabelColumnName: "PredictedLabel");
return model;
2. Add the call to the ClassifySingleImage() method as the next line of code in the Main method:
ClassifySingleImage(mlContext, model);
3. Run your console app (Ctrl + F5). Your results should be similar to the following output. You may see
warnings or processing messages, but these messages have been removed from the following results for
clarity.
Congratulations! You've now successfully built a machine learning model for image classification by applying
transfer learning to a TensorFlow model in ML.NET.
You can find the source code for this tutorial at the dotnet/samples repository.
In this tutorial, you learned how to:
Understand the problem
Incorporate the pre-trained TensorFlow model into the ML.NET pipeline
Train and evaluate the ML.NET model
Classify a test image
Check out the Machine Learning samples GitHub repository to explore an expanded image classification sample.
dotnet/machinelearning-samples GitHub repository
Tutorial: Forecast bike rental service demand with
time series analysis and ML.NET
11/2/2020 • 9 minutes to read • Edit Online
Learn how to forecast demand for a bike rental service using univariate time series analysis on data stored in a
SQL Server database with ML.NET.
In this tutorial, you learn how to:
Understand the problem
Load data from a database
Create a forecasting model
Evaluate forecasting model
Save a forecasting model
Use a forecasting model
Prerequisites
Visual Studio 2019 or later or Visual Studio 2017 version 15.6 or later with the ".NET Core cross-platform
development" workload installed.
a. In Solution Explorer, right-click on your project and select Manage NuGet Packages .
b. Choose "nuget.org" as the Package source, select the Browse tab, search for Microsoft.ML .
c. Check the Include prerelease checkbox.
d. Select the Install button.
e. Select the OK button on the Preview Changes dialog and then select the I Accept button on the
License Acceptance dialog if you agree with the license terms for the packages listed.
f. Repeat these steps for System.Data.SqlClient and Microsoft.ML.TimeSeries .
Prepare and understand the data
1. Create a directory called Data.
2. Download the DailyDemand.mdf database file and save it to the Data directory.
NOTE
The data used in this tutorial comes from the UCI Bike Sharing Dataset. Fanaee-T, Hadi, and Gama, Joao, 'Event labeling
combining ensemble detectors and background knowledge', Progress in Artificial Intelligence (2013): pp. 1-15, Springer
Berlin Heidelberg, Web Link.
The original dataset contains several columns corresponding to seasonality and weather. For brevity and
because the algorithm used in this tutorial only requires the values from a single numerical column, the original
dataset has been condensed to include only the following columns:
dteday : The date of the observation.
year : The encoded year of the observation (0=2011, 1=2012).
cnt : The total number of bike rentals for that day.
The original dataset is mapped to a database table with the following schema in a SQL Server database.
1/1/2011 0 985
1/2/2011 0 801
1/3/2011 0 1349
2. Create ModelInput class. Below the Program class, add the following code.
2. Initialize the mlContext variable with a new instance of MLContext by adding the following line to the
Main method.
MLContext mlContext = new MLContext();
The MLContext class is a starting point for all ML.NET operations, and initializing mlContext creates a new
ML.NET environment that can be shared across the model creation workflow objects. It's similar,
conceptually, to DBContext in Entity Framework.
ML.NET algorithms expect data to be of type Single . Therefore, numerical values coming from the
database that are not of type Real , a single-precision floating-point value, have to be converted to Real
.
The Year and TotalRental columns are both integer types in the database. Using the CAST built-in
function, they are both cast to Real .
3. Create a DatabaseSource to connect to the database and execute the query.
5. The dataset contains two years worth of data. Only data from the first year is used for training, the
second year is held out to compare the actual values against the forecast produced by the model. Filter
the data using the FilterRowsByColumn transform.
For the first year, only the values in the Year column less than 1 are selected by setting the upperBound
parameter to 1. Conversely, for the second year, values greater than or equal to 1 are selected by setting
the lowerBound parameter to 1.
The forecastingPipeline takes 365 data points for the first year and samples or splits the time-series
dataset into 30-day (monthly) intervals as specified by the seriesLength parameter. Each of these
samples is analyzed through weekly or a 7-day window. When determining what the forecasted value for
the next period(s) is, the values from previous seven days are used to make a prediction. The model is set
to forecast seven periods into the future as defined by the horizon parameter. Because a forecast is an
informed guess, it's not always 100% accurate. Therefore, it's good to know the range of values in the
best and worst-case scenarios as defined by the upper and lower bounds. In this case, the level of
confidence for the lower and upper bounds is set to 95%. The confidence level can be increased or
decreased accordingly. The higher the value, the wider the range is between the upper and lower bounds
to achieve the desired level of confidence.
2. Use the Fit method to train the model and fit the data to the previously defined forecastingPipeline .
2. Inside the Evaluate method, forecast the second year's data by using the Transform method with the
trained model.
3. Get the actual values from the data by using the CreateEnumerable method.
IEnumerable<float> actual =
mlContext.Data.CreateEnumerable<ModelInput>(testData, true)
.Select(observed => observed.TotalRentals);
5. Calculate the difference between the actual and forecast values, commonly referred to as the error.
6. Measure performance by computing the Mean Absolute Error and Root Mean Squared Error values.
Console.WriteLine("Evaluation Metrics");
Console.WriteLine("---------------------");
Console.WriteLine($"Mean Absolute Error: {MAE:F3}");
Console.WriteLine($"Root Mean Squared Error: {RMSE:F3}\n");
2. Save the model to a file called MLModel.zip as specified by the previously defined modelPath variable.
Use the Checkpoint method to save the model.
forecastEngine.CheckPoint(mlContext, modelPath);
2. Inside the Forecast method, use the Predict method to forecast rentals for the next seven days.
IEnumerable<string> forecastOutput =
mlContext.Data.CreateEnumerable<ModelInput>(testData, reuseRowObject: false)
.Take(horizon)
.Select((ModelInput rental, int index) =>
{
string rentalDate = rental.RentalDate.ToShortDateString();
float actualRentals = rental.TotalRentals;
float lowerEstimate = Math.Max(0, forecast.LowerBoundRentals[index]);
float estimate = forecast.ForecastedRentals[index];
float upperEstimate = forecast.UpperBoundRentals[index];
return $"Date: {rentalDate}\n" +
$"Actual Rentals: {actualRentals}\n" +
$"Lower Estimate: {lowerEstimate}\n" +
$"Forecast: {estimate}\n" +
$"Upper Estimate: {upperEstimate}\n";
});
Console.WriteLine("Rental Forecast");
Console.WriteLine("---------------------");
foreach (var prediction in forecastOutput)
{
Console.WriteLine(prediction);
}
2. Run the application. Output similar to that below should appear on the console. For brevity, the output
has been condensed.
Evaluation Metrics
---------------------
Mean Absolute Error: 726.416
Root Mean Squared Error: 987.658
Rental Forecast
---------------------
Date: 1/1/2012
Actual Rentals: 2294
Lower Estimate: 1197.842
Forecast: 2334.443
Upper Estimate: 3471.044
Date: 1/2/2012
Actual Rentals: 1951
Lower Estimate: 1148.412
Forecast: 2360.861
Upper Estimate: 3573.309
Inspection of the actual and forecasted values shows the following relationships:
While the forecasted values are not predicting the exact number of rentals, they provide a more narrow range of
values that allows an operation to optimize their use of resources.
Congratulations! You've now successfully built a time series machine learning model to forecast bike rental
demand.
You can find the source code for this tutorial at the dotnet/machinelearning-samples repository.
Next steps
Machine learning tasks in ML.NET
Improve model accuracy
Tutorial: Detect anomalies in time series with
ML.NET
1/25/2021 • 7 minutes to read • Edit Online
Learn how to build an anomaly detection application for time series data. This tutorial creates a .NET Core
console application using C# in Visual Studio 2019.
In this tutorial, you learn how to:
Load the data
Detect period for a time series
Detect anomaly for a periodical time series
You can find the source code for this tutorial at the dotnet/samples repository.
Prerequisites
Visual Studio 2019 version 16.7.8 or later with the ".NET Core cross-platform development" workload
installed.
The phone-calls.csv dataset.
NOTE
This sample uses the latest stable version of the NuGet packages mentioned unless otherwise stated.
In Solution Explorer, right-click on your project and select Manage NuGet Packages . Choose
"nuget.org" as the Package source, select the Browse tab, search for Microsoft.ML and select the Install
button. Select the OK button on the Preview Changes dialog and then select the I Accept button on the
License Acceptance dialog if you agree with the license terms for the packages listed. Repeat these
steps for Microsoft.ML.TimeSeries .
4. Add the following using statements at the top of your Program.cs file:
using System;
using System.IO;
using Microsoft.ML;
using System.Collections.Generic;
using Microsoft.ML.TimeSeries;
T IM ESTA M P VA L UE
2018/9/3 36.69670857
2018/9/4 35.74160571
..... .....
2018/10/3 34.49893429
... ....
This file represents a time-series. Each row in the file is a data point. Each data point has two attributes, namely,
timestamp and value , to represent the number of phone calls at each day. The number of phone calls is
transformed to de-sensitivity.
Create classes and define paths
Next, define your input and prediction class data structures.
Add a new class to your project:
1. In Solution Explorer , right-click the project, and then select Add > New Item .
2. In the Add New Item dialog box , select Class and change the Name field to PhoneCallsData.cs. Then,
select the Add button.
The PhoneCallsData.cs file opens in the code editor.
3. Add the following using statement to the top of PhoneCallsData.cs:
using Microsoft.ML.Data;
4. Remove the existing class definition and add the following code, which has two classes PhoneCallsData
and PhoneCallsPrediction , to the PhoneCallsData.cs file:
public class PhoneCallsData
{
[LoadColumn(0)]
public string timestamp;
[LoadColumn(1)]
public double value;
}
PhoneCallsData specifies an input data class. The LoadColumn attribute specifies which columns (by
column index) in the dataset should be loaded. It has two attributes timestamp and value that
correspond to the same attributes in the data file.
PhoneCallsPrediction specifies the prediction data class. For SR-CNN detector, the prediction depends on
the detect mode specified. In this sample, we select the AnomalyAndMargin mode. The output contains
seven columns. In most cases, IsAnomaly , ExpectedValue , UpperBoundary , and LowerBoundary are
informative enough. They tell you if a point is an anomaly, the expected value of the point and the lower /
upper boundary region of the point.
5. Add the following code to the line right above the Main method to specify the path to your data file:
The MLContext class is a starting point for all ML.NET operations, and initializing mlContext creates a
new ML.NET environment that can be shared across the model creation workflow objects. It's similar,
conceptually, to DBContext in Entity Framework.
Load the data
Data in ML.NET is represented as an IDataView class. IDataView is a flexible, efficient way of describing tabular
data (numeric and text). Data can be loaded from a text file or from other sources (for example, SQL database or
log files) to an IDataView object.
1. Add the following code as the next line of the Main method:
The LoadFromTextFile() defines the data schema and reads in the file. It takes in the data path variables
and returns an IDataView .
Time series anomaly detection
Time series anomaly detection is the process of detecting time-series data outliers; points on a given input time-
series where the behavior isn't what was expected, or "weird". These anomalies are typically indicative of some
events of interest in the problem domain: a cyber-attack on user accounts, power outage, bursting RPS on a
server, memory leak, etc.
To find anomaly on time series, you should first determine the period of the series. Then, the time series can be
decomposed into several components as Y = T + S + R , where Y is the original series, T is the trend
component, S is the seasonal component, and R is the residual component of the series. This step is called
decomposition. Finally, detection is performed on the residual component to find the anomalies. In ML.NET, The
SR-CNN algorithm is an advanced and novel algorithm that is based on Spectral Residual (SR) and
Convolutional Neural Network(CNN) to detect anomaly on time-series. For more information on this algorithm,
see Time-Series Anomaly Detection Service at Microsoft.
In this tutorial, you will see that these procedures can be completed using two functions.
Detect Period
In the first step, we invoke the DetectSeasonality function to determine the period of the series.
Create the DetectPeriod method
1. Create the DetectPeriod method, just below the Main method, using the following code:
2. Use the DetectSeasonality function to detect period. Add it to the DetectPeriod method with the
following code:
3. Display the period value by adding the following as the next line of code in the DetectPeriod method:
4. Add the following call to the DetectPeriod method in the Main method:
Detect Anomaly
In this step, you use the DetectEntireAnomalyBySrCnn method to find anomalies.
Create the DetectAnomaly method
1. Create the DetectAnomaly method, just below the DetectPeriod method, using the following code:
3. Detect anomaly by SR-CNN algorithm by adding the following line of code in the DetectAnomaly method:
4. Convert the output data view into a strongly typed IEnumerable for easier display using the
CreateEnumerable method with the following code:
5. Create a display header with the following code as the next line in the DetectAnomaly method:
Console.WriteLine("Index\tData\tAnomaly\tAnomalyScore\tMag\tExpectedValue\tBoundaryUnit\tUpperBoundar
y\tLowerBoundary");
You'll display the following information in your change point detection results:
Index is the index of each point.
Anomaly is the indicator of whether each point is detected as anomaly.
ExpectedValue is the estimated value of each point.
LowerBoundary is the lowest value each point can be to be not anomaly.
UpperBoundary is the highest value each point can be to be not anomaly.
6. Iterate through the predictions IEnumerable and display the results with the following code:
var index = 0;
Console.WriteLine("");
7. Add the following call to the DetectAnomaly method in the Main method:
Congratulations! You've now successfully built machine learning models for detecting period and anomaly on a
periodical series.
You can find the source code for this tutorial at the dotnet/samples repository.
In this tutorial, you learned how to:
Load the data
Detect period on the time series data
Detect anomaly on the time series data
Next steps
Check out the Machine Learning samples GitHub repository to explore a Power Consumption Anomaly
Detection sample.
dotnet/machinelearning-samples GitHub repository
Tutorial: Detect anomalies in product sales with
ML.NET
1/25/2021 • 11 minutes to read • Edit Online
Learn how to build an anomaly detection application for product sales data. This tutorial creates a .NET Core
console application using C# in Visual Studio.
In this tutorial, you learn how to:
Load the data
Create a transform for spike anomaly detection
Detect spike anomalies with the transform
Create a transform for change point anomaly detection
Detect change point anomalies with the transform
You can find the source code for this tutorial at the dotnet/samples repository.
Prerequisites
Visual Studio 2017 version 15.6 or later with the ".NET Core cross-platform development" workload
installed.
The product-sales.csv dataset
NOTE
The data format in product-sales.csv is based on the dataset “Shampoo Sales Over a Three Year Period” originally
sourced from DataMarket and provided by Time Series Data Library (TSDL), created by Rob Hyndman. “Shampoo Sales
Over a Three Year Period” Dataset Licensed Under the DataMarket Default Open License.
NOTE
This sample uses the latest stable version of the NuGet packages mentioned unless otherwise stated.
In Solution Explorer, right-click on your project and select Manage NuGet Packages . Choose
"nuget.org" as the Package source, select the Browse tab, search for Microsoft.ML and select the Install
button. Select the OK button on the Preview Changes dialog and then select the I Accept button on the
License Acceptance dialog if you agree with the license terms for the packages listed. Repeat these
steps for Microsoft.ML.TimeSeries .
4. Add the following using statements at the top of your Program.cs file:
using System;
using System.IO;
using Microsoft.ML;
using System.Collections.Generic;
MONT H P RO DUC T SA L ES
1-Jan 271
2-Jan 150.9
..... .....
1-Feb 199.3
..... .....
using Microsoft.ML.Data;
4. Remove the existing class definition and add the following code, which has two classes ProductSalesData
and ProductSalesPrediction , to the ProductSalesData.cs file:
public class ProductSalesData
{
[LoadColumn(0)]
public string Month;
[LoadColumn(1)]
public float numSales;
}
ProductSalesData specifies an input data class. The LoadColumn attribute specifies which columns (by
column index) in the dataset should be loaded.
ProductSalesPrediction specifies the prediction data class. For anomaly detection, the prediction consists
of an alert to indicate whether there is an anomaly, a raw score, and p-value. The closer the p-value is to
0, the more likely an anomaly has occurred.
5. Create two global fields to hold the recently downloaded dataset file path and the saved model file path:
_dataPath has the path to the dataset used to train the model.
_docsize has the number of records in dataset file. You'll use _docSize to calculate
pvalueHistoryLength .
6. Add the following code to the line right above the Main method to specify those paths:
The MLContext class is a starting point for all ML.NET operations, and initializing mlContext creates a
new ML.NET environment that can be shared across the model creation workflow objects. It's similar,
conceptually, to DBContext in Entity Framework.
Load the data
Data in ML.NET is represented as an IDataView class. IDataView is a flexible, efficient way of describing tabular
data (numeric and text). Data can be loaded from a text file or from other sources (for example, SQL database or
log files) to an IDataView object.
1. Add the following code as the next line of the Main() method:
Anomaly detection is the process of detecting time-series data outliers; points on a given input time-series
where the behavior isn't what was expected, or "weird".
Anomaly detection can be useful in lots of ways. For instance:
If you have a car, you might want to know: Is this oil gauge reading normal, or do I have a leak? If you're
monitoring power consumption, you’d want to know: Is there an outage?
There are two types of time series anomalies that can be detected:
Spikes indicate temporary bursts of anomalous behavior in the system.
Change points indicate the beginning of persistent changes over time in the system.
In ML.NET, The IID Spike Detection or IID Change point Detection algorithms are suited for independent and
identically distributed datasets.
Unlike the models in the other tutorials, the time series anomaly detector transforms operate directly on input
data. The IEstimator.Fit() method does not need training data to produce the transform. It does need the data
schema though, which is provided by a data view generated from an empty list of ProductSalesData .
You'll analyze the same product sales data to detect spikes and change points. The building and training model
process is the same for spike detection and change point detection; the main difference is the specific detection
algorithm used.
Spike detection
The goal of spike detection is to identify sudden yet temporary bursts that significantly differ from the majority
of the time series data values. It's important to detect these suspicious rare items, events, or observations in a
timely manner to be minimized. The following approach can be used to detect a variety of anomalies such as:
outages, cyber-attacks, or viral web content. The following image is an example of spikes in a time series dataset:
Add the CreateEmptyDataView() method
Add the following method to Program.cs :
The CreateEmptyDataView() produces an empty data view object with the correct schema to be used as input to
the IEstimator.Fit() method.
Create the DetectSpike () method
The DetectSpike() method:
Creates the transform from the estimator.
Detects spikes based on historical sales data.
Displays the results.
1. Create the DetectSpike() method, just after the Main() method, using the following code:
2. Use the IidSpikeEstimator to train the model for spike detection. Add it to the DetectSpike() method with
the following code:
3. Create the spike detection transform by adding the following as the next line of code in the
DetectSpike() method:
4. Add the following line of code to transform the productSales data as the next line in the DetectSpike()
method:
IDataView transformedData = iidSpikeTransform.Transform(productSales);
The previous code uses the Transform() method to make predictions for multiple input rows of a dataset.
5. Convert your transformedData into a strongly typed IEnumerable for easier display using the
CreateEnumerable() method with the following code:
Console.WriteLine("Alert\tScore\tP-Value");
if (p.Prediction[0] == 1)
{
results += " <-- Spike detected";
}
Console.WriteLine(results);
}
Console.WriteLine("");
2. Create the iidChangePointEstimator in the DetectChangepoint() method with the following code:
3. As you did previously, create the transform from the estimator by adding the following line of code in the
DetectChangePoint() method:
4. Use the Transform() method to transform the data by adding the following code to DetectChangePoint()
:
5. As you did previously, convert your transformedData into a strongly typed IEnumerable for easier display
using the CreateEnumerable() method with the following code:
6. Create a display header with the following code as the next line in the DetectChangePoint() method:
Console.WriteLine("Alert\tScore\tP-Value\tMartingale value");
You'll display the following information in your change point detection results:
Alert indicates a change point alert for a given data point.
Score is the ProductSales value for a given data point in the dataset.
P-Value The "P" stands for probability. The closer the P-value is to 0, the more likely the data point is
an anomaly.
Martingale value is used to identify how "weird" a data point is, based on the sequence of P-values.
7. Iterate through the predictions IEnumerable and display the results with the following code:
foreach (var p in predictions)
{
var results = $"
{p.Prediction[0]}\t{p.Prediction[1]:f2}\t{p.Prediction[2]:F2}\t{p.Prediction[3]:F2}";
if (p.Prediction[0] == 1)
{
results += " <-- alert is on, predicted changepoint";
}
Console.WriteLine(results);
}
Console.WriteLine("");
8. Add the following call to the DetectChangepoint() method in the Main() method:
Congratulations! You've now successfully built machine learning models for detecting spikes and change point
anomalies in sales data.
You can find the source code for this tutorial at the dotnet/samples repository.
In this tutorial, you learned how to:
Load the data
Train the model for spike anomaly detection
Detect spike anomalies with the trained model
Train the model for change point anomaly detection
Detect change point anomalies with the trained mode
Next steps
Check out the Machine Learning samples GitHub repository to explore a seasonality data anomaly detection
sample.
dotnet/machinelearning-samples GitHub repository
Tutorial: Detect objects using ONNX in ML.NET
11/2/2020 • 30 minutes to read • Edit Online
Learn how to use a pre-trained ONNX model in ML.NET to detect objects in images.
Training an object detection model from scratch requires setting millions of parameters, a large amount of
labeled training data and a vast amount of compute resources (hundreds of GPU hours). Using a pre-trained
model allows you to shortcut the training process.
In this tutorial, you learn how to:
Understand the problem
Learn what ONNX is and how it works with ML.NET
Understand the model
Reuse the pre-trained model
Detect objects with a loaded model
Pre-requisites
Visual Studio 2019 or later or Visual Studio 2017 version 15.6 or later with the ".NET Core cross-platform
development" workload installed.
Microsoft.ML NuGet Package
Microsoft.ML.ImageAnalytics NuGet Package
Microsoft.ML.OnnxTransformer NuGet Package
Tiny YOLOv2 pre-trained model
Netron (optional)
The YOLO model takes an image 3(RGB) x 416px x 416px . The model takes this input and passes it through the
different layers to produce an output. The output divides the input image into a 13 x 13 grid, with each cell in
the grid consisting of 125 values.
What is an ONNX model?
The Open Neural Network Exchange (ONNX) is an open source format for AI models. ONNX supports
interoperability between frameworks. This means you can train a model in one of the many popular machine
learning frameworks like PyTorch, convert it into ONNX format and consume the ONNX model in a different
framework like ML.NET. To learn more, visit the ONNX website.
The pre-trained Tiny YOLOv2 model is stored in ONNX format, a serialized representation of the layers and
learned patterns of those layers. In ML.NET, interoperability with ONNX is achieved with the ImageAnalytics and
OnnxTransformer NuGet packages. The ImageAnalytics package contains a series of transforms that take an
image and encode it into numerical values that can be used as input into a prediction or training pipeline. The
OnnxTransformer package leverages the ONNX Runtime to load an ONNX model and use it to make predictions
based on input provided.
NOTE
This sample uses the latest stable version of the NuGet packages mentioned unless otherwise stated.
In Solution Explorer, right-click on your project and select Manage NuGet Packages .
Choose "nuget.org" as the Package source, select the Browse tab, search for Microsoft.ML .
Select the Install button.
Select the OK button on the Preview Changes dialog and then select the I Accept button on the
License Acceptance dialog if you agree with the license terms for the packages listed.
Repeat these steps for Microsoft.ML.ImageAnalytics , Microsoft.ML.OnnxTransformer and
Microsoft.ML.OnnxRuntime .
Prepare your data and pre -trained model
1. Download The project assets directory zip file and unzip.
2. Copy the assets directory into your ObjectDetection project directory. This directory and its
subdirectories contain the image files (except for the Tiny YOLOv2 model, which you'll download and add
in the next step) needed for this tutorial.
3. Download the Tiny YOLOv2 model from the ONNX Model Zoo, and unzip.
Open the command prompt and enter the following command:
4. Copy the extracted model.onnx file from the directory just unzipped into your ObjectDetection project
assets\Model directory and rename it to TinyYolo2_model.onnx . This directory contains the model
needed for this tutorial.
5. In Solution Explorer, right-click each of the files in the asset directory and subdirectories and select
Proper ties . Under Advanced , change the value of Copy to Output Director y to Copy if newer .
Create classes and define paths
Open the Program.cs file and add the following additional using statements to the top of the file:
using System;
using System.IO;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using Microsoft.ML;
return fullPath;
}
2. Then, inside the Main method, create fields to store the location of your assets.
Add a new directory to your project to store your input data and prediction classes.
In Solution Explorer , right-click the project, and then select Add > New Folder . When the new folder appears
in the Solution Explorer, name it "DataStructures".
Create your input data class in the newly created DataStructures directory.
1. In Solution Explorer , right-click the DataStructures directory, and then select Add > New Item .
2. In the Add New Item dialog box, select Class and change the Name field to ImageNetData.cs. Then,
select the Add button.
The ImageNetData.cs file opens in the code editor. Add the following using statement to the top of
ImageNetData.cs:
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.ML.Data;
Remove the existing class definition and add the following code for the ImageNetData class to the
ImageNetData.cs file:
[LoadColumn(1)]
public string Label;
ImageNetData is the input image data class and has the following String fields:
ImagePath contains the path where the image is stored.
Label contains the name of the file.
Additionally, ImageNetData contains a method ReadFromFile that loads multiple image files stored in the
imageFolder path specified and returns them as a collection of ImageNetData objects.
using Microsoft.ML.Data;
Remove the existing class definition and add the following code for the ImageNetPrediction class to the
ImageNetPrediction.cs file:
ImageNetPrediction is the prediction data class and has the following float[] field:
PredictedLabel contains the dimensions, objectness score, and class probabilities for each of the
bounding boxes detected in an image.
Initialize variables in Main
The MLContext class is a starting point for all ML.NET operations, and initializing mlContext creates a new
ML.NET environment that can be shared across the model creation workflow objects. It's similar, conceptually, to
DBContext in Entity Framework.
Initialize the mlContext variable with a new instance of MLContext by adding the following line to the Main
method of Program.cs below the outputFolder field.
x the x position of the bounding box center relative to the grid cell it's associated with.
y the y position of the bounding box center relative to the grid cell it's associated with.
w the width of the bounding box.
h the height of the bounding box.
o the confidence value that an object exists within the bounding box, also known as objectness score.
p1-p20 class probabilities for each of the 20 classes predicted by the model.
In total, the 25 elements describing each of the 5 bounding boxes make up the 125 elements contained in each
grid cell.
The output generated by the pre-trained ONNX model is a float array of length 21125 , representing the
elements of a tensor with dimensions 125 x 13 x 13 . In order to transform the predictions generated by the
model into a tensor, some post-processing work is required. To do so, create a set of classes to help parse the
output.
Add a new directory to your project to organize the set of parser classes.
1. In Solution Explorer , right-click the project, and then select Add > New Folder . When the new folder
appears in the Solution Explorer, name it "YoloParser".
Create bounding boxes and dimensions
The data output by the model contains coordinates and dimensions of the bounding boxes of objects within the
image. Create a base class for dimensions.
1. In Solution Explorer , right-click the YoloParser directory, and then select Add > New Item .
2. In the Add New Item dialog box, select Class and change the Name field to DimensionsBase.cs. Then,
select the Add button.
The DimensionsBase.cs file opens in the code editor. Remove all using statements and existing class
definition.
Add the following code for the DimensionsBase class to the DimensionsBase.cs file:
using System.Drawing;
Just above the existing class definition, add a new class definition called BoundingBoxDimensions that
inherits from the DimensionsBase class to contain the dimensions of the respective bounding box.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
Inside the existing YoloOutputParser class definition, add a nested class that contains the dimensions of
each of the cells in the image. Add the following code for the CellDimensions class that inherits from the
DimensionsBase class at the top of the YoloOutputParser class definition.
3. Inside the YoloOutputParser class definition, add the following constants and fields.
public const int ROW_COUNT = 13;
public const int COL_COUNT = 13;
public const int CHANNEL_COUNT = 125;
public const int BOXES_PER_CELL = 5;
public const int BOX_INFO_FEATURE_COUNT = 5;
public const int CLASS_COUNT = 20;
public const float CELL_WIDTH = 32;
public const float CELL_HEIGHT = 32;
ROW_COUNT is the number of rows in the grid the image is divided into.
COL_COUNT is the number of columns in the grid the image is divided into.
CHANNEL_COUNT is the total number of values contained in one cell of the grid.
BOXES_PER_CELL is the number of bounding boxes in a cell,
BOX_INFO_FEATURE_COUNT is the number of features contained within a box (x,y,height,width,confidence).
CLASS_COUNT is the number of class predictions contained in each bounding box.
CELL_WIDTH is the width of one cell in the image grid.
CELL_HEIGHT is the height of one cell in the image grid.
channelStride is the starting position of the current cell in the grid.
When the model makes a prediction, also known as scoring, it divides the 416px x 416px input image
into a grid of cells the size of 13 x 13 . Each cell contains is 32px x 32px . Within each cell, there are 5
bounding boxes each containing 5 features (x, y, width, height, confidence). In addition, each bounding
box contains the probability of each of the classes, which in this case is 20. Therefore, each cell contains
125 pieces of information (5 features + 20 class probabilities).
Create a list of anchors below channelStride for all 5 bounding boxes:
Anchors are pre-defined height and width ratios of bounding boxes. Most object or classes detected by a model
have similar ratios. This is valuable when it comes to creating bounding boxes. Instead of predicting the
bounding boxes, the offset from the pre-defined dimensions is calculated therefore reducing the computation
required to predict the bounding box. Typically these anchor ratios are calculated based on the dataset used. In
this case, because the dataset is known and the values have been pre-computed, the anchors can be hard-coded.
Next, define the labels or classes that the model will predict. This model predicts 20 classes, which is a subset of
the total number of classes predicted by the original YOLOv2 model.
Add your list of labels below the anchors .
There are colors associated with each of the classes. Assign your class colors below your labels :
private static Color[] classColors = new Color[]
{
Color.Khaki,
Color.Fuchsia,
Color.Silver,
Color.RoyalBlue,
Color.Green,
Color.DarkOrange,
Color.Purple,
Color.Gold,
Color.Red,
Color.Aquamarine,
Color.Lime,
Color.AliceBlue,
Color.Sienna,
Color.Orchid,
Color.Tan,
Color.LightPink,
Color.Yellow,
Color.HotPink,
Color.OliveDrab,
Color.SandyBrown,
Color.DarkTurquoise
};
Add the code for all the helper methods below your list of classColors .
if (areaA <= 0)
return 0;
Once you have defined all of the helper methods, it's time to use them to process the model output.
Below the IntersectionOverUnion method, create the ParseOutputs method to process the output generated by
the model.
Create a list to store your bounding boxes and define variables inside the ParseOutputs method.
Each image is divided into a grid of 13 x 13 cells. Each cell contains five bounding boxes. Below the boxes
variable, add code to process all of the boxes in each of the cells.
}
}
}
Inside the inner-most loop, calculate the starting position of the current box within the one-dimensional model
output.
Directly below that, use the ExtractBoundingBoxDimensions method to get the dimensions of the current
bounding box.
Then, use the GetConfidence method to get the confidence for the current bounding box.
Before doing any further processing, check whether your confidence value is greater than the threshold
provided. If not, process the next bounding box.
Otherwise, continue processing the output. The next step is to get the probability distribution of the predicted
classes for the current bounding box using the ExtractClasses method.
Then, use the GetTopResult method to get the value and index of the class with the highest probability for the
current box and compute its score.
Use the topScore to once again keep only those bounding boxes that are above the specified threshold.
Finally, if the current bounding box exceeds the threshold, create a new BoundingBox object and add it to the
boxes list.
boxes.Add(new YoloBoundingBox()
{
Dimensions = new BoundingBoxDimensions
{
X = (mappedBoundingBox.X - mappedBoundingBox.Width / 2),
Y = (mappedBoundingBox.Y - mappedBoundingBox.Height / 2),
Width = mappedBoundingBox.Width,
Height = mappedBoundingBox.Height,
},
Confidence = topScore,
Label = labels[topResultIndex],
BoxColor = classColors[topResultIndex]
});
Once all cells in the image have been processed, return the boxes list. Add the following return statement
below the outer-most for-loop in the ParseOutputs method.
return boxes;
Inside the FilterBoundingBoxes method, start off by creating an array equal to the size of detected boxes and
marking all slots as active or ready for processing.
Then, sort the list containing your bounding boxes in descending order based on confidence.
Begin processing each bounding box by iterating over each of the bounding boxes.
Inside of this for-loop, check whether the current bounding box can be processed.
if (isActiveBoxes[i])
{
If so, add the bounding box to the list of results. If the results exceed the specified limit of boxes to be extracted,
break out of the loop. Add the following code inside the if-statement.
Otherwise, look at the adjacent bounding boxes. Add the following code below the box limit check.
for (var j = i + 1; j < boxes.Count; j++)
{
Like the first box, if the adjacent box is active or ready to be processed, use the IntersectionOverUnion method
to check whether the first box and the second box exceed the specified threshold. Add the following code to your
innermost for-loop.
if (isActiveBoxes[j])
{
var boxB = sortedBoxes[j].Box;
if (activeCount <= 0)
break;
}
}
Outside of the inner-most for-loop that checks adjacent bounding boxes, see whether there are any remaining
bounding boxes to be processed. If not, break out of the outer for-loop.
if (activeCount <= 0)
break;
Finally, outside of the initial for-loop of the FilterBoundingBoxes method, return the results:
return results;
Great! Now it's time to use this code along with the model for scoring.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.ML;
using Microsoft.ML.Data;
using ObjectDetection.DataStructures;
using ObjectDetection.YoloParser;
Inside the OnnxModelScorer class definition, add the following variables.
Directly below that, create a constructor for the OnnxModelScorer class that will initialize the previously
defined variables.
Once you have created the constructor, define a couple of structs that contain variables related to the
image and model settings. Create a struct called ImageNetSettings to contain the height and width
expected as input for the model.
After that, create another struct called TinyYoloModelSettings that contains the names of the input and
output layers of the model. To visualize the name of the input and output layers of the model, you can use
a tool like Netron.
Next, create the first set of methods use for scoring. Create the LoadModel method inside of your
OnnxModelScorer class.
Inside the LoadModel method, add the following code for logging.
Console.WriteLine("Read model");
Console.WriteLine($"Model location: {modelLocation}");
Console.WriteLine($"Default parameters: image size=({ImageNetSettings.imageWidth},
{ImageNetSettings.imageHeight})");
ML.NET pipelines need to know the data schema to operate on when the Fit method is called. In this
case, a process similar to training will be used. However, because no actual training is happening, it is
acceptable to use an empty IDataView . Create a new IDataView for the pipeline from an empty list.
Below that, define the pipeline. The pipeline will consist of four transforms.
LoadImages loads the image as a Bitmap.
ResizeImages rescales the image to the size specified (in this case, 416 x 416 ).
ExtractPixels changes the pixel representation of the image from a Bitmap to a numerical vector.
ApplyOnnxModel loads the ONNX model and uses it to score on the data provided.
Define your pipeline in the LoadModel method below the data variable.
Now it's time to instantiate the model for scoring. Call the Fit method on the pipeline and return it for
further processing.
return model;
Once the model is loaded, it can then be used to make predictions. To facilitate that process, create a method
called PredictDataUsingModel below the LoadModel method.
Extract the predicted probabilities and return them for additional processing.
return probabilities;
Now that both steps are set up, combine them into a single method. Below the PredictDataUsingModel method,
add a new method called Score .
Detect objects
Now that all of the setup is complete, it's time to detect some objects. Start off by adding references to the
scorer and parser in your Program.cs class.
using ObjectDetection.YoloParser;
using ObjectDetection.DataStructures;
try
{
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Inside of the try block, start implementing the object detection logic. First, load the data into an IDataView .
Then, create an instance of OnnxModelScorer and use it to score the loaded data.
Now it's time for the post-processing step. Create an instance of YoloOutputParser and use it to process the
model output.
var boundingBoxes =
probabilities
.Select(probability => parser.ParseOutputs(probability))
.Select(boxes => parser.FilterBoundingBoxes(boxes, 5, .5F));
Once the model output has been processed, it's time to draw the bounding boxes on the images.
Visualize predictions
After the model has scored the images and the outputs have been processed, the bounding boxes have to be
drawn on the image. To do so, add a method called DrawBoundingBox below the GetAbsolutePath method inside
of Program.cs.
First, load the image and get the height and width dimensions in the DrawBoundingBox method.
Then, create a for-each loop to iterate over each of the bounding boxes detected by the model.
Inside of the for-each loop, get the dimensions of the bounding box.
Because the dimensions of the bounding box correspond to the model input of 416 x 416 , scale the bounding
box dimensions to match the actual size of the image.
x = (uint)originalImageWidth * x / OnnxModelScorer.ImageNetSettings.imageWidth;
y = (uint)originalImageHeight * y / OnnxModelScorer.ImageNetSettings.imageHeight;
width = (uint)originalImageWidth * width / OnnxModelScorer.ImageNetSettings.imageWidth;
height = (uint)originalImageHeight * height / OnnxModelScorer.ImageNetSettings.imageHeight;
Then, define a template for text that will appear above each bounding box. The text will contain the class of the
object inside of the respective bounding box as well as the confidence.
string text = $"{box.Label} ({(box.Confidence * 100).ToString("0")}%)";
Inside the using code block, tune the graphic's Graphics object settings.
thumbnailGraphic.CompositingQuality = CompositingQuality.HighQuality;
thumbnailGraphic.SmoothingMode = SmoothingMode.HighQuality;
thumbnailGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
Below that, set the font and color options for the text and bounding box.
Create and fill a rectangle above the bounding box to contain the text using the FillRectangle method. This will
help contrast the text and improve readability.
Then, Draw the text and bounding box on the image using the DrawString and DrawRectangle methods.
Outside of the for-each loop, add code to save the images in the outputDirectory .
if (!Directory.Exists(outputImageLocation))
{
Directory.CreateDirectory(outputImageLocation);
}
image.Save(Path.Combine(outputImageLocation, imageName));
For additional feedback that the application is making predictions as expected at runtime, add a method called
LogDetectedObjects below the DrawBoundingBox method in the Program.cs file to output the detected objects to
the console.
private static void LogDetectedObjects(string imageName, IList<YoloBoundingBox> boundingBoxes)
{
Console.WriteLine($".....The objects in the image {imageName} are detected as below....");
Console.WriteLine("");
}
Now that you have helper methods to create visual feedback from the predictions, add a for-loop to iterate over
each of the scored images.
Inside of the for-loop, get the name of the image file and the bounding boxes associated with it.
Below that, use the DrawBoundingBox method to draw the bounding boxes on the image.
LogDetectedObjects(imageFileName, detectedObjects);
After the try-catch statement, add additional logic to indicate the process is done running.
That's it!
Results
After following the previous steps, run your console app (Ctrl + F5). Your results should be similar to the
following output. You may see warnings or processing messages, but these messages have been removed from
the following results for clarity.
=====Identify the objects in the images=====
To see the images with bounding boxes, navigate to the assets/images/output/ directory. Below is a sample
from one of the processed images.
Congratulations! You've now successfully built a machine learning model for object detection by reusing a pre-
trained ONNX model in ML.NET.
You can find the source code for this tutorial at the dotnet/machinelearning-samples repository.
In this tutorial, you learned how to:
Understand the problem
Learn what ONNX is and how it works with ML.NET
Understand the model
Reuse the pre-trained model
Detect objects with a loaded model
Check out the Machine Learning samples GitHub repository to explore an expanded object detection sample.
dotnet/machinelearning-samples GitHub repository
Tutorial: Analyze sentiment of movie reviews using a
pre-trained TensorFlow model in ML.NET
11/2/2020 • 10 minutes to read • Edit Online
This tutorial shows you how to use a pre-trained TensorFlow model to classify sentiment in website comments.
The binary sentiment classifier is a C# console application developed using Visual Studio.
The TensorFlow model used in this tutorial was trained using movie reviews from the IMDB database. Once you
have finished developing the application, you will be able to supply movie review text and the application will
tell you whether the review has positive or negative sentiment.
In this tutorial, you learn how to:
Load a pre-trained TensorFlow model
Transform website comment text into features suitable for the model
Use the model to make a prediction
You can find the source code for this tutorial at the dotnet/samples repository.
Prerequisites
Visual Studio 2017 version 15.6 or later with the ".NET Core cross-platform development" workload installed.
Setup
Create the application
1. Create a .NET Core Console Application called "TextClassificationTF".
2. Create a directory named Data in your project to save your data set files.
3. Install the Microsoft.ML NuGet Package :
NOTE
This sample uses the latest stable version of the NuGet packages mentioned unless otherwise stated.
In Solution Explorer, right-click on your project and select Manage NuGet Packages . Choose
"nuget.org" as the package source, and then select the Browse tab. Search for Microsoft.ML , select the
package you want, and then select the Install button. Proceed with the installation by agreeing to the
license terms for the package you choose. Repeat these steps for Microsoft.ML.TensorFlow ,
Microsoft.ML.SampleUtils and SciSharp.TensorFlow.Redist .
Add the TensorFlow model to the project
NOTE
The model for this tutorial is from the dotnet/machinelearning-testdata GitHub repo. The model is in TensorFlow
SavedModel format.
3. In Solution Explorer, right-click each of the files in the sentiment_model directory and subdirectory and
select Proper ties . Under Advanced , change the value of Copy to Output Director y to Copy if
newer .
Add using statements and global variables
1. Add the following additional using statements to the top of the Program.cs file:
using System;
using System.IO;
using System.Collections.Generic;
using Microsoft.ML;
using Microsoft.ML.Data;
using Microsoft.ML.Transforms;
2. Create two global variables right above the Main method to hold the saved model file path, and the
feature vector length.
The variable length feature array is then resized to a fixed length of 600. This is the length that the TensorFlow
model expects.
P RO P ERT Y VA L UE TYPE
1. Create a class for your input data, after the Main method:
/// <summary>
/// Class to hold original sentiment data.
/// </summary>
public class MovieReview
{
public string ReviewText { get; set; }
}
The input data class, MovieReview , has a string for user comments ( ReviewText ).
2. Create a class for the variable length features, after the Main method:
/// <summary>
/// Class to hold the variable length feature vector. Used to define the
/// column names used as input to the custom mapping action.
/// </summary>
public class VariableLength
{
/// <summary>
/// This is a variable length vector designated by VectorType attribute.
/// Variable length vectors are produced by applying operations such as 'TokenizeWords' on
strings
/// resulting in vectors of tokens of variable lengths.
/// </summary>
[VectorType]
public int[] VariableLengthFeatures { get; set; }
}
The VariableLengthFeatures property has a VectorType attribute to designate it as a vector. All of the
vector elements must be the same type. In data sets with a large number of columns, loading multiple
columns as a single vector reduces the number of data passes when you apply data transformations.
This class is used in the ResizeFeatures action. The names of its properties (in this case only one) are
used to indicate which columns in the DataView can be used as the input to the custom mapping action.
3. Create a class for the fixed length features, after the Main method:
/// <summary>
/// Class to hold the fixed length feature vector. Used to define the
/// column names used as output from the custom mapping action,
/// </summary>
public class FixedLength
{
/// <summary>
/// This is a fixed length vector designated by VectorType attribute.
/// </summary>
[VectorType(FeatureLength)]
public int[] Features { get; set; }
}
This class is used in the ResizeFeatures action. The names of its properties (in this case only one) are
used to indicate which columns in the DataView can be used as the output of the custom mapping action.
Note that the name of the property Features is determined by the TensorFlow model. You cannot change
this property name.
4. Create a class for the prediction after the Main method:
/// <summary>
/// Class to contain the output values from the transformation.
/// </summary>
public class MovieReviewSentimentPrediction
{
[VectorType(2)]
public float[] Prediction { get; set; }
}
1. Replace the Console.WriteLine("Hello World!") line in the Main method with the following code to
declare and initialize the mlContext variable:
2. Create a dictionary to encode words as integers by using the LoadFromTextFile method to load mapping
data from a file, as seen in the following table:
W O RD IN DEX
kids 362
want 181
wrong 355
effects 302
W O RD IN DEX
feeling 547
3. Add an Action to resize the variable length word integer array to an integer array of fixed size, with the
next lines of code:
Once the model is loaded, you can extract its input and output schema. The schemas are displayed for
interest and learning only. You do not need this code for the final application to function:
The input schema is the fixed-length array of integer encoded words. The output schema is a float array
of probabilities indicating whether a review's sentiment is negative, or positive . These values sum to 1, as
the probability of being positive is the complement of the probability of the sentiment being negative.
The TokenizeIntoWords transform uses spaces to parse the text/string into words. It creates a new column
and splits each input string to a vector of substrings based on the user-defined separator.
2. Map the words onto their integer encoding using the lookup table that you declared above:
// Map each word to an integer value. The array of integer makes up the input features.
.Append(mlContext.Transforms.Conversion.MapValue("VariableLengthFeatures", lookupMap,
lookupMap.Schema["Words"], lookupMap.Schema["Ids"], "TokenizedWords"))
3. Resize the variable length integer encodings to the fixed-length one required by the model:
The TensorFlow model output is called Prediction/Softmax . Note that the name Prediction/Softmax is
determined by the TensorFlow model. You cannot change this name.
5. Create a new column for the output prediction:
You need to copy the Prediction/Softmax column into one with a name that can be used as a property in
a C# class: Prediction . The / character is not allowed in a C# property name.
An ML.NET model is created from the chain of estimators in the pipeline by calling the Fit method. In
this case, we are not fitting any data to create the model, as the TensorFlow model has already been
previously trained. We supply an empty data view object to satisfy the requirements of the Fit method.
2. Add the following code to create the PredictionEngine as the first line in the PredictSentiment()
method:
The PredictionEngine is a convenience API, which allows you to perform a prediction on a single instance
of data. PredictionEngine is not thread-safe. It's acceptable to use in single-threaded or prototype
environments. For improved performance and thread safety in production environments, use the
PredictionEnginePool service, which creates an ObjectPool of PredictionEngine objects for use
throughout your application. See this guide on how to use PredictionEnginePool in an ASP.NET Core Web
API.
NOTE
PredictionEnginePool service extension is currently in preview.
3. Add a comment to test the trained model's prediction in the Predict() method by creating an instance
of MovieReview :
4. Pass the test comment data to the Prediction Engine by adding the next lines of code in the
PredictSentiment() method:
P RO P ERT Y VA L UE TYPE
PredictSentiment(mlContext, model);
Results
Build and run your application.
Your results should be similar to the following. During processing, messages are displayed. You may see
warnings, or processing messages. These messages have been removed from the following results for clarity.
Number of classes: 2
Is sentiment/review positive ? Yes
Congratulations! You've now successfully built a machine learning model for classifying and predicting
messages sentiment by reusing a pre-trained TensorFlow model in ML.NET.
You can find the source code for this tutorial at the dotnet/samples repository.
In this tutorial, you learned how to:
Load a pre-trained TensorFlow model
Transform website comment text into features suitable for the model
Use the model to make a prediction
Create a game match up list app with Infer.NET and
probabilistic programming
2/8/2020 • 4 minutes to read • Edit Online
This how-to guide teaches you about probabilistic programming using Infer.NET. Probabilistic programming is a
machine learning approach where custom models are expressed as computer programs. It allows for
incorporating domain knowledge in the models and makes the machine learning system more interpretable. It
also supports online inference – the process of learning as new data arrives. Infer.NET is used in various
products at Microsoft in Azure, Xbox, and Bing.
Prerequisites
Local development environment setup
This how-to guide expects you to have a machine you can use for development. The .NET tutorial Hello
World in 10 minutes has instructions for setting up your local development environment on macOS,
Windows, or Linux.
The dotnet command creates a new application of type console . The -o parameter creates a directory
named myApp where your app is stored and populates it with the required files. The cd myApp command puts
you into the newly created app directory.
GA M E W IN N ER LO SER
1 Player 0 Player 1
2 Player 0 Player 3
3 Player 0 Player 4
4 Player 1 Player 2
5 Player 3 Player 1
6 Player 4 Player 2
With a closer look at the sample data, you’ll notice that players 3 and 4 both have one win and one loss. Let's see
what the rankings look like using probabilistic programming. Notice also there is a player zero because even
office match up lists are zero based to us developers.
{
using System;
using System.Linq;
using Microsoft.ML.Probabilistic;
using Microsoft.ML.Probabilistic.Distributions;
using Microsoft.ML.Probabilistic.Models;
class Program
{
using (Variable.ForEach(game))
{
// The player performance is a noisy version of their skill
var winnerPerformance = Variable.GaussianFromMeanAndVariance(playerSkills[winners[game]], 1.0);
var loserPerformance = Variable.GaussianFromMeanAndVariance(playerSkills[losers[game]], 1.0);
// Run inference
var inferenceEngine = new InferenceEngine();
var inferredSkills = inferenceEngine.Infer<Gaussian[]>(playerSkills);
dotnet run
Results
Your results should be similar to the following:
Compiling model...done.
Iterating:
.........|.........|.........|.........|.........| 50
Player 0 skill: Gaussian(9.517, 3.926)
Player 3 skill: Gaussian(6.834, 3.892)
Player 4 skill: Gaussian(6.054, 4.731)
Player 1 skill: Gaussian(4.955, 3.503)
Player 2 skill: Gaussian(2.639, 4.288)
In the results, notice that player 3 ranks slightly higher than player 4 according to our model. That’s because the
victory of player 3 over player 1 is more significant than the victory of player 4 over player 2 – note that player
1 beats player 2. Player 0 is the overall champ!
Keep learning
Designing statistical models is a skill on its own. The Microsoft Research Cambridge team has written a free
online book, which gives a gentle introduction to the article. Chapter 3 of this book covers the TrueSkill model in
more detail. Once you have a model in mind, you can transform it into code using the extensive documentation
on the Infer.NET website.
Next steps
Check out the Infer.NET GitHub repository to continue learning and find more samples.
dotnet/infer GitHub repository
Machine learning tasks in ML.NET
11/2/2020 • 7 minutes to read • Edit Online
A machine learning task is the type of prediction or inference being made, based on the problem or question
that is being asked, and the available data. For example, the classification task assigns data to categories, and the
clustering task groups data according to similarity.
Machine learning tasks rely on patterns in the data rather than being explicitly programmed.
This article describes the different machine learning tasks that you can choose from in ML.NET and some
common use cases.
Once you have decided which task works for your scenario, then you need to choose the best algorithm to train
your model. The available algorithms are listed in the section for each task.
Binary classification
A supervised machine learning task that is used to predict which of two classes (categories) an instance of data
belongs to. The input of a classification algorithm is a set of labeled examples, where each label is an integer of
either 0 or 1. The output of a binary classification algorithm is a classifier, which you can use to predict the class
of new unlabeled instances. Examples of binary classification scenarios include:
Understanding sentiment of Twitter comments as either "positive" or "negative".
Diagnosing whether a patient has a certain disease or not.
Making a decision to mark an email as "spam" or not.
Determining if a photo contains a particular item or not, such as a dog or fruit.
For more information, see the Binary classification article on Wikipedia.
Binary classification trainers
You can train a binary classification model using the following algorithms:
AveragedPerceptronTrainer
SdcaLogisticRegressionBinaryTrainer
SdcaNonCalibratedBinaryTrainer
SymbolicSgdLogisticRegressionBinaryTrainer
LbfgsLogisticRegressionBinaryTrainer
LightGbmBinaryTrainer
FastTreeBinaryTrainer
FastForestBinaryTrainer
GamBinaryTrainer
FieldAwareFactorizationMachineTrainer
PriorTrainer
LinearSvmTrainer
Binary classification inputs and outputs
For best results with binary classification, the training data should be balanced (that is, equal numbers of
positive and negative training data). Missing values should be handled before training.
The input label column data must be Boolean. The input features column data must be a fixed-size vector of
Single.
These trainers output the following columns:
O UT P UT C O L UM N N A M E C O L UM N T Y P E DESC RIP T IO N
Multiclass classification
A supervised machine learning task that is used to predict the class (category) of an instance of data. The input
of a classification algorithm is a set of labeled examples. Each label normally starts as text. It is then run through
the TermTransform, which converts it to the Key (numeric) type. The output of a classification algorithm is a
classifier, which you can use to predict the class of new unlabeled instances. Examples of multi-class
classification scenarios include:
Determining the breed of a dog as a "Siberian Husky", "Golden Retriever", "Poodle", etc.
Understanding movie reviews as "positive", "neutral", or "negative".
Categorizing hotel reviews as "location", "price", "cleanliness", etc.
For more information, see the Multiclass classification article on Wikipedia.
NOTE
One vs all upgrades any binary classification learner to act on multiclass datasets. More information on Wikipedia.
Regression
A supervised machine learning task that is used to predict the value of the label from a set of related features.
The label can be of any real value and is not from a finite set of values as in classification tasks. Regression
algorithms model the dependency of the label on its related features to determine how the label will change as
the values of the features are varied. The input of a regression algorithm is a set of examples with labels of
known values. The output of a regression algorithm is a function, which you can use to predict the label value
for any new set of input features. Examples of regression scenarios include:
Predicting house prices based on house attributes such as number of bedrooms, location, or size.
Predicting future stock prices based on historical data and current market trends.
Predicting sales of a product based on advertising budgets.
Regression trainers
You can train a regression model using the following algorithms:
LbfgsPoissonRegressionTrainer
LightGbmRegressionTrainer
SdcaRegressionTrainer
OlsTrainer
OnlineGradientDescentTrainer
FastTreeRegressionTrainer
FastTreeTweedieTrainer
FastForestRegressionTrainer
GamRegressionTrainer
Regression inputs and outputs
The input label column data must be Single.
The trainers for this task output the following:
Clustering
An unsupervised machine learning task that is used to group instances of data into clusters that contain similar
characteristics. Clustering can also be used to identify relationships in a dataset that you might not logically
derive by browsing or simple observation. The inputs and outputs of a clustering algorithm depends on the
methodology chosen. You can take a distribution, centroid, connectivity, or density-based approach. ML.NET
currently supports a centroid-based approach using K-Means clustering. Examples of clustering scenarios
include:
Understanding segments of hotel guests based on habits and characteristics of hotel choices.
Identifying customer segments and demographics to help build targeted advertising campaigns.
Categorizing inventory based on manufacturing metrics.
Clustering trainer
You can train a clustering model using the following algorithm:
KMeansTrainer
Clustering inputs and outputs
The input features data must be Single. No labels are needed.
This trainer outputs the following:
Anomaly detection
This task creates an anomaly detection model by using Principal Component Analysis (PCA). PCA-Based
Anomaly Detection helps you build a model in scenarios where it is easy to obtain training data from one class,
such as valid transactions, but difficult to obtain sufficient samples of the targeted anomalies.
An established technique in machine learning, PCA is frequently used in exploratory data analysis because it
reveals the inner structure of the data and explains the variance in the data. PCA works by analyzing data that
contains multiple variables. It looks for correlations among the variables and determines the combination of
values that best captures differences in outcomes. These combined feature values are used to create a more
compact feature space called the principal components.
Anomaly detection encompasses many important tasks in machine learning:
Identifying transactions that are potentially fraudulent.
Learning patterns that indicate that a network intrusion has occurred.
Finding abnormal clusters of patients.
Checking values entered into a system.
Because anomalies are rare events by definition, it can be difficult to collect a representative sample of data to
use for modeling. The algorithms included in this category have been especially designed to address the core
challenges of building and training models by using imbalanced data sets.
Anomaly detection trainer
You can train an anomaly detection model using the following algorithm:
RandomizedPcaTrainer
Anomaly detection inputs and outputs
The input features must be a fixed-sized vector of Single.
This trainer outputs the following:
Ranking
A ranking task constructs a ranker from a set of labeled examples. This example set consists of instance groups
that can be scored with a given criteria. The ranking labels are { 0, 1, 2, 3, 4 } for each instance. The ranker is
trained to rank new instance groups with unknown scores for each instance. ML.NET ranking learners are
machine learned ranking based.
Ranking training algorithms
You can train a ranking model with the following algorithms:
LightGbmRankingTrainer
FastTreeRankingTrainer
Ranking input and outputs
The input label data type must be key type or Single. The value of the label determines relevance, where higher
values indicate higher relevance. If the label is a key type, then the key index is the relevance value, where the
smallest index is the least relevant. If the label is a Single, larger values indicate higher relevance.
The feature data must be a fixed size vector of Single and input row group column must be key type.
This trainer outputs the following:
Recommendation
A recommendation task enables producing a list of recommended products or services. ML.NET uses Matrix
factorization (MF), a collaborative filtering algorithm for recommendations when you have historical product
rating data in your catalog. For example, you have historical movie rating data for your users and want to
recommend other movies they are likely to watch next.
Recommendation training algorithms
You can train a recommendation model with the following algorithm:
MatrixFactorizationTrainer
Forecasting
The forecasting task use past time-series data to make predictions about future behavior. Scenarios applicable to
forecasting include weather forecasting, seasonal sales predictions, and predictive maintenance,
Forecasting trainers
You can train a forecasting model with the following algorithm:
ForecastBySsa
How to choose an ML.NET algorithm
1/25/2021 • 4 minutes to read • Edit Online
For each ML.NET task, there are multiple training algorithms to choose from. Which one to choose depends on
the problem you are trying to solve, the characteristics of your data, and the compute and storage resources you
have available. It is important to note that training a machine learning model is an iterative process. You might
need to try multiple algorithms to find the one that works best.
Algorithms operate on features . Features are numerical values computed from your input data. They are
optimal inputs for machine learning algorithms. You transform your raw input data into features using one or
more data transforms. For example, text data is transformed into a set of word counts and word combination
counts. Once the features have been extracted from a raw data type using data transforms, they are referred to
as featurized . For example, featurized text, or featurized image data.
Linear algorithms
Linear algorithms produce a model that calculates scores from a linear combination of the input data and a set
of weights . The weights are parameters of the model estimated during training.
Linear algorithms work well for features that are linearly separable.
Before training with a linear algorithm, the features should be normalized. This prevents one feature from
having more influence over the result than others.
In general, linear algorithms are scalable, fast, cheap to train, and cheap to predict. They scale by the number of
features and approximately by the size of the training data set.
Linear algorithms make multiple passes over the training data. If your dataset fits into memory, then adding a
cache checkpoint to your ML.NET pipeline before appending the trainer will make the training run faster.
Linear Trainers
Stochastic dual coordinated ascent Tuning not needed for good default SdcaLogisticRegressionBinaryTrainer
performance SdcaNonCalibratedBinaryTrainer
SdcaMaximumEntropyMulticlassTrainer
SdcaNonCalibratedMulticlassTrainer
SdcaRegressionTrainer
Symbolic stochastic gradient descent Fastest and most accurate linear binary SymbolicSgdLogisticRegressionBinaryTr
classification trainer. Scales well with ainer
number of processors
Light gradient boosted machine Fastest and most accurate of the LightGbmBinaryTrainer
binary classification tree trainers. LightGbmMulticlassTrainer
Highly tunable LightGbmRegressionTrainer
LightGbmRankingTrainer
Generalized additive model (GAM) Best for problems that perform well GamBinaryTrainer
with tree algorithms but where GamRegressionTrainer
explainability is a priority
Matrix factorization
P RO P ERT IES T RA IN ERS
Meta algorithms
These trainers create a multiclass trainer from a binary trainer. Use with AveragedPerceptronTrainer,
LbfgsLogisticRegressionBinaryTrainer, SymbolicSgdLogisticRegressionBinaryTrainer, LightGbmBinaryTrainer,
FastTreeBinaryTrainer, FastForestBinaryTrainer, GamBinaryTrainer.
K-Means
P RO P ERT IES T RA IN ERS
Naive Bayes
P RO P ERT IES T RA IN ERS
Prior Trainer
P RO P ERT IES T RA IN ERS
SelectColumns Select one or more columns to keep from the input data
NormalizeMeanVariance Subtract the mean (of the training data) and divide by the
variance (of the training data)
NormalizeGlobalContrast Scale each value in a row by subtracting the mean of the row
data and divide by either the standard deviation or l2-norm
(of the row data), and multiply by a configurable scale factor
(default 2)
T RA N SF O RM DEF IN IT IO N
NormalizeBinning Assign the input value to a bin index and divide by the
number of bins to produce a float value between 0 and 1.
The bin boundaries are calculated to evenly distribute the
training data across bins
NormalizeSupervisedBinning Assign the input value to a bin based on its correlation with
label column
NormalizeMinMax Scale the input by the difference between the minimum and
maximum values in the training data
Text transformations
T RA N SF O RM DEF IN IT IO N
RemoveDefaultStopWords Remove default stop words for the specified language from
input columns
Image transformations
T RA N SF O RM DEF IN IT IO N
DetectAnomalyBySrCnn Detect anomalies in the input time series data using the
Spectral Residual (SR) algorithm
T RA N SF O RM DEF IN IT IO N
Missing values
T RA N SF O RM DEF IN IT IO N
Feature selection
T RA N SF O RM DEF IN IT IO N
SelectFeaturesBasedOnMutualInformation Select the features on which the data in the label column is
most dependent
Feature transformations
T RA N SF O RM DEF IN IT IO N
Explainability transformations
T RA N SF O RM DEF IN IT IO N
Calibration transformations
T RA N SF O RM DEF IN IT IO N
Platt(String, String, String) Transforms a binary classifier raw score into a class
probability using logistic regression with parameters
estimated using the training data
Platt(Double, Double, String) Transforms a binary classifier raw score into a class
probability using logistic regression with fixed parameters
Custom transformations
T RA N SF O RM DEF IN IT IO N
Accuracy Accuracy is the proportion of correct The closer to 1.00, the better . But
predictions with a test data set. It is exactly 1.00 indicates an issue
the ratio of number of correct (commonly: label/target leakage, over-
predictions to the total number of fitting, or testing with training data).
input samples. It works well if there are When the test data is unbalanced
similar number of samples belonging (where most of the instances belong to
to each class. one of the classes), the dataset is small,
or scores approach 0.00 or 1.00, then
accuracy doesn't really capture the
effectiveness of a classifier and you
need to check additional metrics.
AUC aucROC or Area under the curve The closer to 1.00, the better . It
measures the area under the curve should be greater than 0.50 for a
created by sweeping the true positive model to be acceptable. A model with
rate vs. the false positive rate. AUC of 0.50 or less is worthless.
AUCPR aucPR or Area under the curve of a The closer to 1.00, the better .
Precision-Recall curve: Useful measure High scores close to 1.00 show that
of success of prediction when the the classifier is returning accurate
classes are imbalanced (highly skewed results (high precision), as well as
datasets). returning a majority of all positive
results (high recall).
F1-score F1 score also known as balanced F- The closer to 1.00, the better . An
score or F-measure. It's the harmonic F1 score reaches its best value at 1.00
mean of the precision and recall. F1 and worst score at 0.00. It tells you
Score is helpful when you want to seek how precise your classifier is.
a balance between Precision and Recall.
For further details on binary classification metrics read the following articles:
Accuracy, Precision, Recall, or F1?
Binary Classification Metrics class
The Relationship Between Precision-Recall and ROC Curves
Log-loss Logarithmic loss measures the The closer to 0.00, the better . A
performance of a classification model perfect model would have a log-loss of
where the prediction input is a 0.00. The goal of our machine learning
probability value between 0.00 and models is to minimize this value.
1.00. Log-loss increases as the
predicted probability diverges from the
actual label.
Log-Loss Reduction Logarithmic loss reduction can be Ranges from -inf and 1.00, where
interpreted as the advantage of the 1.00 is perfect predictions and
classifier over a random prediction. 0.00 indicates mean predictions .
For example, if the value equals 0.20, it
can be interpreted as "the probability
of a correct prediction is 20% better
than random guessing"
Micro-accuracy is generally better aligned with the business needs of ML predictions. If you want to select a
single metric for choosing the quality of a multiclass classification task, it should usually be micro-accuracy.
Example, for a support ticket classification task: (maps incoming tickets to support teams)
Micro-accuracy -- how often does an incoming ticket get classified to the right team?
Macro-accuracy -- for an average team, how often is an incoming ticket correct for their team?
Macro-accuracy overweights small teams in this example; a small team that gets only 10 tickets per year counts
as much as a large team with 10k tickets per year. Micro-accuracy in this case correlates better with the business
need of, "how much time/money can the company save by automating my ticket routing process".
For further details on multi-class classification metrics read the following articles:
Micro- and Macro-average of Precision, Recall, and F-Score
Multiclass Classification with Imbalanced Dataset
Absolute-loss Absolute-loss or Mean absolute error The closer to 0.00, the better
(MAE) measures how close the quality. The mean absolute error uses
predictions are to the actual outcomes. the same scale as the data being
It is the average of all the model measured (is not normalized to specific
errors, where model error is the range). Absolute-loss, Squared-loss,
absolute distance between the and RMS-loss can only be used to
predicted label value and the correct make comparisons between models for
label value. This prediction error is the same dataset or dataset with a
calculated for each record of the test similar label value distribution.
data set. Finally, the mean value is
calculated for all recorded absolute
errors.
RMS-loss RMS-loss or Root Mean Squared Error It is always non-negative, and values
(RMSE) (also called Root Mean Square closer to 0.00 are better . RMSD is
Deviation, RMSD), measures the a measure of accuracy, to compare
difference between values predicted by forecasting errors of different models
a model and the values observed from for a particular dataset and not
the environment that is being between datasets, as it is scale-
modeled. RMS-loss is the square root dependent.
of Squared-loss and has the same
units as the label, similar to the
absolute-loss though giving more
weight to larger differences. Root mean
square error is commonly used in
climatology, forecasting, and
regression analysis to verify
experimental results.
Average Distance Average of the distance between data Values closer to 0 are better. The closer
points and the center of their assigned to zero the average distance is, the
cluster. The average distance is a more clustered the data is. Note
measure of proximity of the data though, that this metric will decrease if
points to cluster centroids. It's a the number of clusters is increased,
measure of how 'tight' the cluster is. and in the extreme case (where each
distinct data point is its own cluster) it
will be equal to zero.
Davies Bouldin Index The average ratio of within-cluster Values closer to 0 are better. Clusters
distances to between-cluster distances. that are farther apart and less
The tighter the cluster, and the further dispersed will result in a better score.
apart the clusters are, the lower this
value is.
Normalized Mutual Information Can be used when the training data Values closer to 1 are better
used to train the clustering model also
comes with ground truth labels (that
is, supervised clustering). The
Normalized Mutual Information metric
measures whether similar data points
get assigned to the same cluster and
disparate data points get assigned to
different clusters. Normalized mutual
information is a value between 0 and 1
Discounted Cumulative Gains Discounted cumulative gain (DCG) is a Higher values are better
measure of ranking quality. It is
derived from two assumptions. One:
Highly relevant items are more useful
when appearing higher in ranking
order. Two: Usefulness tracks relevance
that is, the higher the relevance, the
more useful an item. Discounted
cumulative gain is calculated for a
particular position in the ranking order.
It sums the relevance grading divided
by the logarithm of the ranking index
up to the position of interest. It is
calculated using $\sum_{i=0}^{p} \frac
{rel_i} {\log_{e}{i+1}}$ Relevance
gradings are provided to a ranking
training algorithm as ground truth
labels. One DCG value is provided for
each position in the ranking table,
hence the name Discounted
Cumulative Gains .
M ET RIC DESC RIP T IO N LO O K F O R
Normalized Discounted Normalizing DCG allows the metric to Values closer to 1 are better
Cumulative Gains be compared for ranking lists of
different lengths
Area Under ROC Cur ve Area under the receiver operator curve Values closer to 1 are better . Only
measures how well the model values greater than 0.5 demonstrate
separates anomalous and usual data effectiveness of the model. Values of
points. 0.5 or below indicate that the model is
no better than randomly allocating the
inputs to anomalous and usual
categories
Detection Rate At False Positive Detection rate at false positive count is Values closer to 1 are better . If
Count the ratio of the number of correctly there are no false positives, then this
identified anomalies to the total value is 1
number of anomalies in a test set,
indexed by each false positive. That is,
there is a value for detection rate at
false positive count for each false
positive item.
Improve ML.NET Model Accuracy
1/8/2020 • 2 minutes to read • Edit Online
Cross-validation
Cross-validation is a training and model evaluation technique that splits the data into several partitions and
trains multiple algorithms on these partitions. This technique improves the robustness of the model by holding
out data from the training process. In addition to improving performance on unseen observations, in data-
constrained environments it can be an effective tool for training models with a smaller dataset.
Visit the following link to learn how to use cross validation in ML.NET
Hyperparameter tuning
Training machine learning models is an iterative and exploratory process. For example, what is the optimal
number of clusters when training a model using the K-Means algorithm? The answer depends on many factors
such as the structure of the data. Finding that number would require experimenting with different values for k
and then evaluating performance to determine which value is best. The practice of tuning these parameters to
find an optimal model is known as hyper-parameter tuning.
Learn how to load your training datasets from a file or a SQL Server database for use in one of the Model
Builder scenarios for ML.NET. Model Builder scenarios can use SQL Server databases, image files, and CSV or
TSV file formats as training data.
\---flower_photos
+---daisy
| 100080576_f52e8ee070_n.jpg
| 102841525_bd6628ae3c.jpg
| 105806915_a9c13e2106_n.jpg
|
+---dandelion
| 10443973_aeb97513fc_m.jpg
| 10683189_bd6e371b97.jpg
| 10919961_0af657c4e8.jpg
|
+---roses
| 102501987_3cdb8e5394_n.jpg
| 110472418_87b6a3aa98_m.jpg
| 118974357_0faa23cce9_n.jpg
|
+---sunflowers
| 127192624_afa3d9cb84.jpg
| 145303599_2627e23815_n.jpg
| 147804446_ef9244c8ce_m.jpg
|
\---tulips
100930342_92e8746431_n.jpg
107693873_86021ac4ea_n.jpg
10791227_7168491604.jpg
Next steps
Follow these tutorials to build machine learning apps with Model Builder:
Predict prices using regression
Analyze sentiment in a web application using binary classification
If you're training a model using code, learn how to load data using the ML.NET API.
How to install ML.NET Model Builder
3/6/2020 • 2 minutes to read • Edit Online
Learn how to install ML.NET Model Builder to add machine learning to your .NET applications.
NOTE
Model Builder is currently in Preview.
Prerequisites
Visual Studio 2017 version 15.9.12 or later / Visual Studio 2019
.NET Core 2.1 SDK or later.
NOTE
.NET Core 3.0 SDK is not currently supported.
Limitations
ML.NET Model Builder Extension currently only works on Visual Studio on Windows.
Training dataset limit of 1GB
SQL Server has a limit of 100 thousand rows for training
Microsoft SQL Server Data Tools for Visual Studio 2017 is not supported
Install
ML.NET Model builder can be installed either through the Visual Studio Marketplace or from within Visual
Studio.
Visual Studio Marketplace
1. Download from Visual Studio Marketplace
2. Follow prompts to install onto respective Visual Studio version
Visual Studio 2017
1. In the menu bar, select Tools > Extensions and Updates
2. Inside the Extension and Updates prompt, select the Online node.
3. In the search bar, search for ML.NET Model Builder and from the results, select ML.NET Model Builder
(Preview)
Uninstall
Visual Studio 2017
1. On the menu bar, select Tools > Extensions and Updates
2. Inside the Extension and Updates prompt, expand the Installed node and select Tools
3. Select ML.NET Model Builder (Preview) from the list of tools and then, select Uninstall
Upgrade
The upgrade process is similar to the installation process. Either download the latest version from Visual Studio
Marketplace or use the Extensions Manager in Visual Studio.
How to install GPU support in Model Builder
11/2/2020 • 2 minutes to read • Edit Online
Learn how to install the GPU drivers to use your GPU with Model Builder.
Prerequisites
Model Builder Visual Studio extension. The extension is built into Visual Studio as of version 16.6.1.
Model Builder Visual Studio GPU support extension.
At least one CUDA compatible GPU. For a list of compatible GPUs, see NVIDIA's guide.
NVIDIA developer account. If you don't have one, create a free account.
Install dependencies
1. Install CUDA v10.0. Make sure you install CUDA v10.0, not any other newer version. You cannot have
multiple versions of CUDA installed.
2. Install cuDNN v7.6.4 for CUDA 10.0. You cannot have multiple versions of cuDNN installed. After
downloading cuDNN v7.6.4 zip file and unpacking it, copy <CUDNN_zip_files_path>\cuda\bin\cudnn64_7.dll to
<YOUR_DRIVE>\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.0\bin .
Troubleshooting
How do I know what GPU I have?
Follow instructions provided:
1. Right-click on desktop
2. If you see "NVIDIA Control Panel" or "NVIDIA Display" in the pop-up window, you have an NVIDIA GPU
3. Click on "NVIDIA Control Panel" or "NVIDIA Display" in the pop-up window
4. Look at "Graphics Card Information"
5. You will see the name of your NVIDIA GPU
I don't see NVIDIA Control Panel (or it fails to open) but I know I have an NVIDIA GPU.
1. Open Device Manager
2. Look at Display adapters
3. Install appropriate driver for your GPU.
How to install the ML.NET Command-Line Interface
(CLI) tool
11/2/2020 • 3 minutes to read • Edit Online
Learn how to install the ML.NET CLI (command-line interface) on Windows, Mac, or Linux.
The ML.NET CLI generates good quality ML.NET models and source code using automated machine learning
(AutoML) and a training dataset.
NOTE
This topic refers to ML.NET CLI and ML.NET AutoML, which are currently in Preview, and material may be subject to
change.
Pre-requisites
.NET Core 3.1 SDK
(Optional) Visual Studio 2019
You can run the generated C# code projects with Visual Studio by pressing the F5 key or with dotnet run (.NET
Core CLI).
Note: If after installing .NET Core SDK the dotnet tool command is not working, sign out from Windows and
sign in again.
Install
The ML.NET CLI is installed like any other dotnet Global Tool. You use the dotnet tool install .NET Core CLI
command.
The following example shows how to install the ML.NET CLI in the default NuGet feed location:
If the tool can't be installed (that is, if it is not available at the default NuGet feed), error messages are displayed.
Check that the feeds you expected are being checked.
If installation is successful, a message is displayed showing the command used to call the tool and the version
installed, similar to the following example:
You can invoke the tool using the following command: mlnet
Tool 'mlnet' (version 'X.X.X') was successfully installed.
You can confirm the installation was successful by typing the following command:
mlnet
You should see the help for available commands for the mlnet tool such as the 'classification' command.
Install a specific release version
If you're trying to install a pre-release version or a specific version of the tool, you can specify the framework
using the following format:
You can also check if the package is properly installed by typing the following command:
'Tab-based auto-completion' (parameter suggestions) works on Windows PowerShell and macOS/Linux bash
but it won't work on Windows CMD.
To enable it, in the current preview version, the end user has to take a few steps once per shell, outlined below.
Once this is done, completions will work for all apps written using System.CommandLine such as the ML.NET CLI.
On the machine where you'd like to enable completion, you'll need to do two things.
1. Install the dotnet-suggest global tool by running the following command:
2. Add the appropriate shim script to your shell profile. You may have to create a shell profile file. The shim
script will forward completion requests from your shell to the dotnet-suggest tool, which delegates to
the appropriate System.CommandLine -based app.
For bash, add the contents of dotnet-suggest-shim.bash to ~/.bash_profile .
For PowerShell, add the contents of dotnet-suggest-shim.ps1 to your PowerShell profile. You can
find the expected path to your PowerShell profile by running the following command in your
console:
echo $profile
Installation directory
The ML.NET CLI can be installed in the default directory or in a specific location. The default directories are:
OS PAT H
Linux/macOS $HOME/.dotnet/tools
Windows %USERPROFILE%\.dotnet\tools
These locations are added to the user's path when the SDK is first run, so Global Tools installed there can be
called directly.
Note: the Global Tools are user-specific, not machine global. Being user-specific means you cannot install a
Global Tool that is available to all users of the machine. The tool is only available for each user profile where the
tool was installed.
Global Tools can also be installed in a specific directory. When installed in a specific directory, the user must
ensure the command is available, by including that directory in the path, by calling the command with the
directory specified, or calling the tool from within the specified directory. In this case, the .NET Core CLI doesn't
add this location automatically to the PATH environment variable.
See also
ML.NET CLI overview
Tutorial: Analyze sentiment with the ML.NET CLI
ML.NET CLI auto-train command reference guide
Telemetry in ML.NET CLI
How to use the ML.NET automated machine
learning API
11/2/2020 • 4 minutes to read • Edit Online
Automated machine learning (AutoML) automates the process of applying machine learning to data. Given a
dataset, you can run an AutoML experiment to iterate over different data featurizations, machine learning
algorithms, and hyperparameters to select the best model.
NOTE
This topic refers to the automated machine learning API for ML.NET, which is currently in preview. Material may be subject
to change.
Load data
Automated machine learning supports loading a dataset into an IDataView. Data can be in the form of tab-
separated value (TSV) files and comma separated value (CSV) files.
Example:
using Microsoft.ML;
using Microsoft.ML.AutoML;
// ...
MLContext mlContext = new MLContext();
IDataView trainDataView = mlContext.Data.LoadFromTextFile<SentimentIssue>("my-data-file.csv", hasHeader:
true);
Multiclass Classification
Recommendation
experimentSettings.MaxExperimentTimeInSeconds = 3600;
experimentSettings.CancellationToken = cts.Token;
4. The CacheDirectory setting is a pointer to a directory where all models trained during the AutoML task
will be saved. If CacheDirectory is set to null, models will be kept in memory instead of written to disk.
experimentSettings.CacheDirectory = null;
The list of supported trainers per ML task can be found at the corresponding link below:
Supported Binary Classification Algorithms
Supported Multiclass Classification Algorithms
Supported Regression Algorithms
Supported Recommendation Algorithms
Optimizing metric
The optimizing metric, as shown in the example above, determines the metric to be optimized during model
training. The optimizing metric you can select is determined by the task type you choose. Below is a list of
available metrics.
NegativePrecision TopKAccuracy
NegativeRecall
PositivePrecision
PositiveRecall
Data pre-processing happens by default and the following steps are performed automatically for you:
1. Drop features with no useful information
Drop features with no useful information from training and validation sets. These include features with all
values missing, same value across all rows or with extremely high cardinality (e.g., hashes, IDs or GUIDs).
2. Missing value indication and imputation
Fill missing value cells with the default value for the datatype. Append indicator features with the same
number of slots as the input column. The value in the appended indicator features is 1 if the value in the
input column is missing and 0 otherwise.
3. Generate additional features
For text features: Bag-of-word features using unigrams and tri-character-grams.
For categorical features: One-hot encoding for low cardinality features, and one-hot-hash encoding for
high cardinality categorical features.
4. Transformations and encodings
Text features with very few unique values transformed into categorical features. Depending on cardinality
of categorical features, perform one-hot encoding or one-hot hash encoding.
Exit criteria
Define the criteria to complete your task:
1. Exit after a length of time - Using MaxExperimentTimeInSeconds in your experiment settings you can define
how long in seconds that an task should continue to run.
2. Exit on a cancellation token - You can use a cancellation token that lets you cancel the task before it is
scheduled to finish.
Create an experiment
Once you have configured the experiment settings, you are ready to create the experiment.
Explore other overloads for Execute() if you want to pass in validation data, column information indicating the
column purpose, or prefeaturizers.
Training modes
Training dataset
AutoML provides an overloaded experiment execute method which allows you to provide training data.
Internally, automated ML divides the data into train-validate splits.
experiment.Execute(trainDataView);
experiment.Execute(trainDataView, validationDataView);
See also
For full code samples and more visit the dotnet/machinelearning-samples GitHub repository.
Install extra ML.NET dependencies
1/25/2021 • 2 minutes to read • Edit Online
In most cases, on all operating systems, installing ML.NET is as simple as referencing the appropriate NuGet
package.
In some cases though, there are additional installation requirements, particularly when native components are
required. This document describes the installation requirements for those cases. The sections are broken down
by the specific Microsoft.ML.* NuGet package that has the additional dependency.
Microsoft.ML.TimeSeries, Microsoft.ML.AutoML
Both of these packages have a dependency on Microsoft.ML.MKL.Redist , which has a dependency on libomp .
Windows
No extra installation steps required. The library is installed when the NuGet package is added to the project.
Linux
1. Install the GPG key for the repository
sudo bash
# <type your user password when prompted. this will put you in a root shell>
# cd to /tmp where this shell has write permission
cd /tmp
# now get the key:
wget https://apt.repos.intel.com/intel-gpg-keys/GPG-PUB-KEY-INTEL-SW-PRODUCTS-2019.PUB
# now install that key
apt-key add GPG-PUB-KEY-INTEL-SW-PRODUCTS-2019.PUB
# now remove the public key file exit the root shell
rm GPG-PUB-KEY-INTEL-SW-PRODUCTS-2019.PUB
exit
3. Update packages
4. Install MKL
For example:
sudo apt-get install intel-mkl-64bit-2020.0-088
For example:
/opt/intel/compilers_and_libraries_2020.0.166/linux/compiler/lib/intel64_lin/libiomp5.so
Mac
1. Install the library with Homebrew
Learn how to load data for processing and training into ML.NET using the API. The data is originally stored in
files or other data sources such as databases, JSON, XML or in-memory collections.
If you're using Model Builder, see Load training data into Model Builder.
Size (Sq. ft.), HistoricalPrice1 ($), HistoricalPrice2 ($), HistoricalPrice3 ($), Current Price ($)
700, 100000, 3000000, 250000, 500000
1000, 600000, 400000, 650000, 700000
[LoadColumn(1, 3)]
[VectorType(3)]
public float[] HistoricalPrices { get; set; }
[LoadColumn(4)]
[ColumnName("Label")]
public float CurrentPrice { get; set; }
}
IMPORTANT
LoadColumn is only required when loading data from a file.
//Create MLContext
MLContext mlContext = new MLContext();
//Load Data
IDataView data = mlContext.Data.LoadFromTextFile<HousingData>("my-data-file.csv", separatorChar: ',',
hasHeader: true);
//Create MLContext
MLContext mlContext = new MLContext();
//Create MLContext
MLContext mlContext = new MLContext();
// Create TextLoader
TextLoader textLoader = mlContext.Data.CreateTextLoader<HousingData>(separatorChar: ',', hasHeader: true);
// Load Data
IDataView data = textLoader.Load("DataFolder/SubFolder1/1.txt", "DataFolder/SubFolder2/1.txt");
Given a database with a table named House and the following schema:
Define your connection string as well as the SQL command to be executed on the database and create a
DatabaseSource instance. This sample uses a LocalDB SQL Server database with a file path. However,
DatabaseLoader supports any other valid connection string for databases on-premises and in the cloud.
string sqlCommand = "SELECT Size, CAST(NumBed as REAL) as NumBed, Price FROM House";
Numerical data that is not of type Real has to be converted to Real . The Real type is represented as a single-
precision floating-point value or Single , the input type expected by ML.NET algorithms. In this sample, the
NumBed column is an integer in the database. Using the CAST built-in function, it's converted to Real . Because
the Price property is already of type Real it is loaded as is.
Use the Load method to load the data into an IDataView .
Load the in-memory collection into an IDataView with the LoadFromEnumerable method:
IMPORTANT
LoadFromEnumerable assumes that the IEnumerable it loads from is thread-safe.
// Create MLContext
MLContext mlContext = new MLContext();
//Load Data
IDataView data = mlContext.Data.LoadFromEnumerable<HousingData>(inMemoryCollection);
Next steps
To clean or otherwise process data, see Prepare data for building a model.
When you're ready to build a model, see Train and evaluate a model.
Prepare data for building a model
2/13/2020 • 8 minutes to read • Edit Online
Learn how to use ML.NET to prepare data for additional processing or building a model.
Data is often unclean and sparse. ML.NET machine learning algorithms expect input or features to be in a single
numerical vector. Similarly, the value to predict (label), especially when it's categorical data, has to be encoded.
Therefore one of the goals of data preparation is to get the data into the format expected by ML.NET algorithms.
Filter data
Sometimes, not all data in a dataset is relevant for analysis. An approach to remove irrelevant data is filtering.
The DataOperationsCatalog contains a set of filter operations that take in an IDataView containing all of the data
and return an IDataView containing only the data points of interest. It's important to note that because filter
operations are not an IEstimator or ITransformer like those in the TransformsCatalog , they cannot be included
as part of an EstimatorChain or TransformerChain data preparation pipeline.
Take the following input data and load it into an IDataView called data :
To filter data based on the value of a column, use the FilterRowsByColumn method.
// Apply filter
IDataView filteredData = mlContext.Data.FilterRowsByColumn(data, "Price", lowerBound: 200000, upperBound:
1000000);
The sample above takes rows in the dataset with a price between 200000 and 1000000. The result of applying
this filter would return only the last two rows in the data and exclude the first row because its price is 100000
and not between the specified range.
Notice that the last element in our list has a missing value for Price . To replace the missing values in the Price
column, use the ReplaceMissingValues method to fill in that missing value.
IMPORTANT
ReplaceMissingValue only works with numerical data.
// Transform data
IDataView transformedData = replacementTransformer.Transform(data);
ML.NET supports various replacement modes. The sample above uses the Mean replacement mode, which fills
in the missing value with that column's average value. The replacement 's result fills in the Price property for
the last element in our data with 200,000 since it's the average of 100,000 and 300,000.
Use normalizers
Normalization is a data pre-processing technique used to scale features to be in the same range, usually
between 0 and 1, so that they can be more accurately processed by a machine learning algorithm. For example,
the ranges for age and income vary significantly with age generally being in the range of 0-100 and income
generally being in the range of zero to thousands. Visit the transforms page for a more detailed list and
description of normalization transforms.
Min-Max normalization
Take the following input data and load it into an IDataView called data :
HomeData[] homeDataList = new HomeData[]
{
new HomeData
{
NumberOfBedrooms = 2f,
Price = 200000f
},
new HomeData
{
NumberOfBedrooms = 1f,
Price = 100000f
}
};
Normalization can be applied to columns with single numerical values as well as vectors. Normalize the data in
the Price column using min-max normalization with the NormalizeMinMax method.
// Transform data
IDataView transformedData = minMaxTransformer.Transform(data);
The original price values [200000,100000] are converted to [ 1, 0.5 ] using the MinMax normalization
formula that generates output values in the range of 0-1.
Binning
Binning converts continuous values into a discrete representation of the input. For example, suppose one of
your features is age. Instead of using the actual age value, binning creates ranges for that value. 0-18 could be
one bin, another could be 19-35 and so on.
Take the following input data and load it into an IDataView called data :
Normalize the data into bins using the NormalizeBinning method. The maximumBinCount parameter enables you
to specify the number of bins needed to classify your data. In this example, data will be put into two bins.
// Define binning estimator
var binningEstimator = mlContext.Transforms.NormalizeBinning("Price", maximumBinCount: 2);
// Transform Data
IDataView transformedData = binningTransformer.Transform(data);
The result of binning creates bin bounds of [0,200000,Infinity] . Therefore the resulting bins are [0,1,1]
because the first observation is between 0-200000 and the others are greater than 200000 but less than infinity.
RAW VA L UE O N E H OT EN C O DED VA L UE
98052 00...01
98100 00...10
... ...
98109 10...00
ML.NET provides the FeaturizeText transform that takes a text's string value and creates a set of features from
the text, by applying a series of individual transforms.
// Transform data
IDataView transformedData = textTransformer.Transform(data);
The resulting transform converts the text values in the Description column to a numerical vector that looks
similar to the output below:
The transforms that make up FeaturizeText can also be applied individually for finer grain control over feature
generation.
textEstimator contains a subset of operations performed by the FeaturizeText method. The benefit of a more
complex pipeline is control and visibility over the transformations applied to the data.
Using the first entry as an example, the following is a detailed description of the results produced by the
transformation steps defined by textEstimator :
Original Text: This is a good product
Learn how to build machine learning models, collect metrics, and measure performance with ML.NET. Although
this sample trains a regression model, the concepts are applicable throughout a majority of the other
algorithms.
[LoadColumn(1, 3)]
[VectorType(3)]
public float[] HistoricalPrices { get; set; }
[LoadColumn(4)]
[ColumnName("Label")]
public float CurrentPrice { get; set; }
}
Use the TrainTestSplit method to split the data into train and test sets. The result will be a TrainTestData
object which contains two IDataView members, one for the train set and the other for the test set. The data split
percentage is determined by the testFraction parameter. The snippet below is holding out 20 percent of the
original data for the test set.
If you don't want to use the default column names, pass in the names of the feature and label columns as
parameters when defining the machine learning algorithm estimator as demonstrated by the subsequent
snippet:
Caching data
By default, when data is processed, it is lazily loaded or streamed which means that trainers may load the data
from disk and iterate over it multiple times during training. Therefore, caching is recommended for datasets that
fit into memory to reduce the number of times data is loaded from disk. Caching is done as part of an
EstimatorChain by using AppendCacheCheckpoint .
NOTE
Other models have parameters that are specific to their tasks. For example, the K-Means algorithm puts data into cluster
based on centroids and the KMeansModelParameters contains a property that stores these learned centroids. To learn
more, visit the Microsoft.ML.Trainers API Documentation and look for classes that contain ModelParameters in their
name.
NOTE
The Evaluate method produces different metrics depending on which machine learning task was performed. For more
details, visit the Microsoft.ML.Data API Documentation and look for classes that contain Metrics in their name.
// Measure trained model performance
// Apply data prep transformer to test data
IDataView transformedTestData = dataPrepTransformer.Transform(testData);
NOTE
In this small example, the R-Squared is a number not in the range of 0-1 because of the limited size of the data. In a real-
world scenario, you should expect to see a value between 0 and 1.
Train a machine learning model using cross
validation
11/2/2020 • 3 minutes to read • Edit Online
Learn how to use cross validation to train more robust machine learning models in ML.NET.
Cross-validation is a training and model evaluation technique that splits the data into several partitions and
trains multiple algorithms on these partitions. This technique improves the robustness of the model by holding
out data from the training process. In addition to improving performance on unseen observations, in data-
constrained environments it can be an effective tool for training models with a smaller dataset.
Size (Sq. ft.), HistoricalPrice1 ($), HistoricalPrice2 ($), HistoricalPrice3 ($), Current Price ($)
620.00, 148330.32, 140913.81, 136686.39, 146105.37
550.00, 557033.46, 529181.78, 513306.33, 548677.95
1127.00, 479320.99, 455354.94, 441694.30, 472131.18
1120.00, 47504.98, 45129.73, 43775.84, 46792.41
The data can be modeled by a class like HousingData and loaded into an IDataView .
[LoadColumn(1, 3)]
[VectorType(3)]
public float[] HistoricalPrices { get; set; }
[LoadColumn(4)]
[ColumnName("Label")]
public float CurrentPrice { get; set; }
}
// Transform data
IDataView transformedData = dataPrepTransformer.Transform(data);
NOTE
Although this sample uses a linear regression model, CrossValidate is applicable to all other machine learning tasks in
ML.NET except Anomaly Detection.
IEnumerable<double> rSquared =
cvResults
.Select(fold => fold.Metrics.RSquared);
If you inspect the contents of the rSquared variable, the output should be five values ranging from 0-1 where
closer to 1 means best. Using metrics like R-Squared, select the models from best to worst performing. Then,
select the top model to make predictions or perform additional operations with.
Learn how to inspect intermediate data during loading, processing, and model training steps in ML.NET.
Intermediate data is the output of each stage in the machine learning pipeline.
Intermediate data like the one represented below which is loaded into an IDataView can be inspected in various
ways in ML.NET.
WARNING
Converting the result of CreateEnumerable to an array or list will load all the requested IDataView rows into memory
which may affect performance.
Once the collection has been created, you can perform operations on the data. The code snippet below takes the
first three rows in the dataset and calculates the average current price.
// Create DataViewCursor
using (DataViewRowCursor cursor = data.GetRowCursor(columns))
{
// Define variables where extracted values will be stored to
float size = default;
VBuffer<float> historicalPrices = default;
float currentPrice = default;
The model building process is experimental and iterative. To preview what data would look like after pre-
processing or training a machine learning model on a subset of the data, use the Preview method which
returns a DataDebuggerPreview . The result is an object with ColumnView and RowView properties which are both
an IEnumerable and contain the values in a particular column or row. Specify the number of rows to apply the
transformation to with the maxRows parameter.
Using Permutation Feature Importance (PFI), learn how to interpret ML.NET machine learning model predictions.
PFI gives the relative contribution each feature makes to a prediction.
Machine learning models are often thought of as opaque boxes that take inputs and generate an output. The
intermediate steps or interactions among the features that influence the output are rarely understood. As
machine learning is introduced into more aspects of everyday life such as healthcare, it's of utmost importance
to understand why a machine learning model makes the decisions it does. For example, if diagnoses are made
by a machine learning model, healthcare professionals need a way to look into the factors that went into making
that diagnoses. Providing the right diagnosis could make a great difference on whether a patient has a speedy
recovery or not. Therefore the higher the level of explainability in a model, the greater confidence healthcare
professionals have to accept or reject the decisions made by the model.
Various techniques are used to explain models, one of which is PFI. PFI is a technique used to explain
classification and regression models that is inspired by Breiman's Random Forests paper (see section 10). At a
high level, the way it works is by randomly shuffling data one feature at a time for the entire dataset and
calculating how much the performance metric of interest decreases. The larger the change, the more important
that feature is.
Additionally, by highlighting the most important features, model builders can focus on using a subset of more
meaningful features which can potentially reduce noise and training time.
1,24,13,1,0.59,3,96,11,23,608,14,13,32
4,80,18,1,0.37,5,14,7,4,346,19,13,41
2,98,16,1,0.25,10,5,1,8,689,13,36,12
The data in this sample can be modeled by a class like HousingPriceData and loaded into an IDataView .
class HousingPriceData
{
[LoadColumn(0)]
public float CrimeRate { get; set; }
[LoadColumn(1)]
public float ResidentialZones { get; set; }
[LoadColumn(2)]
public float CommercialZones { get; set; }
[LoadColumn(3)]
public float NearWater { get; set; }
[LoadColumn(4)]
public float ToxicWasteLevels { get; set; }
[LoadColumn(5)]
public float AverageRoomNumber { get; set; }
[LoadColumn(6)]
public float HomeAge { get; set; }
[LoadColumn(7)]
public float BusinessCenterDistance { get; set; }
[LoadColumn(8)]
public float HighwayAccess { get; set; }
[LoadColumn(9)]
public float TaxRate { get; set; }
[LoadColumn(10)]
public float StudentTeacherRatio { get; set; }
[LoadColumn(11)]
public float PercentPopulationBelowPoverty { get; set; }
[LoadColumn(12)]
[ColumnName("Label")]
public float Price { get; set; }
}
Train the model
The code sample below illustrates the process of training a linear regression model to predict house prices.
ImmutableArray<RegressionMetricsStatistics> permutationFeatureImportance =
mlContext
.Regression
.PermutationFeatureImportance(sdcaModel, preprocessedTrainData, permutationCount:3);
Console.WriteLine("Feature\tPFI");
Printing the values for each of the features in featureImportanceMetrics would generate output similar to that
below. Keep in mind that you should expect to see different results because these values vary based on the data
that they are given.
HighwayAccess -0.042731
StudentTeacherRatio -0.012730
BusinessCenterDistance -0.010491
TaxRate -0.008545
AverageRoomNumber -0.003949
CrimeRate -0.003665
CommercialZones 0.002749
HomeAge -0.002426
ResidentialZones -0.002319
NearWater 0.000203
PercentPopulationLivingBelowPoverty 0.000031
ToxicWasteLevels -0.000019
Taking a look at the five most important features for this dataset, the price of a house predicted by this model is
influenced by its proximity to highways, student teacher ratio of schools in the area, proximity to major
employment centers, property tax rate and average number of rooms in the home.
Save and load trained models
11/2/2020 • 3 minutes to read • Edit Online
// Create MLContext
MLContext mlContext = new MLContext();
// Load Data
IDataView data = mlContext.Data.LoadFromEnumerable<HousingData>(housingData);
// Train model
ITransformer trainedModel = pipelineEstimator.Fit(data);
// Save model
mlContext.Model.Save(trainedModel, data.Schema, "model.zip");
Because most models and data preparation pipelines inherit from the same set of classes, the save and load
method signatures for these components is the same. Depending on your use case, you can either combine the
data preparation pipeline and model into a single EstimatorChain which would output a single ITransformer or
separate them thus creating a separate ITransformer for each.
Save a model locally
When saving a model you need two things:
1. The ITransformer of the model.
2. The DataViewSchema of the ITransformer 's expected input.
After training the model, use the Save method to save the trained model to a file called model.zip using the
DataViewSchema of the input data.
// Create MLContext
MLContext mlContext = new MLContext();
When working with separate data preparation pipelines and models, the same process as single pipelines
applies; except now both pipelines need to be saved and loaded simultaneously.
Given separate data preparation and model training pipelines:
// Create MLContext
MLContext mlContext = new MLContext();
[LoadColumn(1, 3)]
[VectorType(3)]
public float[] HistoricalPrices { get; set; }
[LoadColumn(4)]
[ColumnName("Label")]
public float CurrentPrice { get; set; }
}
Output data
Like the Features and Label input column names, ML.NET has default names for the predicted value columns
produced by a model. Depending on the task the name may differ.
Because the algorithm used in this sample is a linear regression algorithm, the default name of the output
column is Score which is defined by the ColumnName attribute on the PredictedPrice property.
class HousingPrediction
{
[ColumnName("Score")]
public float PredictedPrice { get; set; }
}
//Create MLContext
MLContext mlContext = new MLContext();
Single prediction
To make a single prediction, create a PredictionEngine using the loaded prediction pipeline.
// Create PredictionEngines
PredictionEngine<HousingData, HousingPrediction> predictionEngine =
mlContext.Model.CreatePredictionEngine<HousingData, HousingPrediction>(predictionPipeline);
Then, use the Predict method and pass in your input data as a parameter. Notice that using the Predict
method does not require the input to be an IDataView ). This is because it conveniently internalizes the input
data type manipulation so you can pass in an object of the input data type. Additionally, since CurrentPrice is
the target or label you're trying to predict using new data, it's assumed there is no value for it at the moment.
// Input Data
HousingData inputData = new HousingData
{
Size = 900f,
HistoricalPrices = new float[] { 155000f, 190000f, 220000f }
};
// Get Prediction
HousingPrediction prediction = predictionEngine.Predict(inputData);
If you access the Score property of the prediction object, you should get a value similar to 150079 .
Multiple predictions
Given the following data, load it into an IDataView . In this case, the name of the IDataView is inputData .
Because CurrentPrice is the target or label you're trying to predict using new data, it's assumed there is no
value for it at the moment.
// Actual data
HousingData[] housingData = new HousingData[]
{
new HousingData
{
Size = 850f,
HistoricalPrices = new float[] { 150000f, 175000f, 210000f }
},
new HousingData
{
Size = 900f,
HistoricalPrices = new float[] { 155000f, 190000f, 220000f }
},
new HousingData
{
Size = 550f,
HistoricalPrices = new float[] { 99000f, 98000f, 130000f }
}
};
Then, use the Transform method to apply the data transformations and generate predictions.
// Predicted Data
IDataView predictions = predictionPipeline.Transform(inputData);
// Get Predictions
float[] scoreColumn = predictions.GetColumn<float>("Score").ToArray();
The predicted values in the score column should look like the following:
O B SERVAT IO N P REDIC T IO N
1 144638.2
2 150079.4
3 107789.8
Re-train a model
11/2/2020 • 2 minutes to read • Edit Online
// Create MLContext
MLContext mlContext = new MLContext();
Re-train model
The process for retraining a model is no different than that of training a model. The only difference is, the Fit
method in addition to the data also takes as input the original learned model parameters and uses them as a
starting point in the re-training process.
// New Data
HousingData[] housingData = new HousingData[]
{
new HousingData
{
Size = 850f,
HistoricalPrices = new float[] { 150000f,175000f,210000f },
CurrentPrice = 205000f
},
new HousingData
{
Size = 900f,
HistoricalPrices = new float[] { 155000f, 190000f, 220000f },
CurrentPrice = 210000f
},
new HousingData
{
Size = 550f,
HistoricalPrices = new float[] { 99000f, 98000f, 130000f },
CurrentPrice = 180000f
}
};
// Preprocess Data
IDataView transformedNewData = dataPrepPipeline.Transform(newData);
// Retrain model
RegressionPredictionTransformer<LinearRegressionModelParameters> retrainedModel =
mlContext.Regression.Trainers.OnlineGradientDescent()
.Fit(transformedNewData, originalModelParameters);
The table below shows what the output might look like.
Learn how to deploy a pre-trained ML.NET machine learning model for predictions over HTTP through an Azure
Functions serverless environment.
NOTE
This sample runs a preview version of the PredictionEnginePool service.
Prerequisites
Visual Studio 2019 or later or Visual Studio 2017 version 15.6 or later with the ".NET Core cross-platform
development" and "Azure development" workloads installed.
Azure Functions Tools
PowerShell
Pre-trained model. Use the ML.NET Sentiment Analysis tutorial to build your own model or download this
pre-trained sentiment analysis machine learning model
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Extensions.ML;
using SentimentAnalysisFunctionsApp.DataModels;
By default, the AnalyzeSentiment class is static . Make sure to remove the static keyword from the
class definition.
public class AnalyzeSentiment
{
using Microsoft.ML.Data;
Remove the existing class definition and add the following code to the SentimentData.cs file:
[LoadColumn(1)]
[ColumnName("Label")]
public bool Sentiment;
}
4. In Solution Explorer, right-click the DataModels directory, and then select Add > New Item .
5. In the Add New Item dialog box, select Class and change the Name field to SentimentPrediction.cs.
Then, select the Add button. The SentimentPrediction.cs file opens in the code editor. Add the following
using statement to the top of SentimentPrediction.cs:
using Microsoft.ML.Data;
Remove the existing class definition and add the following code to the SentimentPrediction.cs file:
[ColumnName("PredictedLabel")]
public bool Prediction { get; set; }
SentimentPrediction inherits from SentimentData which provides access to the original data in the
SentimentText property as well as the output generated by the model.
The following link provides more information if you want to learn more about dependency injection.
1. In Solution Explorer , right-click the project, and then select Add > New Item .
2. In the Add New Item dialog box, select Class and change the Name field to Startup.cs. Then, select the
Add button.
3. Add the following using statements to the top of Startup.cs:
using System;
using System.IO;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.ML;
using SentimentAnalysisFunctionsApp;
using SentimentAnalysisFunctionsApp.DataModels;
4. Remove the existing code below the using statements and add the following code:
[assembly: FunctionsStartup(typeof(Startup))]
namespace SentimentAnalysisFunctionsApp
{
public class Startup : FunctionsStartup
{
}
}
5. Define variables to store the environment the app is running in and the file path where the model is
located inside the Startup class
6. Below that, create a constructor to set the values of the _environment and _modelPath variables. When
the application is running locally, the default environment is Development.
public Startup()
{
_environment = Environment.GetEnvironmentVariable("AZURE_FUNCTIONS_ENVIRONMENT");
if (_environment == "Development")
{
_modelPath = Path.Combine("MLModels", "sentiment_model.zip");
}
else
{
string deploymentPath = @"D:\home\site\wwwroot\";
_modelPath = Path.Combine(deploymentPath, "MLModels", "sentiment_model.zip");
}
}
7. Then, add a new method called Configure to register the PredictionEnginePool service below the
constructor.
At a high level, this code initializes the objects and services automatically for later use when requested by the
application instead of having to manually do it.
Machine learning models are not static. As new training data becomes available, the model is retrained and
redeployed. One way to get the latest version of the model into your application is to redeploy the entire
application. However, this introduces application downtime. The PredictionEnginePool service provides a
mechanism to reload an updated model without taking your application down.
Set the watchForChanges parameter to true , and the PredictionEnginePool starts a FileSystemWatcher that
listens to the file system change notifications and raises events when there is a change to the file. This prompts
the PredictionEnginePool to automatically reload the model.
The model is identified by the modelName parameter so that more than one model per application can be
reloaded upon change.
TIP
Alternatively, you can use the FromUri method when working with models stored remotely. Rather than watching for file
changed events, FromUri polls the remote location for changes. The polling interval defaults to 5 minutes. You can
increase or decrease the polling interval based on your application's requirements. In the code sample below, the
PredictionEnginePool polls the model stored at the specified URI every minute.
builder.Services.AddPredictionEnginePool<SentimentData, SentimentPrediction>()
.FromUri(
modelName: "SentimentAnalysisModel",
uri:"https://github.com/dotnet/samples/raw/master/machine-
learning/models/sentimentanalysis/sentiment_model.zip",
period: TimeSpan.FromMinutes(1));
This code assigns the PredictionEnginePool by passing it to the function's constructor which you get via
dependency injection.
[FunctionName("AnalyzeSentiment")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
//Make Prediction
SentimentPrediction prediction = _predictionEnginePool.Predict(modelName: "SentimentAnalysisModel",
example: data);
//Return Prediction
return (ActionResult)new OkObjectResult(sentiment);
}
When the Run method executes, the incoming data from the HTTP request is deserialized and used as input for
the PredictionEnginePool . The Predict method is then called to make predictions using the
SentimentAnalysisModel registered in the Startup class and returns the results back to the user if successful.
Test locally
Now that everything is set up, it's time to test the application:
1. Run the application
2. Open PowerShell and enter the code into the prompt where PORT is the port your application is running
on. Typically the port is 7071.
Negative
Congratulations! You have successfully served your model to make predictions over the internet using an Azure
Function.
Next Steps
Deploy to Azure
Deploy a model in an ASP.NET Core Web API
11/2/2020 • 6 minutes to read • Edit Online
Learn how to serve a pre-trained ML.NET machine learning model on the web using an ASP.NET Core Web API.
Serving a model over a web API enables predictions via standard HTTP methods.
Prerequisites
Visual Studio 2019 or later or Visual Studio 2017 version 15.6 or later with the ".NET Core cross-platform
development" workload installed.
PowerShell.
Pre-trained model. Use the ML.NET Sentiment Analysis tutorial to build your own model or download this
pre-trained sentiment analysis machine learning model
using Microsoft.ML.Data;
Remove the existing class definition and add the following code to the SentimentData.cs file:
[LoadColumn(1)]
[ColumnName("Label")]
public bool Sentiment;
}
4. In Solution Explorer, right-click the DataModels directory, and then select Add > New Item .
5. In the Add New Item dialog box, select Class and change the Name field to SentimentPrediction.cs.
Then, select the Add button. The SentimentPrediction.cs file opens in the code editor. Add the following
using statement to the top of SentimentPrediction.cs:
using Microsoft.ML.Data;
Remove the existing class definition and add the following code to the SentimentPrediction.cs file:
[ColumnName("PredictedLabel")]
public bool Prediction { get; set; }
SentimentPrediction inherits from SentimentData . This makes it easier to see the original data in the
SentimentText property along with the output generated by the model.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.ML;
using SentimentAnalysisWebAPI.DataModels;
services.AddPredictionEnginePool<SentimentData, SentimentPrediction>()
.FromFile(modelName: "SentimentAnalysisModel", filePath:"MLModels/sentiment_model.zip",
watchForChanges: true);
At a high level, this code initializes the objects and services automatically for later use when requested by the
application instead of having to manually do it.
Machine learning models are not static. As new training data becomes available, the model is retrained and
redeployed. One way to get the latest version of the model into your application is to redeploy the entire
application. However, this introduces application downtime. The PredictionEnginePool service provides a
mechanism to reload an updated model without taking your application down.
Set the watchForChanges parameter to true , and the PredictionEnginePool starts a FileSystemWatcher that
listens to the file system change notifications and raises events when there is a change to the file. This prompts
the PredictionEnginePool to automatically reload the model.
The model is identified by the modelName parameter so that more than one model per application can be
reloaded upon change.
TIP
Alternatively, you can use the FromUri method when working with models stored remotely. Rather than watching for file
changed events, FromUri polls the remote location for changes. The polling interval defaults to 5 minutes. You can
increase or decrease the polling interval based on your application's requirements. In the code sample below, the
PredictionEnginePool polls the model stored at the specified URI every minute.
services.AddPredictionEnginePool<SentimentData, SentimentPrediction>()
.FromUri(
modelName: "SentimentAnalysisModel",
uri:"https://github.com/dotnet/samples/raw/master/machine-
learning/models/sentimentanalysis/sentiment_model.zip",
period: TimeSpan.FromMinutes(1));
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.ML;
using SentimentAnalysisWebAPI.DataModels;
Remove the existing class definition and add the following code to the PredictController.cs file:
public PredictController(PredictionEnginePool<SentimentData,SentimentPrediction>
predictionEnginePool)
{
_predictionEnginePool = predictionEnginePool;
}
[HttpPost]
public ActionResult<string> Post([FromBody] SentimentData input)
{
if(!ModelState.IsValid)
{
return BadRequest();
}
return Ok(sentiment);
}
}
This code assigns the PredictionEnginePool by passing it to the controller's constructor which you get via
dependency injection. Then, the Predict controller's Post method uses the PredictionEnginePool to make
predictions using the SentimentAnalysisModel registered in the Startup class and returns the results back to the
user if successful.
Negative
Congratulations! You have successfully served your model to make predictions over the internet using an
ASP.NET Core Web API.
Next Steps
Deploy to Azure
The ML.NET CLI command reference
1/25/2021 • 8 minutes to read • Edit Online
The classification , regression , and recommendation commands are the main commands provided by the
ML.NET CLI tool. These commands allow you to generate good quality ML.NET models for classification,
regression, and recommendation models using automated machine learning (AutoML) as well as the example
C# code to run/score that model. In addition, the C# code to train the model is generated for you to research the
algorithm and settings of the model.
NOTE
This topic refers to ML.NET CLI and ML.NET AutoML, which are currently in Preview, and material may be subject to
change.
Overview
Example usage:
The mlnet ML task commands ( classification , regression , and recommendation ) generate the following
assets:
A serialized model .zip ("best model") ready to use.
C# code to run/score that generated model.
C# code with the training code used to generate that model.
The first two assets can directly be used in your end-user apps (ASP.NET Core web app, services, desktop app
and more) to make predictions with the model.
The third asset, the training code, shows you what ML.NET API code was used by the CLI to train the generated
model, so you can investigate the specific algorithm and settings of the model.
Examples
The simplest CLI command for a classification problem (AutoML infers most of the configuration from the
provided data):
Create and train a classification model with a train dataset, a test dataset, and further customization explicit
arguments:
mlnet classification --dataset "/MyDataSets/Population-Training.csv" --test-dataset "/MyDataSets/Population-
Test.csv" --label-col "InsuranceRisk" --cache on --train-time 600
Command options
The mlnet ML task commands ( classification , regression , and recommendation ) train multiple models based
on the provided dataset and ML.NET CLI options. These commands also select the best model, save the model as
a serialized .zip file, and generate related C# code for scoring and training.
Classification options
Running mlnet classification will train a classification model. Choose this command if you want an ML Model
to categorize data into 2 or more classes (e.g. sentiment analysis).
mlnet classification
--cache <option>
--ignore-cols <cols>
--log-file-path <path>
--name <name>
--test-dataset <path>
--validation-dataset <path>
Regression options
Running mlnet regression will train a regression model. Choose this command if you want an ML Model to
predict a numeric value (e.g. price prediction).
mlnet regression
--cache <option>
--ignore-cols <cols>
--log-file-path <path>
--name <name>
--test-dataset <path>
--validation-dataset <path>
Recommendation options
Running mlnet recommendation will train a recommendation model. Choose this command if you want an ML
Model to recommend items to users based on ratings (e.g. product recommendation).
mlnet recommendation
--cache <option>
--log-file-path <path>
--name <name>
--test-dataset <path>
--validation-dataset <path>
Dataset
--dataset | -d (string)
This argument provides the filepath to either one of the following options:
A: The whole dataset file: If using this option and the user is not providing --test-dataset and
--validation-dataset , then cross-validation (k-fold, etc.) or automated data split approaches will be used
internally for validating the model. In that case, the user will just need to provide the dataset filepath.
B: The training dataset file: If the user is also providing datasets for model validation (using
--test-dataset and optionally --validation-dataset ), then the --dataset argument means to only have
the "training dataset". For example, when using an 80% - 20% approach to validate the quality of the
model and to obtain accuracy metrics, the "training dataset" will have 80% of the data and the "test
dataset" would have 20% of the data.
Test dataset
--test-dataset | -t (string)
File path pointing to the test dataset file, for example when using an 80% - 20% approach when making regular
validations to obtain accuracy metrics.
If using --test-dataset , then --dataset is also required.
The --test-dataset argument is optional unless the --validation-dataset is used. In that case, the user must use
the three arguments.
Validation dataset
--validation-dataset | -v (string)
File path pointing to the validation dataset file. The validation dataset is optional, in any case.
If using a validation dataset , the behavior should be:
The test-dataset and --dataset arguments are also required.
The validation-dataset dataset is used to estimate prediction error for model selection.
The test-dataset is used for assessment of the generalization error of the final chosen model. Ideally,
the test set should be kept in a “vault,” and be brought out only at the end of the data analysis.
Basically, when using a validation dataset plus the test dataset , the validation phase is split into two parts:
1. In the first part, you just look at your models and select the best performing approach using the validation
data (=validation)
2. Then you estimate the accuracy of the selected approach (=test).
Hence, the separation of data could be 80/10/10 or 75/15/10. For example:
training-dataset file should have 75% of the data.
validation-dataset file should have 15% of the data.
test-dataset file should have 10% of the data.
In any case, those percentages will be decided by the user using the CLI who will provide the files already split.
Label column
--label-col (int or string)
With this argument, a specific objective/target column (the variable that you want to predict) can be specified by
using the column's name set in the dataset's header or the column's numeric index in the dataset's file (the
column index values start at 0).
This argument is used for classification and regression problems.
Item column
--item-col (int or string)
The item column has the list of items that users rate (items are recommended to users). This column can be
specified by using the column's name set in the dataset's header or the column's numeric index in the dataset's
file (the column index values start at 0).
This argument is used only for the recommendation task.
Rating column
--rating-col (int or string)
The rating column has the list of ratings that are given to items by users. This column can be specified by using
the column's name set in the dataset's header or the column's numeric index in the dataset's file (the column
index values start at 0).
This argument is used only for the recommendation task.
User column
--user-col (int or string)
The user column has the list of users that give ratings to items. This column can be specified by using the
column's name set in the dataset's header or the column's numeric index in the dataset's file (the column index
values start at 0).
This argument is used only for the recommendation task.
Ignore columns
--ignore-columns (string)
With this argument, you can ignore existing columns in the dataset file so they are not loaded and used by the
training processes.
Specify the columns names that you want to ignore. Use ', ' (comma with space) or ' ' (space) to separate
multiple column names. You can use quotes for column names containing whitespace (e.g. "logged in").
Example:
--ignore-columns email, address, id, logged_in
Has header
--has-header (bool)
Specify if the dataset file(s) have a header row. Possible values are:
true
false
The ML.NET CLI will try to detect this property if this argument is not specified by the user.
Train time
--train-time (string)
By default, the maximum exploration / train time is 30 minutes.
This argument sets the maximum time (in seconds) for the process to explore multiple trainers and
configurations. The configured time may be exceeded if the provided time is too short (say 2 seconds) for a
single iteration. In this case, the actual time is the required time to produce one model configuration in a single
iteration.
The needed time for iterations can vary depending on the size of the dataset.
Cache
--cache (string)
If you use caching, the whole training dataset will be loaded in-memory.
For small and medium datasets, using cache can drastically improve the training performance, meaning the
training time can be shorter than when you don't use cache.
However, for large datasets, loading all the data in memory can impact negatively since you might get out of
memory. When training with large dataset files and not using cache, ML.NET will be streaming chunks of data
from the drive when it needs to load more data while training.
You can specify the following values:
on : Forces cache to be used when training. off : Forces cache not to be used when training. auto : Depending
on AutoML heuristics, the cache will be used or not. Usually, small/medium datasets will use cache and large
datasets won't use cache if you use the auto choice.
If you don't specify the --cache parameter, then the cache auto configuration will be used by default.
Name
--name (string)
The name for the created output project or solution. If no name is specified, the name sample-{mltask} is used.
The ML.NET model file (.ZIP file) will get the same name, as well.
Output path
--output | -o (string)
Root location/folder to place the generated output. The default is the current directory.
Verbosity
--verbosity | -v (string)
Sets the verbosity level of the standard output.
Allowed values are:
q[uiet]
m[inimal] (by default)
diag[nostic] (logging information level)
By default, the CLI tool should show some minimum feedback ( minimal ) when working, such as mentioning
that it is working and if possible how much time is left or what % of the time is completed.
Help
-h |--help
Prints out help for the command with a description for each command's parameter.
See also
How to install the ML.NET CLI tool
Overview of the ML.NET CLI
Tutorial: Analyze sentiment using the ML.NET CLI
Telemetry in ML.NET CLI
ML.NET resources
2/26/2020 • 2 minutes to read • Edit Online
Next Steps
Apply your learning by doing one of the ML.NET ML.NET tutorials.
Machine learning glossary of important terms
1/8/2020 • 7 minutes to read • Edit Online
The following list is a compilation of important machine learning terms that are useful as you build your custom
models in ML.NET.
Accuracy
In classification, accuracy is the number of correctly classified items divided by the total number of items in the
test set. Ranges from 0 (least accurate) to 1 (most accurate). Accuracy is one of evaluation metrics of the model
performance. Consider it in conjunction with precision, recall, and F-score.
Binary classification
A classification case where the label is only one out of two classes. For more information, see the Binary
classification section of the Machine learning tasks topic.
Calibration
Calibration is the process of mapping a raw score onto a class membership, for binary and multiclass
classification. Some ML.NET trainers have a NonCalibrated suffix. These algorithms produce a raw score that
then must be mapped to a class probability.
Catalog
In ML.NET, a catalog is a collection of extension functions, grouped by a common purpose.
For example, each machine learning task (binary classification, regression, ranking etc) has a catalog of available
machine learning algorithms (trainers). The catalog for the binary classification trainers is:
BinaryClassificationCatalog.BinaryClassificationTrainers.
Classification
When the data is used to predict a category, supervised machine learning task is called classification. Binary
classification refers to predicting only two categories (for example, classifying an image as a picture of either a
'cat' or a 'dog'). Multiclass classification refers to predicting multiple categories (for example, when classifying
an image as a picture of a specific breed of dog).
Coefficient of determination
In regression, an evaluation metric that indicates how well data fits a model. Ranges from 0 to 1. A value of 0
means that the data is random or otherwise cannot be fit to the model. A value of 1 means that the model
exactly matches the data. This is often referred to as r2, R 2, or r-squared.
Data
Data is central to any machine learning application. In ML.NET data is represented by IDataView objects. Data
view objects:
are made up of columns and rows
are lazily evaluated, that is they only load data when an operation calls for it
contain a schema that defines the type, format and length of each column
Estimator
A class in ML.NET that implements the IEstimator<TTransformer> interface.
An estimator is a specification of a transformation (both data preparation transformation and machine learning
model training transformation). Estimators can be chained together into a pipeline of transformations. The
parameters of an estimator or pipeline of estimators are learned when Fit is called. The result of Fit is a
Transformer.
Extension method
A .NET method that is part of a class but is defined outside of the class. The first parameter of an extension
method is a static this reference to the class to which the extension method belongs.
Extension methods are used extensively in ML.NET to construct instances of estimators.
Feature
A measurable property of the phenomenon being measured, typically a numeric (double) value. Multiple
features are referred to as a Feature vector and typically stored as double[] . Features define the important
characteristics of the phenomenon being measured. For more information, see the Feature article on Wikipedia.
Feature engineering
Feature engineering is the process that involves defining a set of features and developing software that
produces feature vectors from available phenomenon data, i.e., feature extraction. For more information, see the
Feature engineering article on Wikipedia.
F-score
In classification, an evaluation metric that balances precision and recall.
Hyperparameter
A parameter of a machine learning algorithm. Examples include the number of trees to learn in a decision forest
or the step size in a gradient descent algorithm. Values of Hyperparameters are set before training the model
and govern the process of finding the parameters of the prediction function, for example, the comparison points
in a decision tree or the weights in a linear regression model. For more information, see the Hyperparameter
article on Wikipedia.
Label
The element to be predicted with the machine learning model. For example, the breed of dog or a future stock
price.
Log loss
In classification, an evaluation metric that characterizes the accuracy of a classifier. The smaller log loss is, the
more accurate a classifier is.
Loss function
A loss function is the difference between the training label values and the prediction made by the model. The
parameters of the model are estimated by minimizing the loss function.
Different trainers can be configured with different loss functions.
Model
Traditionally, the parameters for the prediction function. For example, the weights in a linear regression model or
the split points in a decision tree. In ML.NET, a model contains all the information necessary to predict the label
of a domain object (for example, image or text). This means that ML.NET models include the featurization steps
necessary as well as the parameters for the prediction function.
Multiclass classification
A classification case where the label is one out of three or more classes. For more information, see the Multiclass
classification section of the Machine learning tasks topic.
N-gram
A feature extraction scheme for text data: any sequence of N words turns into a feature value.
Normalization
Normalization is the process of scaling floating point data to values between 0 and 1. Many of the training
algorithms used in ML.NET require input feature data to be normalized. ML.NET provides a series of transforms
for normalization
Pipeline
All of the operations needed to fit a model to a data set. A pipeline consists of data import, transformation,
featurization, and learning steps. Once a pipeline is trained, it turns into a model.
Precision
In classification, the precision for a class is the number of items correctly predicted as belonging to that class
divided by the total number of items predicted as belonging to the class.
Recall
In classification, the recall for a class is the number of items correctly predicted as belonging to that class divided
by the total number of items that actually belong to the class.
Regularization
Regularization penalizes a linear model for being too complicated. There are two types of regularization:
$L_1$ regularization zeros weights for insignificant features. The size of the saved model may become
smaller after this type of regularization.
$L_2$ regularization minimizes weight range for insignificant features. This is a more general process and is
less sensitive to outliers.
Regression
A supervised machine learning task where the output is a real value, for example, double. Examples include
predicting stock prices. For more information, see the Regression section of the Machine learning tasks topic.
Scoring
Scoring is the process of applying new data to a trained machine learning model, and generating predictions.
Scoring is also known as inferencing. Depending on the type of model, the score may be a raw value, a
probability, or a category.
Training
The process of identifying a model for a given training data set. For a linear model, this means finding the
weights. For a tree, it involves identifying the split points.
Transformer
An ML.NET class that implements the ITransformer interface.
A transformer transforms one IDataView into another. A transformer is created by training an estimator, or an
estimator pipeline.
Unsupervised machine learning
A subclass of machine learning in which a desired model finds hidden (or latent) structure in data. Examples
include clustering, topic modeling, and dimensionality reduction. For more information, see the Unsupervised
learning article on Wikipedia.
Model Builder Azure Training Resources
11/2/2020 • 3 minutes to read • Edit Online
The following is a guide to help you learn more about resources used to train models in Azure with Model
Builder.
T EM P GP U
M EM O RY : STO RA GE M EM O RY : M A X DATA
SIZ E VC P U GIB ( SSD) GIB GP U GIB DISK S M A X N IC S
Visit the NC-series Linux VM documentation for more details on GPU optimized compute types.
Compute priority
Low-priority: Suited for tasks with shorter execution times. May be impacted by interruptions and lack
of availability. Usually costs less because it takes advantage of surplus capacity in Azure.
Dedicated: Suited for tasks of any duration, but especially long-running jobs. Not impacted by
interruptions or lack of availability. Usually costs more because it reserves a dedicated set of compute
resources in Azure for your tasks.
Training
Training on Azure is only available for the Model Builder image classification scenario. The algorithm used to
train these models is a Deep Neural Network based on the ResNet50 architecture. The training process takes
some time and the amount of time may vary depending on the size of compute selected as well as amount of
data. You can track the progress of your runs by selecting the "Monitor current run in Azure portal" link in Visual
Studio.
Results
Once training is complete, two projects are added to your solution with the following suffixes:
ConsoleApp: A C# .NET Core console application that provides starter code to build the prediction
pipeline and make predictions.
Model: A C# .NET Standard application that contains the data models that define the schema of input and
output model data as well as the following assets:
bestModel.onnx: A serialized version of the model in Open Neural Network Exchange (ONNX) format.
ONNX is an open source format for AI models that supports interoperability between frameworks like
ML.NET, PyTorch and TensorFlow.
bestModelMap.json: A list of categories used when making predictions to map the model output to a
text category.
MLModel.zip: A serialized version of the ML.NET prediction pipeline that uses the serialized version of
the model bestModel.onnx to make predictions and maps outputs using the bestModelMap.json file.
Troubleshooting
Cannot create compute
If an error occurs during Azure Machine Learning compute creation, the compute resource may still exist, in an
errored state. If you try to re-create the compute resource with the same name, the operation fails. To fix this
error, either:
Create the new compute with a different name
Go to the Azure portal, and remove the original compute resource
Telemetry collection by the ML.NET CLI
11/2/2020 • 2 minutes to read • Edit Online
The ML.NET CLI includes a telemetry feature that collects anonymous usage data that is aggregated for use by
Microsoft.
Scope
The mlnet command launches the ML.NET CLI, but the command itself doesn't collect telemetry.
Telemetry isn't enabled when you run the mlnet command with no other command attached. For example:
mlnet
mlnet --help
Telemetry is enabled when you run an ML.NET CLI command, such as mlnet classification .
License
The Microsoft distribution of ML.NET CLI is licensed with the Microsoft Software License Terms: Microsoft .NET
Library. For details on data collection and processing, see the section entitled "Data."
Disclosure
When you first run a ML.NET CLI command such as mlnet classification , the ML.NET CLI tool displays
disclosure text that tells you how to opt out of telemetry. Text may vary slightly depending on the version of the
CLI you're running.
See also
ML.NET CLI reference
Microsoft Software License Terms: Microsoft .NET Library
Privacy at Microsoft
Microsoft Privacy Statement