在《使用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实现情感分析[新手篇]后补的更多相关文章

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

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

  2. INTERSPEECH2020 语音情感分析论文之我见

    摘要:本文为大家带来InterSpeech2020 语音情感分析25篇论文中的其中8篇的总结. 本文分享自华为云社区<INTERSPEECH2020 语音情感分析论文总结一>,原文作者:T ...

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

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

  4. 在Keras中用Bert进行情感分析

    之前在BERT实战——基于Keras一文中介绍了两个库 keras_bert 和 bert4keras 但是由于 bert4keras 处于开发阶段,有些函数名称和位置等等发生了变化,那篇文章只用了 ...

  5. 如何用KNIME进行情感分析

    Customer Intelligence Social Media Finance Credit Scoring Manufacturing Pharma / Health Care Retail ...

  6. 朴素贝叶斯算法下的情感分析——C#编程实现

    这篇文章做了什么 朴素贝叶斯算法是机器学习中非常重要的分类算法,用途十分广泛,如垃圾邮件处理等.而情感分析(Sentiment Analysis)是自然语言处理(Natural Language Pr ...

  7. Stanford NLP学习笔记:7. 情感分析(Sentiment)

    1. 什么是情感分析(别名:观点提取,主题分析,情感挖掘...) 应用: 1)正面VS负面的影评(影片分类问题) 2)产品/品牌评价: Google产品搜索 3)twitter情感预测股票市场行情/消 ...

  8. SA: 情感分析资源(Corpus、Dictionary)

    先主要摘自一篇中文Survey,http://wenku.baidu.com/view/0c33af946bec0975f465e277.html   4.2 情感分析的资源建设 4.2.1 情感分析 ...

  9. C#编程实现朴素贝叶斯算法下的情感分析

    C#编程实现 这篇文章做了什么 朴素贝叶斯算法是机器学习中非常重要的分类算法,用途十分广泛,如垃圾邮件处理等.而情感分析(Sentiment Analysis)是自然语言处理(Natural Lang ...

随机推荐

  1. 使用Kazoo操作ZooKeeper服务治理

    单机服务的可靠性及可扩展性有限,某台服务宕机可能会影响整个系统的正常使用:分布式服务能够有效地解决这一问题,但同时分布式服务也会带来一些新的问题,如:服务发现(新增或者删除了服务如何确保能让客户端知道 ...

  2. 用Sklearn画一颗决策树

    小伙伴们大家好~o( ̄▽ ̄)ブ,首先声明一下,我的开发环境是Jupyter lab,所用的库和版本大家参考: Python 3.7.1(你的版本至少要3.4以上 Scikit-learn 0.20.0 ...

  3. 数组遍历for forEach for..in for..of

    最开始接触的遍历for 通过下标获取数组每一项的值 ,,]; ;i<num.length;i++) { console.log(num[i]) } /*打印2 5 7*/ forEach遍历数组 ...

  4. web-storage-cache 使用JS数据缓存

    https://github.com/WQTeam/web-storage-cache 使用WebStorageCache,只要在页面上引入下面代码即可. <script src="s ...

  5. Spring-Docker简易指南

     使用代码:https://files.cnblogs.com/files/miracle9527/demo4springboot.rar # 约定#为注释行.$为命令行 # 开始操作前将demo4s ...

  6. python基础----1. globals和locals

    官方文档 globals """ Return a dictionary representing the current global symbol table. Th ...

  7. sqlzoo:using group by and having

    For each continent show the number of countries: SELECT continent, COUNT(name) FROM world GROUP BY c ...

  8. Python列表,字典和字符串操作

    列表: 列表:list, 也叫数组,表现[].特点:有角标,元素可以重复,有序的元素 例子:stus = ['王志华','乔美玲','乔美玲','王文文','feixiang']#中括号,这就是一个l ...

  9. 样式布局与 BFC

    一.几类视图 内联视图:inline 单行 块级视图:block 换行,有高度 行内块级视图:inline-block 单行,有高度 二.几类布局 块级布局 换行,通过设置 margin 水平居中 & ...

  10. Golang Go Go Go part3:数据类型及操作

    五.Go 基本类型 1.基本类型种类 布尔值: bool 长度 1字节 取值范围 true, false注意事项:不可用数字代表 true 或 false 整型: int/uint 根据运行平台可能为 ...