使用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 ...
随机推荐
- pygame学习之绘制移动的矩形
import pygame from pygame.locals import * pygame.init() screen = pygame.display.set_mode((600, 500)) ...
- 利用 Saltstack 远程执行命令
Saltstack的一个比较突出优势就是具备执行远程命令的功能. 操作方法与func (https://fedorahosted.org/func/)相似,可以帮助运维人员完成集中化的操作平台. ht ...
- IO流2
一.IO流简介及分类 1.IO流简介 IO流: 简单理解数据从一个地方流向另外一个地方 2.IO流分类 按照数据流动的方向 分为 输入流和输出流 按照数据流动的单位分为 字节流和字符流 二.四大 ...
- centos7.x 安装 fastDFS
环境准备 使用的系统软件 名称 说明 centos 7.x libfatscommon FastDFS分离出的一些公用函数包 FastDFS FastDFS本体 fastdfs-nginx-modul ...
- Vray
VRay是由chaosgroup和asgvis公司出品,中国由曼恒公司负责推广的一款高质量渲染软件.
- JS精度问题(0.1+0.2 = 0.3吗?)
一.引出问题 0.1+0.2 = 0.3吗?在JS中是这样的吗?我们写个测试代码不就知道了吗? 结果出人意料,并不像我们所想象的那样.那么这到底是为什么呢? 二.原因分析 JS浮点数存储机制: 三.解 ...
- 多项式与三角函数求导——BUAA OO 第一单元作业总结
第一次作业 需求简要说明 针对符合规定的多项式表达式输出其符合格式规定的导函数多项式,格式错误输出WRONG FORMAT! 带符号整数 支持前导0的带符号整数,符号可省略,如: +02.-16> ...
- yii2 注册一个新事件(trigger Event)
有些时候我们需要在某个方法的中间注册一个新事件,确保某些业务的可拓展性. 下面我介绍一下注册一个新事件的方法: 第一步:需要的地方(比如控制器或模型)中定义一个事件常量(如:const EVENT_C ...
- centos7安装tomcat8.5
1.下载 tomcat Linux 版本 tomcat 官网下载地址:http://tomcat.apache.org/download-80.cgi 百度云盘链接:链接: https://pan.b ...
- sql查询优化策略
Sql语句执行顺序: 查询的逻辑执行顺序 (1) FROM left_table (3) join_type JOIN right_table (2) ON join_condition (4) WH ...