PyTorch 1.3 Tutorials : テキスト : TorchText でテキスト分類

PyTorch 1.3 Tutorials : テキスト : TorchText でテキスト分類 (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 12/28/2019 (1.3.1)

* 本ページは、PyTorch 1.3 Tutorials の以下のページを翻訳した上で適宜、補足説明したものです:

* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。

 

テキスト : TorchText でテキスト分類

このチュートリアルは torchtext でどのように、以下を含むテキスト分類データセットを使用するかを示します :

- AG_NEWS,
- SogouNews,
- DBpedia,
- YelpReviewPolarity,
- YelpReviewFull,
- YahooAnswers,
- AmazonReviewPolarity,
- AmazonReviewFull

このサンプルはこれらの TextClassification データセットの一つを使用して分類のための教師あり学習アルゴリズムをどのように訓練するか示します。

 

ngram でデータをロードする

bag of ngrams 特徴は局所単語順序についての何某かの部分的な情報を捕捉するために適用されます。実際には、一つだけの単語よりも単語グループとして bi-gram か tri-gram がより多くの利益を提供するために適用されます :

"load data with ngrams"
Bi-grams results: "load data", "data with", "with ngrams"
Tri-grams results: "load data with", "data with ngrams"

TextClassification データセットは ngram メソッドをサポートします。ngrams を 2 に設定することにより、 データセットのサンプルテキストは単一単語プラス bi-grams 文字列のリストになります。

import torch
import torchtext
from torchtext.datasets import text_classification
NGRAMS = 2
import os
if not os.path.isdir('./.data'):
    os.mkdir('./.data')
train_dataset, test_dataset = text_classification.DATASETS['AG_NEWS'](
    root='./.data', ngrams=NGRAMS, vocab=None)
BATCH_SIZE = 16
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

 

モデルを定義する

モデルは EmbeddingBag 層と線形層から成ります (下の図参照)。nn.EmbeddingBag は埋め込みの「バッグ」の平均値を計算します。ここでのテキスト・エントリは異なる長さを持ちます。ここでは nn.EmbeddingBag はパディングを必要としません、何故ならばテキスト長はオフセットにセーブされているからです。

更に、nn.EmbeddingBag は埋め込みに渡り平均を on the fly に累積しますので、nn.EmbeddingBag は tensor のシークエンスを処理するパフォーマンスとメモリ効率を強化できます。

import torch.nn as nn
import torch.nn.functional as F
class TextSentiment(nn.Module):
    def __init__(self, vocab_size, embed_dim, num_class):
        super().__init__()
        self.embedding = nn.EmbeddingBag(vocab_size, embed_dim, sparse=True)
        self.fc = nn.Linear(embed_dim, num_class)
        self.init_weights()

    def init_weights(self):
        initrange = 0.5
        self.embedding.weight.data.uniform_(-initrange, initrange)
        self.fc.weight.data.uniform_(-initrange, initrange)
        self.fc.bias.data.zero_()

    def forward(self, text, offsets):
        embedded = self.embedding(text, offsets)
        return self.fc(embedded)

 

インスタンスを初期化する

AG_NEWS データセットは 4 つのラベルを持ちしたがってクラス数は 4 です。

1 : World
2 : Sports
3 : Business
4 : Sci/Tec

語彙サイズは語彙の長さに等しいです (単一単語と ngram を含みます)。クラス数はラベルの数に等しく、これは AG_NEWS の場合では 4 です。

VOCAB_SIZE = len(train_dataset.get_vocab())
EMBED_DIM = 32
NUN_CLASS = len(train_dataset.get_labels())
model = TextSentiment(VOCAB_SIZE, EMBED_DIM, NUN_CLASS).to(device)

 

バッチを生成するために使用される関数

テキスト・エントリは異なる長さを持ちますので、データバッチとオフセットを生成するためにカスタム関数 generate_batch() が使用されます。関数は torch.utils.data.DataLoader の collate_fn に渡されます。collate_fn への入力は batch_size のサイズを持つ tensor のリストで、collate_fn 関数はそれらをミニバッチにパックします。ここで注意してください、そして collate_fn はトップレベル def として宣言されることを確実にしてください。これは関数が各ワーカーで利用可能であることを保証します。

元のデータバッチ入力のテキスト・エントリはリストにパックされて nn.EmbeddingBag の入力として単一の tensor に結合されます。オフセットはテキスト tensor で個々のシークエンスの開始インデックスを表す区切り文字 (= delimiter) の tensor です。ラベルは個々のテキスト・エントリのラベルを保存している tensor です。

def generate_batch(batch):
    label = torch.tensor([entry[0] for entry in batch])
    text = [entry[1] for entry in batch]
    offsets = [0] + [len(entry) for entry in text]
    # torch.Tensor.cumsum returns the cumulative sum
    # of elements in the dimension dim.
    # torch.Tensor([1.0, 2.0, 3.0]).cumsum(dim=0)

    offsets = torch.tensor(offsets[:-1]).cumsum(dim=0)
    text = torch.cat(text)
    return text, offsets, label

 

モデルを訓練して結果を評価するための関数を定義する

torch.utils.data.DataLoader は PyTorch ユーザのために推奨されます、そしてそれはデータローディングを容易に並列にします (チュートリアルは ここ です)。ここでは AG_NEWS データセットをロードするために DataLoader を使用してそれを訓練/検証のためにモデルに送ります。

from torch.utils.data import DataLoader

def train_func(sub_train_):

    # Train the model
    train_loss = 0
    train_acc = 0
    data = DataLoader(sub_train_, batch_size=BATCH_SIZE, shuffle=True,
                      collate_fn=generate_batch)
    for i, (text, offsets, cls) in enumerate(data):
        optimizer.zero_grad()
        text, offsets, cls = text.to(device), offsets.to(device), cls.to(device)
        output = model(text, offsets)
        loss = criterion(output, cls)
        train_loss += loss.item()
        loss.backward()
        optimizer.step()
        train_acc += (output.argmax(1) == cls).sum().item()

    # Adjust the learning rate
    scheduler.step()

    return train_loss / len(sub_train_), train_acc / len(sub_train_)

def test(data_):
    loss = 0
    acc = 0
    data = DataLoader(data_, batch_size=BATCH_SIZE, collate_fn=generate_batch)
    for text, offsets, cls in data:
        text, offsets, cls = text.to(device), offsets.to(device), cls.to(device)
        with torch.no_grad():
            output = model(text, offsets)
            loss = criterion(output, cls)
            loss += loss.item()
            acc += (output.argmax(1) == cls).sum().item()

    return loss / len(data_), acc / len(data_)

 

データセットを分割してモデルを実行する

元の AG_NEWS は検証 (= valid) データセットを持ちませんので、訓練データセットを 0.95 (訓練) と 0.05 (検証) の分割比率で訓練/検証セットに分割します。ここで PyTorch コアライブラリの torch.utils.data.dataset.random_split 関数を使用します。

CrossEntropyLoss criterion は nn.LogSoftmax() と nn.NLLLoss() を単一クラスに結合しています。それは C クラスで分類問題を訓練するときに有用です。SGD は optimizer として確率的勾配降下メソッドを実装しています。初期学習率は 4.0 に設定されます。エポックを通して学習率を調整するためにここでは StepLR が使用されます。

import time
from torch.utils.data.dataset import random_split
N_EPOCHS = 5
min_valid_loss = float('inf')

criterion = torch.nn.CrossEntropyLoss().to(device)
optimizer = torch.optim.SGD(model.parameters(), lr=4.0)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1, gamma=0.9)

