机器学习的工作流程分为以下几个步骤:

  1. 理解问题
  2. 准备数据
    • 加载数据
    • 提取特征
  3. 构建与训练
    • 训练模型
    • 评估模型
  4. 运行
    • 使用模型

理解问题

本教程需要解决的问题是根据网站内评论的意见采取合适的行动。

可用的训练数据集中,网站评论可能是有毒(toxic)(1)或者无毒(not toxic)(0)两种类型。这种场景下,机器学习中的分类任务最为适合。

分类任务用于区分数据内的类别(category),类型(type)或种类(class)。常见的例子有:

  • 识别情感是正面或是负面
  • 将邮件按照是否为垃圾邮件归类
  • 判定病人的实验室样本是否为癌症
  • 按照客户的偏好进行分类以响应销售活动

分类任务可以是二元又或是多元的。这里面临的是二元分类的问题。

准备数据

首先建立一个控制台应用程序,基于.NET Core。完成搭建后,添加Microsoft.ML类库包。接着在工程下新建名为Data的文件夹。

之后,下载WikiPedia-detox-250-line-data.tsvwikipedia-detox-250-line-test.tsv文件,并将它们放入Data文件夹,值得注意的是,这两个文件的Copy to Output Directory属性需要修改成Copy if newer

加载数据

Program.cs文件的Main方法里加入以下代码:

MLContext mlContext = new MLContext(seed: 0);

_textLoader = mlContext.Data.TextReader(new TextLoader.Arguments()
{
Separator = "tab",
HasHeader = true,
Column = new[]
{
new TextLoader.Column("Label", DataKind.Bool, 0),
new TextLoader.Column("SentimentText", DataKind.Text, 1)
}
});

其目的是通过使用TextLoader类为数据的加载作好准备。

Column属性中构建了两个对象,即对应数据集中的两列数据。不过第一列这里必须使用Label而不是Sentiment

提取特征

新建一个SentimentData.cs文件,其中加入SentimentData类与SentimentPrediction。

public class SentimentData
{
[Column(ordinal: "0", name: "Label")]
public float Sentiment;
[Column(ordinal: "1")]
public string SentimentText;
} public class SentimentPrediction
{
[ColumnName("PredictedLabel")]
public bool Prediction { get; set; } [ColumnName("Probability")]
public float Probability { get; set; } [ColumnName("Score")]
public float Score { get; set; }
}

SentimentData类中的SentimentText为输入数据集的特征,Sentiment则是数据集的标记(label)。

SentimentPrediction类用于模型被训练后的预测。

训练模型

Program类中加入Train方法。首先它会读取训练数据集,接着将特征列中的文本型数据转换为浮点型数组并设定了训练时所使用的决策树二元分类模型。之后,即是实际训练模型。

public static ITransformer Train(MLContext mlContext, string dataPath)
{
IDataView dataView = _textLoader.Read(dataPath);
var pipeline = mlContext.Transforms.Text.FeaturizeText("SentimentText", "Features")
.Append(mlContext.BinaryClassification.Trainers.FastTree(numLeaves: 50, numTrees: 50, minDatapointsInLeaves: 20)); Console.WriteLine("=============== Create and Train the Model ===============");
var model = pipeline.Fit(dataView);
Console.WriteLine("=============== End of training ===============");
Console.WriteLine(); return model;
}

评估模型

加入Evaluate方法。到了这一步,需要读取的是用于测试的数据集,且读取后的数据仍然需要转换成合适的数据类型。

public static void Evaluate(MLContext mlContext, ITransformer model)
{
IDataView dataView = _textLoader.Read(_testDataPath);
Console.WriteLine("=============== Evaluating Model accuracy with Test data===============");
var predictions = model.Transform(dataView); var metrics = mlContext.BinaryClassification.Evaluate(predictions, "Label");
Console.WriteLine();
Console.WriteLine("Model quality metrics evaluation");
Console.WriteLine("--------------------------------");
Console.WriteLine($"Accuracy: {metrics.Accuracy:P2}");
Console.WriteLine($"Auc: {metrics.Auc:P2}");
Console.WriteLine($"F1Score: {metrics.F1Score:P2}");
Console.WriteLine("=============== End of model evaluation ===============");
}

使用模型

训练及评估模型完成后,就可以正式使用它了。这里需要建立一个用于预测的对象(PredictionFunction),其预测方法的输入参数是SentimentData类型,返回结果为SentimentPrediction类型。

private static void Predict(MLContext mlContext, ITransformer model)
{
var predictionFunction = model.MakePredictionFunction<SentimentData, SentimentPrediction>(mlContext);
SentimentData sampleStatement = new SentimentData
{
SentimentText = "This is a very rude movie"
}; var resultprediction = predictionFunction.Predict(sampleStatement); Console.WriteLine();
Console.WriteLine("=============== Prediction Test of model with a single sample and test dataset ==============="); Console.WriteLine();
Console.WriteLine($"Sentiment: {sampleStatement.SentimentText} | Prediction: {(Convert.ToBoolean(resultprediction.Prediction) ? "Toxic" : "Not Toxic")} | Probability: {resultprediction.Probability} ");
Console.WriteLine("=============== End of Predictions ===============");
Console.WriteLine();
}

