65.9K
CodeProject 正在变化。 阅读更多。
Home

介绍 ML.NET – 适用于 .NET 开发人员的机器学习库

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.98/5 (17投票s)

2018 年 11 月 24 日

CPOL

3分钟阅读

viewsIcon

27333

介绍 ML.NET

引言

大多数常见的机器学习 (ML) 库都是用 Python 编写的,对于 .NET 开发人员来说并不容易。 ML.NET 库充当了 ML 库和 .NET 应用程序之间的桥梁。

ML.NET 是一个开源库,可以直接在 .NET 应用程序中使用。 在本文中,我将介绍如何在 Visual Studio 2017(我使用的是 VS 2017 Community)中使用 ML.NET 库。

背景

一个二元分类问题

假设我们有两个点(在二维空间中)组,分别是红色和蓝色,我们将根据该点的坐标 (xy) 预测一个点是属于 Red 组还是 Blue 组。 我们的训练数据可能如下所示:

3 -2 Red
-2 3 Red
-1 -4 Red
2 3 Red
3 4 Red
-1 9 Blue
2 14 Blue
1 17 Blue
3 12 Blue
0 8 Blue

我们有十个点。 每行的前两个值是每个点的坐标 (xy),第三个值是该点所属的组。

因为我们只有两个输出,即 BlueRed,所以我们的问题是二元分类问题。 有很多不同的 ML 技术可以解决二元分类问题,在本文中,我将使用逻辑回归,因为它最简单的 ML 算法。

创建 .NET 应用程序和安装 ML.NET 库

为简单起见,我们将创建一个控制台应用程序 C# (.NET Framework),并将其命名为 MyFirstMLDOTNET。 在“解决方案资源管理器”窗口中,我们还将 *Program.cs* 重命名为 *MyFirstMLDOTNET.cs*

我们可以通过右键单击 MyFirstMLDOTNET 项目并选择“管理 NuGet 程序包”来安装 ML.NET

在 NuGet 窗口中,我们选择“浏览”选项卡,并在“搜索”字段中输入“ML.NET”。 最后,我们选择 Microsoft.ML 并单击“安装”按钮

在“预览更改”中单击“确定”,然后在“许可证接受”中单击“我接受”。 几秒钟后,Visual Studio 将在“输出”窗口中响应一条消息

此时,如果我们尝试运行我们的应用程序,我们可能会收到一条错误消息,如下所示

通过右键单击 MyFirstMLDOTNET 项目并选择“属性”来解决此错误。 在“属性”窗口中,我们选择左侧的“生成”项,并将“任何 CPU”更改为“平台目标”项中的 x64

我们还需要选择 .NET Framework 的 4.7 版本(或更高版本),因为我们会在早期版本中遇到一些错误。 我们可以通过选择左侧的“应用程序”项并在“目标框架”项中选择版本来选择 .NET Framework 的版本。 如果我们没有 4.7 版本(或更高版本),我们可以选择“安装其他框架”,我们将被定向到 Microsoft 页面以下载和安装 .NET Framework 程序包

到目前为止,我们可以尝试再次运行我们的应用程序,并且它已成功。

Using the Code

训练数据

在创建 ML 模型之前,我们必须通过右键单击 MyFirstMLDOTNET 项目并选择“添加 > 新建项”,选择文本文件类型并在“名称”字段中输入 *myMLData.txt* 来创建训练数据文件

单击“添加”按钮。 在 *myMLData.txt* 窗口中,我们输入(或复制以上)训练数据

3 -2 Red
-2 3 Red
-1 -4 Red
2 3 Red
3 4 Red
-1 9 Blue
2 14 Blue
1 17 Blue
3 12 Blue
0 8 Blue

单击“保存”并关闭 *myMLData.txt* 窗口。

数据类

创建训练数据文件后,我们还需要创建数据类。 一个类(名为 myData)定义了训练数据的结构(两个坐标 (xy) 和一个标签 (RedBlue))

  public class myData
        {
            [Column(ordinal: "0", name: "XCoord")]
            public float x;
            [Column(ordinal: "1", name: "YCoord")]
            public float y;
            [Column(ordinal: "2", name: "Label")]
            public string Label;
        }

并且一个类(名为 myPrediction)保存预测信息

public class myPrediction
  {
            [ColumnName("PredictedLabel")]
            public string PredictedLabels;
  }

创建和训练 ML 模型

我们可以创建 ML 模型并对其进行训练