train_len = int(len(train_dataset) * 0.95)
sub_train_, sub_valid_ = \
    random_split(train_dataset, [train_len, len(train_dataset) - train_len])

for epoch in range(N_EPOCHS):

    start_time = time.time()
    train_loss, train_acc = train_func(sub_train_)
    valid_loss, valid_acc = test(sub_valid_)

    secs = int(time.time() - start_time)
    mins = secs / 60
    secs = secs % 60

    print('Epoch: %d' %(epoch + 1), " | time in %d minutes, %d seconds" %(mins, secs))
    print(f'\tLoss: {train_loss:.4f}(train)\t|\tAcc: {train_acc * 100:.1f}%(train)')
    print(f'\tLoss: {valid_loss:.4f}(valid)\t|\tAcc: {valid_acc * 100:.1f}%(valid)')
Epoch: 1  | time in 0 minutes, 9 seconds
        Loss: 0.0262(train)     |       Acc: 84.6%(train)
        Loss: 0.0001(valid)     |       Acc: 91.0%(valid)
Epoch: 2  | time in 0 minutes, 9 seconds
        Loss: 0.0119(train)     |       Acc: 93.7%(train)
        Loss: 0.0001(valid)     |       Acc: 91.3%(valid)
Epoch: 3  | time in 0 minutes, 9 seconds
        Loss: 0.0070(train)     |       Acc: 96.4%(train)
        Loss: 0.0001(valid)     |       Acc: 91.9%(valid)
