Pytext实战-构建一个文本分类器有多快

1 数据集准备

数据集
数据集包括两个文件: train.tsvtest.tsv,内容是从网上搜集的情感文本数据,简单地通过分词后用空格拼接起来。训练集和测试集各有10000条数据

2 构建文本分类器

Pytext框架包括了Task, Trainer, Model, DataHandler, Exporter 组件,分别对应了任务切换、模型训练、模型结构、数据处理、模型导出的做用,它们都继承自名Component的类 html

(图片来自: pytext-pytext.readthedocs-hosted.com/en/latest/o…python

Component能够读取JSON类型的配置文件,配置文件能够设置训练过程当中使用的输入和学习率等参数。按照官方文本分类教程,咱们几乎能够不须要实现模型,输入,输出等代码,只须要准备好数据集便可。json

docnn.json的内容以下:bash

{
  "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训练完毕,在没有使用词向量以及直接使用默认设置,在测试集的预测效果以下,
image.png

  • 步骤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加速了模型从训练到落地的速度,省去了不少繁琐的工程。不过,咱们上面的例子模型须要有待提升,须要研究下自定义模型和词向量使用,提升分类效果。测试

相关文章
相关标签/搜索