前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Pytext实战-构建一个文本分类器有多快

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

作者头像
致Great
发布2018-12-28 16:00:24
6840
发布2018-12-28 16:00:24
举报
文章被收录于专栏:程序生活程序生活程序生活

1 数据集准备

数据集

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

2 构建文本分类器

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

(图片来自: https://pytext-pytext.readthedocs-hosted.com/en/latest/overview.html

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

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.12.22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1 数据集准备
  • 2 构建文本分类器
  • 3 总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档