使用ML.NET实现情感分析[新手篇]后补
在《使用ML.NET实现情感分析[新手篇]》完成后,有热心的朋友建议说,为何例子不用中文的呢,其实大家是需要知道怎么预处理中文的数据集的。想想确实有道理,于是略微调整一些代码,权作示范。
首先,我们需要一个好用的分词库,所以使用NuGet添加对JiebaNet.Analyser包的引用,这是一个支持.NET Core的版本。

然后,训练和验证用的数据集找一些使用中文的内容,并且确认有正确的标注,当然是要越多越好。内容类似如下:
最差的是三文鱼生鱼片。 0
我在这里吃了一顿非常可口的早餐。 1
这是拉斯维加斯最好的食物之一。 1
但即使是天才也无法挽救这一点。 0
我认为汤姆汉克斯是一位出色的演员。 1
...
增加一个切词的函数:
public static void Segment(string source, string result)
{
var segmenter = new JiebaSegmenter();
using (var reader = new StreamReader(source))
{
using (var writer = new StreamWriter(result))
{
while (true)
{
var line = reader.ReadLine();
if (string.IsNullOrWhiteSpace(line))
break;
var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != ) continue;
var segments = segmenter.Cut(parts[]);
writer.WriteLine("{0}\t{1}", string.Join(" ", segments), parts[]);
}
}
}
}
原有的文件路径要的调整为:
const string _dataPath = @".\data\sentiment labelled sentences\imdb_labelled.txt";
const string _testDataPath = @".\data\sentiment labelled sentences\yelp_labelled.txt";
const string _dataTrainPath = @".\data\sentiment labelled sentences\imdb_labelled_result.txt";
const string _testTargetPath = @".\data\sentiment labelled sentences\yelp_labelled_result.txt";
在Main函数的地方增加调用:
Segment(_dataPath, _dataTrainPath);
Segment(_testDataPath, _testTargetPath);
预测用的数据修改为:
IEnumerable<SentimentData> sentiments = new[]
{
new SentimentData
{
SentimentText = "今天的任务并不轻松",
Sentiment =
},
new SentimentData
{
SentimentText = "我非常想见到你",
Sentiment =
},
new SentimentData
{
SentimentText = "实在是我没有看清楚",
Sentiment =
}
};
一切就绪,运行结果如下:

看上去也不坏对么? :)
不久前也看到.NET Blog发了一篇关于ML.NET的文章《Introducing ML.NET: Cross-platform, Proven and Open Source Machine Learning Framework》,我重点摘一下关于路线图方向的内容。
The Road Ahead
There are many capabilities we aspire to add to ML.NET, but we would love to understand what will best fit your needs. The current areas we are exploring are:
- Additional ML Tasks and Scenarios
- Deep Learning with TensorFlow & CNTK
- ONNX support
- Scale-out on Azure
- Better GUI to simplify ML tasks
- Integration with VS Tools for AI
- Language Innovation for .NET
可以看到,随着ONNX的支持,更多的机器学习框架如:TensorFlow、CNTK,甚至PyTorch都能共享模型了,加上不断新增的场景支持,ML.NET将越来越实用,对已有其他语言开发的机器学习服务也能平滑地过渡到.NET Core来集成,值得期待!
按惯例最后放出项目结构和完整的代码。

