博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
介绍ML.NET——面向.NET开发人员的机器学习库
阅读量:3525 次
发布时间:2019-05-20

本文共 5987 字,大约阅读时间需要 19 分钟。

目录


介绍

大多数常见的机器学习(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 Red2 3 Red3 4 Red-1 9 Blue2 14 Blue1 17 Blue3 12 Blue0 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 Red2 3 Red3 4 Red-1 9 Blue2 14 Blue1 17 Blue3 12 Blue0 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 modelvar pipeline = new LearningPipeline();// loading the training datastring dataPath = "..\\..\\myMLData.txt";pipeline.Add(new TextLoader(dataPath).CreateFrom
(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 problempipeline.Add(new Logistic​Regression​Binary​Classifier());pipeline.Add(new PredictedLabelColumnOriginalValueConverter() { PredictedLabelColumn = "PredictedLabel" });//training the ML modelConsole.WriteLine("\nStarting training \n");var model = pipeline.Train
();

评估模型

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

var testData = new TextLoader(dataPath).CreateFrom
(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
(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
(); //Evaluating the Model var testData = new TextLoader(dataPath).CreateFrom
(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仍在开发中,您可以通过教程了解有关此库的更多信息。

 

原文地址:

转载地址:http://uzzhj.baihongyu.com/

你可能感兴趣的文章
Cache模拟器的实现
查看>>
实验2:MIPS指令系统和MIPS体系结构
查看>>
设计模式七大原则
查看>>
手写 | spring事务
查看>>
AndroidStudio Gradle手动下载
查看>>
SpringBoot入门(二)场景启动器
查看>>
SpringBoot入门--自动配置
查看>>
springboot读取配置文件 例:读取配置文件的优先顺序;在主配置文件中激活其他配置文件;加载非主配置文件
查看>>
自动配置原理
查看>>
TCP协议
查看>>
关于Linux系统使用遇到的问题-1:vi 打开只读(readonly)文件如何退出保存?
查看>>
redis 持久化详解,RDB和AOF是什么?他们优缺点是什么?运行流程是什么?
查看>>
spring注解版(一)
查看>>
SpringBoot中访问控制层(controller)得不到Json数据
查看>>
react项目报出警告Warning: Cannot update during an existing state transition (such as within `render`).
查看>>
BFC(Block Formatting Context)
查看>>
什么是作用域,什么是闭包,什么是作用域链
查看>>
惰性求值,面向对象
查看>>
lodash源码分析之baseSlice()函数
查看>>
数据结构之列表
查看>>