Pytext實戰-構建一個文字分類器有多快

致Great發表於2019-03-02

1 資料集準備

資料集
資料集包括兩個檔案:train.tsvtest.tsv,內容是從網上搜集的情感文字資料,簡單地經過分詞後用空格拼接起來。訓練集和測試集各有10000條資料

2 構建文字分類器

Pytext框架包括了Task, Trainer, Model, DataHandler, Exporter 元件,分別對應了任務切換、模型訓練、模型結構、資料處理、模型匯出的作用,它們都繼承自名Component的類

Pytext實戰-構建一個文字分類器有多快

(圖片來自: 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 
複製程式碼

Pytext實戰-構建一個文字分類器有多快
經過3-4分鐘後,10 epoch訓練完畢,在沒有使用詞向量以及直接使用預設設定,在測試集的預測效果如下,
image.png

  • 步驟2 匯出模型
CONFIG=docnn.json 
pytext export --output-path model.c2 < "$CONFIG"
複製程式碼

在桌面上我們可以看到匯出的模型 model.c2

Pytext實戰-構建一個文字分類器有多快

  • 步驟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 "這是什麼商品啊!太 差了吧?"
複製程式碼

Pytext實戰-構建一個文字分類器有多快

3 總結

我們上面過程可以看到,pytext加速了模型從訓練到落地的速度,省去了很多繁瑣的工程。不過,我們上面的例子模型需要有待提高,需要研究下自定義模型和詞向量使用,提高分類效果。

相關文章