介绍ML.NET——面向.NET开发人员的机器学习库

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mzl87/article/details/84995397

目录

介绍

背景

二元分类问题

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

使用代码

培训数据

数据类

创建和训练ML模型

评估模型

测试模型

兴趣点


介绍

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

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

背景

二元分类问题

假设我们有两个点(在二维空间中)是红色和蓝色的组,我们将根据此点的坐标(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),第三个值是该点所属的组。

因为我们只有两个输出,Blue或者Red,我们的问题是二元分类问题。解决二元分类问题有很多不同的ML技术,在本文中,我将使用Logistic Regression,因为它是最简单的ML算法。

创建.NET应用程序并安装ML.NET

为简单起见,我们将创建一个Console Application C#(.NET Framework)并命名它为MyFirstMLDOTNET。在Solution Explorer窗口中,我们还将Program.cs重命名为MyFirstMLDOTNET.cs

https://www.codeproject.com/KB/AI/1268051/1.png

我们可以通过右键单击MyFirstMLDOTNET项目并选择Manage NuGet Packages 来安装ML.NET 

https://www.codeproject.com/KB/AI/1268051/2.png

NuGet窗口中,我们选择Browse选项卡并在Search字段中输入ML.NET '。最后,我们选择Microsoft.ML并单击Install按钮:

https://www.codeproject.com/KB/AI/1268051/3.png

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

https://www.codeproject.com/KB/AI/1268051/4.png

此时,如果我们尝试运行我们的应用程序,我们可以收到如下错误消息:

https://www.codeproject.com/KB/AI/1268051/5.png

通过右键单击MyFirstMLDOTNET项目并选择属性” 来解决此错误。在Properties窗口中,我们选择左侧的Built选项,并在Plaform目标选项中将Any CPU更改为x64

https://www.codeproject.com/KB/AI/1268051/6.png

我们还需要选择.NET Framework4.7版本(或更高版本),因为我们将遇到早期版本的一些错误。我们可以通过选择左侧的Application项并在Target framework项中选择版本来选择.NET Framework的版本。如果我们没有4.7版本(或更高版本),我们可以选择Install other frameworks,我们将被引导到Microsoft页面下载并安装.NET Framework包:

https://www.codeproject.com/KB/AI/1268051/7.png

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

使用代码

培训数据

在创建ML模型之前,我们必须通过右键单击MyFirstMLDOTNET项目并选择Add> New Item 来创建训练数据文件,选择Text File类型并在Name字段中输入myMLData.txt

https://www.codeproject.com/KB/AI/1268051/8.png

单击“ 添加按钮。在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();
        }
    }
}

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

https://www.codeproject.com/KB/AI/1268051/9.png

兴趣点

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

 

原文地址:https://www.codeproject.com/Articles/1268051/Introducing-the-ML-NET-A-Machine-Learning-Library

猜你喜欢

转载自blog.csdn.net/mzl87/article/details/84995397