完整示例代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.ML;
using Microsoft.ML.Core.Data;
using Microsoft.ML.Runtime.Data;
using Microsoft.ML.Transforms.Text; namespace SentimentAnalysis
{
class Program
{
static readonly string _trainDataPath = Path.Combine(Environment.CurrentDirectory, "Data", "wikipedia-detox-250-line-data.tsv");
static readonly string _testDataPath = Path.Combine(Environment.CurrentDirectory, "Data", "wikipedia-detox-250-line-test.tsv");
static readonly string _modelPath = Path.Combine(Environment.CurrentDirectory, "Data", "Model.zip");
static TextLoader _textLoader; static void Main(string[] args)
{
MLContext mlContext = new MLContext(seed: 0); _textLoader = mlContext.Data.TextReader(new TextLoader.Arguments()
{
Separator = "tab",
HasHeader = true,
Column = new[]
{
new TextLoader.Column("Label", DataKind.Bool, 0),
new TextLoader.Column("SentimentText", DataKind.Text, 1)
}
}); var model = Train(mlContext, _trainDataPath); Evaluate(mlContext, model); Predict(mlContext, model); Console.Read();
} public static ITransformer Train(MLContext mlContext, string dataPath)
{
IDataView dataView = _textLoader.Read(dataPath);
var pipeline = mlContext.Transforms.Text.FeaturizeText("SentimentText", "Features")
.Append(mlContext.BinaryClassification.Trainers.FastTree(numLeaves: 50, numTrees: 50, minDatapointsInLeaves: 20)); Console.WriteLine("=============== Create and Train the Model ===============");
var model = pipeline.Fit(dataView);
Console.WriteLine("=============== End of training ===============");
Console.WriteLine(); return model;
} public static void Evaluate(MLContext mlContext, ITransformer model)
{
IDataView dataView = _textLoader.Read(_testDataPath);
Console.WriteLine("=============== Evaluating Model accuracy with Test data===============");
var predictions = model.Transform(dataView); var metrics = mlContext.BinaryClassification.Evaluate(predictions, "Label");
Console.WriteLine();
Console.WriteLine("Model quality metrics evaluation");
Console.WriteLine("--------------------------------");
Console.WriteLine($"Accuracy: {metrics.Accuracy:P2}");
Console.WriteLine($"Auc: {metrics.Auc:P2}");
Console.WriteLine($"F1Score: {metrics.F1Score:P2}");
Console.WriteLine("=============== End of model evaluation ===============");
} private static void Predict(MLContext mlContext, ITransformer model)
{
var predictionFunction = model.MakePredictionFunction<SentimentData, SentimentPrediction>(mlContext);
SentimentData sampleStatement = new SentimentData
{
SentimentText = "This is a very rude movie"
}; var resultprediction = predictionFunction.Predict(sampleStatement); Console.WriteLine();
Console.WriteLine("=============== Prediction Test of model with a single sample and test dataset ==============="); Console.WriteLine();
Console.WriteLine($"Sentiment: {sampleStatement.SentimentText} | Prediction: {(Convert.ToBoolean(resultprediction.Prediction) ? "Toxic" : "Not Toxic")} | Probability: {resultprediction.Probability} ");
Console.WriteLine("=============== End of Predictions ===============");
Console.WriteLine();
}
}
}

程序运行后显示的结果:

=============== Create and Train the Model ===============
=============== End of training =============== =============== Evaluating Model accuracy with Test data=============== Model quality metrics evaluation
--------------------------------
Accuracy: 83.33%
Auc: 98.77%
F1Score: 85.71%
=============== End of model evaluation =============== =============== Prediction Test of model with a single sample and test dataset =============== Sentiment: This is a very rude movie | Prediction: Toxic | Probability: 0.7387648
=============== End of Predictions ===============

可以看到在预测This is a very rude movie(这是一部粗制滥造的电影)这句评论时,模型判定其是有毒的:-)

