1 数据集准备
数据集包括两个文件: train.tsv 和 test.tsv, 内容是从网上搜集的情感文本数据, 简单地经过分词后用空格拼接起来. 训练集和测试集各有 10000 条数据
2 构建文本分类器
Pytext 框架包括了 Task, Trainer, Model, DataHandler, Exporter 组件, 分别对应了任务切换, 模型训练, 模型结构, 数据处理, 模型导出的作用, 它们都继承自名 Component 的类
(图片来自:
Component 可以读取 JSON 类型的配置文件, 配置文件可以设置训练过程中使用的输入和学习率等参数. 按照官方文本分类教程, 我们几乎可以不需要实现模型, 输入, 输出等代码, 只需要准备好数据集即可.
docnn.JSON 的内容如下:
- {
- "task": {
- "DocClassificationTask": {
- "data_handler": {
- "train_path": "train.tsv",
- "eval_path": "test.tsv",
- "test_path": "test.tsv"
- }
- }
- }
- }
步骤 1 训练模型:
pytext train < docnn.JSON
经过 3-4 分钟后, 10 epoch 训练完毕, 在没有使用词向量以及直接使用默认设置, 在测试集的预测效果如下,
步骤 2 导出模型
- CONFIG=docnn.JSON
- pytext export --output-path model.c2 < "$CONFIG"
在桌面上我们可以看到导出的模型 model.c2
步骤 3 模型预测 参考意图识别的例子, 我写了下面的测试代码
- # !/usr/bin/env python3
- # -*- coding:utf-8 _*-
- """
- @Author:yanqiang
- @File: demo.py
- @Time: 2018/12/21 19:06
- @Software: PyCharm
- @Description:
- """
- import sys
- import pytext
- import jieba
- config_file = sys.argv[1]
- model_file = sys.argv[2]
- text = sys.argv[3]
- text = " ".join([Word for Word in jieba.cut(text)])
- config = pytext.load_config(config_file)
- predictor = pytext.create_predictor(config, model_file)
- # Pass the inputs to PyText's prediction API
- result = predictor({"raw_text": text})
- # Results is a list of output blob names and their scores.
- # The blob names are different for joint models vs doc models
- # Since this tutorial is for both, let's check which one we should look at.
- doc_label_scores_prefix = (
- 'scores:' if any(r.startswith('scores:') for r in result)
- else 'doc_scores:'
- )
- # For now let's just output the top document label!
- best_doc_label = max(
- (label for label in result if label.startswith(doc_label_scores_prefix)),
- key=lambda label: result[label][0],
- # Strip the doc label prefix here
- )[len(doc_label_scores_prefix):]
- print("输入句子的情感为:%s" % best_doc_label)
我们看看效果:
python main.py "$CONFIG" model.c2 "超级喜欢蒙牛这个味 道"
python main.py "$CONFIG" model.c2 "这是什么商品啊! 太 差了吧?"
3 总结
我们上面过程可以看到, pytext 加速了模型从训练到落地的速度, 省去了很多繁琐的工程. 不过, 我们上面的例子模型需要有待提高, 需要研究下自定义模型和词向量使用, 提高分类效果.
来源: https://juejin.im/post/5c1e4cbce51d4529dc45adb7