在《使用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. mac中如何卸载pkg包

    ---恢复内容开始--- 参考地址.https://blog.csdn.net/play_fun_tech/article/details/27964861?utm_source=tuicool&am ...

  2. 问题之Spring MVC配置后,可以打开jsp页面,但打不开html页面

    一.配置Spring MVC 1.导入jar spring框架:http://repo.spring.io/release/org/springframework/spring/ spring-fra ...

  3. Linux内核内存管理架构

    内存管理子系统可能是linux内核中最为复杂的一个子系统,其支持的功能需求众多,如页面映射.页面分配.页面回收.页面交换.冷热页面.紧急页面.页面碎片管理.页面缓存.页面统计等,而且对性能也有很高的要 ...

  4. 查看mac系统版本

    打开终端, 输入命令 uname -a 回车 x86_64 表示系统为64位 i686 表示系统32位的

  5. 学习--->更新集合/内存/深浅拷贝

     一.计算机基础 1..软件(应用程序) 2.解释器/编译器 - 解释型语言:将代码每一行传递给计算机一行,常用编程语言python,PHP,Ruby. - 编译型语言:将代码完全执行完后会形成一个文 ...

  6. C#线程 ---- 线程同步详解

    线程同步 说明:接上一篇,注意分享线程同步的必要性和线程同步的方法. 测试代码下载:https://github.com/EkeSu/C-Thread-synchronization-C-.git 一 ...

  7. LeetCode 字符串专题(一)

    目录 LeetCode 字符串专题 <c++> \([5]\) Longest Palindromic Substring \([28]\) Implement strStr() [\(4 ...

  8. hadoop源码学习(二)之ZooKeeper

    要能够熟练使用hadoop,就得对其原理和源码有些了解.hadoop中比较重要的概念是NameNode,DataNode,去看这些类时,又会发现其使用了ZooKeeper包,这样就可以将hadoop的 ...

  9. Flask的上下文源码剖析

    先写一段Flask程序 from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return ...

  10. layui 表格内容显示更改

    在cole 中使用temple 属性进行修改 例: table.render({ elem: '#messageTable' ,id: 'search_table_mId' ,height: 500 ...