ML.NET教程之情感分析(二元分类问题)的更多相关文章

  1. LSTM 文本情感分析/序列分类 Keras

    LSTM 文本情感分析/序列分类 Keras 请参考 http://spaces.ac.cn/archives/3414/   neg.xls是这样的 pos.xls是这样的neg=pd.read_e ...

  2. ML.NET 示例:二元分类之用户评论的情绪分析

    写在前面 准备近期将微软的machinelearning-samples翻译成中文,水平有限,如有错漏,请大家多多指正. 如果有朋友对此感兴趣,可以加入我:https://github.com/fei ...

  3. Python爬虫和情感分析简介

    摘要 这篇短文的目的是分享我这几天里从头开始学习Python爬虫技术的经验,并展示对爬取的文本进行情感分析(文本分类)的一些挖掘结果. 不同于其他专注爬虫技术的介绍,这里首先阐述爬取网络数据动机,接着 ...

  4. Python爬取《你好李焕英》豆瓣短评并基于SnowNLP做情感分析

    爬取过程在这里: Python爬取你好李焕英豆瓣短评并利用stylecloud制作更酷炫的词云图 本文基于前文爬取生成的douban.txt,基于SnowNLP做情感分析. 依赖库: 豆瓣镜像比较快: ...

  5. 使用ML.NET实现情感分析[新手篇]

    在发出<.NET Core玩转机器学习>和<使用ML.NET预测纽约出租车费>两文后,相信读者朋友们即使在不明就里的情况下,也能按照内容顺利跑完代码运行出结果,对使用.NET ...

  6. ML.NET 示例:二元分类之信用卡欺诈检测

    写在前面 准备近期将微软的machinelearning-samples翻译成中文,水平有限,如有错漏,请大家多多指正. 如果有朋友对此感兴趣,可以加入我:https://github.com/fei ...

  7. 使用ML.NET实现情感分析[新手篇]后补

    在<使用ML.NET实现情感分析[新手篇]>完成后,有热心的朋友建议说,为何例子不用中文的呢,其实大家是需要知道怎么预处理中文的数据集的.想想确实有道理,于是略微调整一些代码,权作示范. ...

  8. ML.NET 示例:二元分类之垃圾短信检测

    写在前面 准备近期将微软的machinelearning-samples翻译成中文,水平有限,如有错漏,请大家多多指正. 如果有朋友对此感兴趣,可以加入我:https://github.com/fei ...

  9. pyhanlp文本分类与情感分析

    语料库 本文语料库特指文本分类语料库,对应IDataSet接口.而文本分类语料库包含两个概念:文档和类目.一个文档只属于一个类目,一个类目可能含有多个文档.比如搜狗文本分类语料库迷你版.zip,下载前 ...

随机推荐

  1. 从HTML Components的衰落看Web Components的危机 HTML Components的一些特性 JavaScript什么叫端到端组件 自己对Polymer的意见

    http://blog.jobbole.com/77837/ 原文出处: 徐飞(@民工精髓V) 搞前端时间比较长的同学都会知道一个东西,那就是HTC(HTML Components),这个东西名字很现 ...

  2. Kubernetes1.2如何使用iptables

    转:http://blog.csdn.net/horsefoot/article/details/51249161 本次分析的kubernetes版本号:v1.2.1-beta.0. Kubernet ...

  3. Socket网络编程--小小网盘程序(3)

    接上一小节,这次增加另外的两张表,用于记录用户是保存那些文件.增加传上来的文件的文件指纹,使用MD5表示. 两张表如下定义: create table files( fid int, filename ...

  4. Python中的format()函数

    普通格式化方法 (%s%d)生成格式化的字符串,其中s是一个格式化字符串,d是一个十进制数; 格式化字符串包含两部分:普通的字符和转换说明符(见下表), 将使用元组或映射中元素的字符串来替换转换说明符 ...

  5. 【工具】我的Git学习日志

    使用github一段时间,一直使用的是可视化工具,配合公司转用git,提前联系下git的命令. 安装 windows上安装git 从git for windows下载安装包,我下的是Git-2.13. ...

  6. 【iCore4 双核心板_FPGA】例程五:基础逻辑门实验——逻辑门使用

    实验现象: 打开tool-->Netlist viewer-->RTL viewer可观察各个逻辑连接 核心代码: //--------------------module_logic_g ...

  7. Go Revel - Cache(缓存)

    revel在服务器端提供了`cache`库用以低延迟的存储临时数据.它缓存那些需要经常访问数据库但是变化不频繁的数据,也可以实现用户会话的存储. ##有效期 一下三种方法为缓存元素设置过期时间: 1. ...

  8. Java知多少(27)继承的概念与实现

    继承是类与类之间的关系,是一个很简单很直观的概念,与现实世界中的继承(例如儿子继承父亲财产)类似. 继承可以理解为一个类从另一个类获取方法和属性的过程.如果类B继承于类A,那么B就拥有A的方法和属性. ...

  9. Git 目录

    linux通过用户名.密码提交的方式搭建私有git服务端 centos 6.5 6.6 6.7安装gitlab教程(社区版) Git 初始化项目.创建合并分支.回滚等常用方法总结 Git 错误集锦

  10. 嵌入式开发之hi3519---lvds ,mipi,camera sensor,/DVI/HDMI Interface

    http://blog.csdn.net/mao0514/article/details/54015466