//creating a ML model
var pipeline = new LearningPipeline();
// loading the training data
string dataPath = "..\\..\\myMLData.txt";
pipeline.Add(new TextLoader(dataPath).CreateFrom<myData>(separator: ' '));
//convert string (Red or Blue) to number (0 or 1)
pipeline.Add(new Dictionarizer("Label"));
//combining the two predictor variables (XCoord and YCoord)
//into an aggregate (Features)
pipeline.Add(new ColumnConcatenator("Features", "XCoord", "YCoord"));
//using the Logistic Regression technique for a binary classification problem
pipeline.Add(new Logistic​Regression​Binary​Classifier());
pipeline.Add(new PredictedLabelColumnOriginalValueConverter()
       { PredictedLabelColumn = "PredictedLabel" });
//training the ML model
Console.WriteLine("\nStarting training \n");
var model = pipeline.Train<myData, myPrediction>();

评估模型

我们可以按如下方式评估我们的 ML 模型

var testData = new TextLoader(dataPath).CreateFrom<myData>(separator: ' ');
var evaluator = new BinaryClassificationEvaluator();
var metrics = evaluator.Evaluate(model, testData);
double acc = metrics.Accuracy * 100;
Console.WriteLine("Model accuracy = " + acc.ToString("F2") + "%");

测试模型

最后,我们可以使用一个新点来测试我们的模型

myData newPoint = new myData(){ x = 5f, y = -7f};
myPrediction prediction = model.Predict(newPoint);
string result = prediction.PredictedLabels;
Console.WriteLine("Prediction = " + result);

我们在 *MyFirstMLDOTNET.cs* 文件中的所有代码

using System;
using Microsoft.ML.Runtime.Api;
using System.Threading.Tasks;
using Microsoft.ML.Legacy;
using Microsoft.ML.Legacy.Data;
using Microsoft.ML.Legacy.Transforms;
using Microsoft.ML.Legacy.Trainers;
using Microsoft.ML.Legacy.Models;

namespace MyFirstMLDOTNET
{
    class MyFirstMLDOTNET
    {
        public class myData
        {
            [Column(ordinal: "0", name: "XCoord")]
            public float x;
            [Column(ordinal: "1", name: "YCoord")]
            public float y;
            [Column(ordinal: "2", name: "Label")]
            public string Label;
        }
        public class myPrediction
        {
            [ColumnName("PredictedLabel")]
            public string PredictedLabels;
        }

        static void Main(string[] args)
        {
            //creating a ML model
            var pipeline = new LearningPipeline();
            // loading the training data
            string dataPath = "..\\..\\myMLData.txt";
            pipeline.Add(new TextLoader(dataPath).CreateFrom<myData>(separator: ' '));
            //convert string (Red or Blue) to number (0 or 1)
            pipeline.Add(new Dictionarizer("Label"));
            //combining the two predictor variables (XCoord and YCoord)
            //into an aggregate (Features)
            pipeline.Add(new ColumnConcatenator("Features", "XCoord", "YCoord"));
            //using Logistic Regression technique for a binary classification problem
            pipeline.Add(new Logistic​Regression​Binary​Classifier());
            pipeline.Add(new PredictedLabelColumnOriginalValueConverter()
            { PredictedLabelColumn = "PredictedLabel" });
            //training and saving the ML model
            Console.WriteLine("\nStarting training \n");
            var model = pipeline.Train<myData, myPrediction>();
            //Evaluating the Model
            var testData = new TextLoader(dataPath).CreateFrom<myData>(separator: ' ');
            var evaluator = new BinaryClassificationEvaluator();
            var metrics = evaluator.Evaluate(model, testData);
            double acc = metrics.Accuracy * 100;
            Console.WriteLine("Model accuracy = " + acc.ToString("F2") + "%");
            //Predicting a new point (5,-7)
            myData newPoint = new myData()
            { x = 5f, y = -7f};
            myPrediction prediction = model.Predict(newPoint);
            string result = prediction.PredictedLabels;
            Console.WriteLine("Prediction = " + result);
            Console.WriteLine("\nEnd ML.NET demo");
            Console.ReadLine();
        }
    }
}

运行我们的应用程序并获得结果,结果可能如下所示

关注点

在本文中,我只是简单介绍了 ML.NET – 适用于 .NET 开发人员的机器学习库。 ML.NET 仍在开发中,您可以通过 此处 的教程了解有关此库的更多信息。

历史

  • 2018 年 11 月 24 日:初始版本
© . All rights reserved.