Epoch: 4  | time in 0 minutes, 9 seconds
        Loss: 0.0038(train)     |       Acc: 98.1%(train)
        Loss: 0.0001(valid)     |       Acc: 91.3%(valid)
Epoch: 5  | time in 0 minutes, 9 seconds
        Loss: 0.0023(train)     |       Acc: 99.0%(train)
        Loss: 0.0001(valid)     |       Acc: 91.7%(valid)

次の情報とともに GPU 上でモデルを訓練しています :

Epoch: 1 | time in 0 minutes, 11 seconds

Loss: 0.0263(train)     |       Acc: 84.5%(train)
Loss: 0.0001(valid)     |       Acc: 89.0%(valid)

Epoch: 2 | time in 0 minutes, 10 seconds

Loss: 0.0119(train)     |       Acc: 93.6%(train)
Loss: 0.0000(valid)     |       Acc: 89.6%(valid)

Epoch: 3 | time in 0 minutes, 9 seconds

Loss: 0.0069(train)     |       Acc: 96.4%(train)
Loss: 0.0000(valid)     |       Acc: 90.5%(valid)

Epoch: 4 | time in 0 minutes, 11 seconds

Loss: 0.0038(train)     |       Acc: 98.2%(train)
Loss: 0.0000(valid)     |       Acc: 90.4%(valid)

Epoch: 5 | time in 0 minutes, 11 seconds

Loss: 0.0022(train)     |       Acc: 99.0%(train)
Loss: 0.0000(valid)     |       Acc: 91.0%(valid)

 

テスト・データセットでモデルを評価する

print('Checking the results of test dataset...')
test_loss, test_acc = test(test_dataset)
print(f'\tLoss: {test_loss:.4f}(test)\t|\tAcc: {test_acc * 100:.1f}%(test)')
Checking the results of test dataset...
        Loss: 0.0003(test)      |       Acc: 88.1%(test)

テストデータセットの結果をチェックする…

Loss: 0.0237(test)      |       Acc: 90.5%(test)

 

ランダムなニュース上のテスト

ここまでの最善のモデルを使用してゴルフのニュースをテストします。ラベル情報は ここ で利用可能です。

import re
from torchtext.data.utils import ngrams_iterator
from torchtext.data.utils import get_tokenizer

ag_news_label = {1 : "World",
                 2 : "Sports",
                 3 : "Business",
                 4 : "Sci/Tec"}

def predict(text, model, vocab, ngrams):
    tokenizer = get_tokenizer("basic_english")
    with torch.no_grad():
        text = torch.tensor([vocab[token]
                            for token in ngrams_iterator(tokenizer(text), ngrams)])
        output = model(text, torch.tensor([0]))
        return output.argmax(1).item() + 1

ex_text_str = "MEMPHIS, Tenn. – Four days ago, Jon Rahm was \
    enduring the season’s worst weather conditions on Sunday at The \
    Open on his way to a closing 75 at Royal Portrush, which \
    considering the wind and the rain was a respectable showing. \
    Thursday’s first round at the WGC-FedEx St. Jude Invitational \
    was another story. With temperatures in the mid-80s and hardly any \
    wind, the Spaniard was 13 strokes better in a flawless round. \
    Thanks to his best putting performance on the PGA Tour, Rahm \
    finished with an 8-under 62 for a three-stroke lead, which \
    was even more impressive considering he’d never played the \
    front nine at TPC Southwind."

vocab = train_dataset.get_vocab()
model = model.to("cpu")

print("This is a %s news" %ag_news_label[predict(ex_text_str, model, vocab, 2)])
This is a Sports news

このノートで表示されたコード・サンプルは ここ で見つけられます。

 
以上