using System;
using Microsoft.ML.Models;
using Microsoft.ML.Runtime;
using Microsoft.ML.Runtime.Api;
using Microsoft.ML.Trainers;
using Microsoft.ML.Transforms;
using System.Collections.Generic;
using System.Linq;
using Microsoft.ML;
using JiebaNet.Segmenter;
using System.IO; namespace SentimentAnalysis
{
class Program
{
const string _dataPath = @".\data\sentiment labelled sentences\imdb_labelled.txt";
const string _testDataPath = @".\data\sentiment labelled sentences\yelp_labelled.txt";
const string _dataTrainPath = @".\data\sentiment labelled sentences\imdb_labelled_result.txt";
const string _testTargetPath = @".\data\sentiment labelled sentences\yelp_labelled_result.txt"; public class SentimentData
{
[Column(ordinal: "")]
public string SentimentText;
[Column(ordinal: "", name: "Label")]
public float Sentiment;
} public class SentimentPrediction
{
[ColumnName("PredictedLabel")]
public bool Sentiment;
} public static PredictionModel<SentimentData, SentimentPrediction> Train()
{
var pipeline = new LearningPipeline();
pipeline.Add(new TextLoader<SentimentData>(_dataTrainPath, useHeader: false, separator: "tab"));
pipeline.Add(new TextFeaturizer("Features", "SentimentText")); var featureSelector = new FeatureSelectorByCount() { Column = new[] { "Features" } };
pipeline.Add(featureSelector); pipeline.Add(new FastTreeBinaryClassifier() { NumLeaves = , NumTrees = , MinDocumentsInLeafs = }); PredictionModel<SentimentData, SentimentPrediction> model = pipeline.Train<SentimentData, SentimentPrediction>();
return model;
} public static void Evaluate(PredictionModel<SentimentData, SentimentPrediction> model)
{
var testData = new TextLoader<SentimentData>(_testTargetPath, useHeader: false, separator: "tab");
var evaluator = new BinaryClassificationEvaluator();
BinaryClassificationMetrics metrics = evaluator.Evaluate(model, testData);
Console.WriteLine();
Console.WriteLine("PredictionModel quality metrics evaluation");
Console.WriteLine("------------------------------------------");
Console.WriteLine($"Accuracy: {metrics.Accuracy:P2}");
Console.WriteLine($"Auc: {metrics.Auc:P2}");
Console.WriteLine($"F1Score: {metrics.F1Score:P2}");
} public static void Predict(PredictionModel<SentimentData, SentimentPrediction> model)
{
IEnumerable<SentimentData> sentiments = new[]
{
new SentimentData
{
SentimentText = "今天的任务并不轻松",
Sentiment =
},
new SentimentData
{
SentimentText = "我非常想见到你",
Sentiment =
},
new SentimentData
{
SentimentText = "实在是我没有看清楚",
Sentiment =
}
}; var segmenter = new JiebaSegmenter();
foreach (var item in sentiments)
{
item.SentimentText = string.Join(" ", segmenter.Cut(item.SentimentText));
} IEnumerable<SentimentPrediction> predictions = model.Predict(sentiments);
Console.WriteLine();
Console.WriteLine("Sentiment Predictions");
Console.WriteLine("---------------------"); var sentimentsAndPredictions = sentiments.Zip(predictions, (sentiment, prediction) => (sentiment, prediction));
foreach (var item in sentimentsAndPredictions)
{
Console.WriteLine($"Sentiment: {item.sentiment.SentimentText.Replace(" ", string.Empty)} | Prediction: {(item.prediction.Sentiment ? "Positive" : "Negative")}");
}
Console.WriteLine();
} public static void Segment(string source, string result)
{
var segmenter = new JiebaSegmenter();
using (var reader = new StreamReader(source))
{
using (var writer = new StreamWriter(result))
{
while (true)
{
var line = reader.ReadLine();
if (string.IsNullOrWhiteSpace(line))
break;
var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != ) continue;
var segments = segmenter.Cut(parts[]);
writer.WriteLine("{0}\t{1}", string.Join(" ", segments), parts[]);
}
}
}
} static void Main(string[] args)
{
Segment(_dataPath, _dataTrainPath);
Segment(_testDataPath, _testTargetPath);
var model = Train();
Evaluate(model);
Predict(model);
}
}
}
使用ML.NET实现情感分析[新手篇]后补的更多相关文章
- 使用ML.NET实现情感分析[新手篇]
在发出<.NET Core玩转机器学习>和<使用ML.NET预测纽约出租车费>两文后,相信读者朋友们即使在不明就里的情况下,也能按照内容顺利跑完代码运行出结果,对使用.NET ...
- INTERSPEECH2020 语音情感分析论文之我见
摘要:本文为大家带来InterSpeech2020 语音情感分析25篇论文中的其中8篇的总结. 本文分享自华为云社区<INTERSPEECH2020 语音情感分析论文总结一>,原文作者:T ...
- Python爬虫和情感分析简介
摘要 这篇短文的目的是分享我这几天里从头开始学习Python爬虫技术的经验,并展示对爬取的文本进行情感分析(文本分类)的一些挖掘结果. 不同于其他专注爬虫技术的介绍,这里首先阐述爬取网络数据动机,接着 ...
- 在Keras中用Bert进行情感分析
之前在BERT实战——基于Keras一文中介绍了两个库 keras_bert 和 bert4keras 但是由于 bert4keras 处于开发阶段,有些函数名称和位置等等发生了变化,那篇文章只用了 ...
- 如何用KNIME进行情感分析
Customer Intelligence Social Media Finance Credit Scoring Manufacturing Pharma / Health Care Retail ...
- 朴素贝叶斯算法下的情感分析——C#编程实现
这篇文章做了什么 朴素贝叶斯算法是机器学习中非常重要的分类算法,用途十分广泛,如垃圾邮件处理等.而情感分析(Sentiment Analysis)是自然语言处理(Natural Language Pr ...
- Stanford NLP学习笔记:7. 情感分析(Sentiment)
1. 什么是情感分析(别名:观点提取,主题分析,情感挖掘...) 应用: 1)正面VS负面的影评(影片分类问题) 2)产品/品牌评价: Google产品搜索 3)twitter情感预测股票市场行情/消 ...
- SA: 情感分析资源(Corpus、Dictionary)
先主要摘自一篇中文Survey,http://wenku.baidu.com/view/0c33af946bec0975f465e277.html 4.2 情感分析的资源建设 4.2.1 情感分析 ...
- C#编程实现朴素贝叶斯算法下的情感分析
C#编程实现 这篇文章做了什么 朴素贝叶斯算法是机器学习中非常重要的分类算法,用途十分广泛,如垃圾邮件处理等.而情感分析(Sentiment Analysis)是自然语言处理(Natural Lang ...
随机推荐
- 029 Es面试小节
1.大纲 Es是什么?处理哪种业务逻辑用的多? Es类比数据库是什么? 对于数据库的字段.表等,在es中叫什么? Es的refresh把数据写到哪里? Es的数据如何变成检索和聚合索引的? Es的fl ...
- mysql 分库分表转
分表是分散数据库压力的好方法. 分表,最直白的意思,就是将一个表结构分为多个表,然后,可以再同一个库里,也可以放到不同的库. 当然,首先要知道什么情况下,才需要分表.个人觉得单表记录条数达到百万到千万 ...
- 怎样使用C# MD5加密来增强密码的安全度
一.前言 MD5说明http://zh.wikipedia.org/wiki/MD5 .NET MD5类 官方文档&示例http://msdn.microsoft.com/zh-cn/libr ...
- C#事件委托概念
事件就是一个狭义的委托,也就是事件是一个用于事件驱动模型的专用委托. 通俗的讲,委托你可以在客户代码中直接调用委托来激发委托指向的函数,而事件不可以,事件的触发只能由服务代码自己触发 也就是说在你的代 ...
- C++入门笔记(一)零碎基础知识
零碎基础知识 一.创建和运行程序 1.使用文本编辑器编写程序,保存为文件,该文件就叫源代码. 2.编译源代码:运行一个程序,将源代码翻译为主机使用的内部语言----机器语言.包含了 编译后程序的文件就 ...
- [CF1093G]Multidimensional Queries
[CF1093G]Multidimensional Queries 题目大意: \(k(k\le5)\)维空间中有\(n(n\le2\times10^5)\)个点.\(m\)次操作,操作包含一下两种: ...
- FCC学习笔记(二)
Nest an Anchor Element within a Paragraph 作为参考,再次看一看a元素的图示: 例如: <p>Here's a <a href="h ...
- 纯javascript实现可拖住/大小的div
好久没写了,不得不说人懒了好多.. 也不打算实现什么太厉害的功能,因为不喜欢网上那些一大堆代码的,看的头晕,于是自己写了一个 旨在越简单越好(当然也走点形式- -其实是自己菜),所以一些宽度和高度都写 ...
- zipkin
转:https://blog.csdn.net/liaokailin/article/details/52077620 zipkin为分布式链路调用监控系统,聚合各业务系统调用延迟数据,达到链路调用监 ...
- 你不知道的JS之作用域和闭包(四)(声明)提升
原文:你不知道的js系列 先有鸡还是先有蛋? 如下代码: a = 2; var a; console.log( a ); 很多开发者可能会认为结果会输出 undefined,因为 var a 在 a ...