Press "Enter" to skip to content

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

数据集包括两个文件:
train.tsv
test.tsv

,内容是从网上搜集的情感文本数据,简单地经过分词后用空格拼接起来。训练集和测试集各有10000条数据

 

2 构建文本分类器

 

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

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

 

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

Be First to Comment

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注