Py を使用した Seq2seq (シーケンス間シーケンス) モデルTorch

⚡ スマートサマリー

Seq2Seqは、2つのリカレントニューラルネットワークを使用して入力シーケンスを出力シーケンスにマッピングするエンコーダー・デコーダーアーキテクチャであり、機械翻訳や、入力と出力の長さが異なるその他の自然言語処理タスクに活用されます。

  • 🧠 NLPの基礎: 自然言語処理により、コンピュータは人間の言語を理解し、応答することができる。 Google Translate.
  • 🔄 エンコーダー・デコーダー: 1つ目のRNNは入力を状態にエンコードし、2つ目のRNNはその状態を出力にデコードする。
  • 🧮 GRUレイヤー: ゲート反復ユニット track個の隠れ状態と、シーケンス全体にわたるリセット、更新、および新規ゲートの更新。
  • 🪙 トークン: SOSと EOS トークンは、トレーニングおよび予測中の各シーケンスの開始と終了を示します。
  • 🎯 教師による強制: 予測された単語ではなく、実際の単語を与えることで、トレーニングが安定し、スピードアップする。
  • 🤖 AIの影響: Seq2Seqは翻訳、要約、チャットボットの基盤となっており、後のアテンションモデルやトランスフォーマーモデルに影響を与えた。

Seq2seq シーケンス間モデル

NLPとは何ですか?

自然言語処理(NLP)は、人工知能の人気分野の一つで、コンピュータが人間の自然言語を理解、操作、応答できるように支援します。NLPは、人工知能の基盤となる技術です。 Google Translate それは他の言語を理解するのに役立ちます。

Seq2Seqとは何ですか?

シーケンス 2 シーケンス これは、タグとアテンション値を使用してシーケンスの入力をシーケンスの出力にマッピングする、エンコーダー/デコーダー ベースの機械翻訳および言語処理の方法です。 このアイデアは、特別なトークンと連携して動作する 2 つの RNN を使用し、前のシーケンスから次の状態シーケンスを予測しようとすることです。

前のシーケンスからシーケンスを予測する方法

前のシーケンスからシーケンスを予測する

Pyを使用して前のシーケンスからシーケンスを予測する手順は次のとおりです。TorCH。

ステップ 1) データをロードする

データセットには、次のデータセットを使用します。 タブ区切りの対訳文ペア。 ここでは英語からインドネシア語へのデータセットを使用します。 好きなものを選択できますが、コード内のファイル名とディレクトリを変更することを忘れないでください。

from __future__ import unicode_literals, print_function, division
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F

import numpy as np
import pandas as pd

import os
import re
import random

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

ステップ 2) データの準備

データセットを直接使用することはできません。文を単語に分割し、ワンホットベクトルに変換する必要があります。Langクラスでは、各単語に一意のインデックスを付けて辞書を作成します。Langクラスは各文を保存し、addSentence関数を使用して単語ごとに分割します。次に、Sequence to sequenceモデル用に、未知の単語すべてにインデックスを付けて辞書を作成します。

SOS_token = 0
EOS_token = 1
MAX_LENGTH = 20

#initialize Lang Class
class Lang:
   def __init__(self):
       #initialize containers to hold the words and corresponding index
       self.word2index = {}
       self.word2count = {}
       self.index2word = {0: "SOS", 1: "EOS"}
       self.n_words = 2  # Count SOS and EOS

#split a sentence into words and add it to the container
   def addSentence(self, sentence):
       for word in sentence.split(' '):
           self.addWord(word)

#If the word is not in the container, the word will be added to it, else, update the word counter
   def addWord(self, word):
       if word not in self.word2index:
           self.word2index[word] = self.n_words
           self.word2count[word] = 1
           self.index2word[self.n_words] = word
           self.n_words += 1
       else:
           self.word2count[word] += 1

Langクラスは、辞書を作成するのに役立つクラスです。各言語について、すべての文は単語に分割され、コンテナに追加されます。各コンテナは、適切なインデックスに単語を格納し、単語の数をカウントし、単語のインデックスを追加します。これにより、単語のインデックスを検索したり、インデックスから単語を検索したりできるようになります。

データは TAB で区切られているため、次を使用する必要があります。 パンダ データローダーとしてPandasを使用します。Pandasはデータをデータフレームとして読み込み、ソース文とターゲット文に分割します。各文について、小文字に正規化し、非文字をすべて削除し、UnicodeからASCIIに変換し、各単語が含まれるように文を分割します。

#Normalize every sentence
def normalize_sentence(df, lang):
   sentence = df[lang].str.lower()
   sentence = sentence.str.replace('[^A-Za-z\s]+', '')
   sentence = sentence.str.normalize('NFD')
   sentence = sentence.str.encode('ascii', errors='ignore').str.decode('utf-8')
   return sentence

def read_sentence(df, lang1, lang2):
   sentence1 = normalize_sentence(df, lang1)
   sentence2 = normalize_sentence(df, lang2)
   return sentence1, sentence2

def read_file(loc, lang1, lang2):
   df = pd.read_csv(loc, delimiter='\t', header=None, names=[lang1, lang2])
   return df

def process_data(lang1,lang2):
   df = read_file('text/%s-%s.txt' % (lang1, lang2), lang1, lang2)
   print("Read %s sentence pairs" % len(df))
   sentence1, sentence2 = read_sentence(df, lang1, lang2)

   source = Lang()
   target = Lang()
   pairs = []
   for i in range(len(df)):
       if len(sentence1[i].split(' ')) < MAX_LENGTH and len(sentence2[i].split(' ')) < MAX_LENGTH:
           full = [sentence1[i], sentence2[i]]
           source.addSentence(sentence1[i])
           target.addSentence(sentence2[i])
           pairs.append(full)

   return source, target, pairs

もう一つ便利な機能は、ペアをテンソルに変換することです。これは、ネットワークがテンソル型のデータしか読み取れないため、非常に重要です。また、この部分は、文の末尾に入力の終了をネットワークに伝えるトークンを追加する部分でもあるため、重要です。文中の各単語について、辞書内の該当する単語のインデックスを取得し、文末にトークンを追加します。

def indexesFromSentence(lang, sentence):
   return [lang.word2index[word] for word in sentence.split(' ')]

def tensorFromSentence(lang, sentence):
   indexes = indexesFromSentence(lang, sentence)
   indexes.append(EOS_token)
   return torch.tensor(indexes, dtype=torch.long, device=device).view(-1, 1)

def tensorsFromPair(input_lang, output_lang, pair):
   input_tensor = tensorFromSentence(input_lang, pair[0])
   target_tensor = tensorFromSentence(output_lang, pair[1])
   return (input_tensor, target_tensor)

Seq2Seq モデル

Seq2seq モデル

PyTorch Seq2seq モデルは Py を使用するモデルの一種ですTorモデルの上にエンコーダとデコーダが配置されています。エンコーダは文を単語ごとに語彙のインデックスまたは既知の単語のインデックスにエンコードし、デコーダは入力を順番にデコードしてエンコードされた入力の出力を予測し、可能であれば最後の入力を次の入力として使用しようとします。この方法では、次の入力を予測して文を作成することもできます。各文には、シーケンスの終わりを示すトークンが割り当てられます。予測の最後には、出力の終わりを示すトークンもあります。したがって、エンコーダからデコーダに状態を渡して出力を予測します。

Seq2seq モデル

エンコーダは入力文を単語ごとに順番にエンコードし、最後に文の終わりを示すトークンを生成します。エンコーダは埋め込み層とGRU層で構成されています。埋め込み層は、入力の埋め込みを固定サイズの単語辞書に格納するルックアップテーブルです。これはGRU層に渡されます。GRU層は、多層タイプのゲート付き再帰ユニットです。 Rnn これにより、シーケンスされた入力が計算されます。 このレイヤーは、前のレイヤーから隠れた状態を計算し、リセット、更新、および新しいゲートを更新します。

Seq2seq モデル

デコーダはエンコーダの出力から入力をデコードします。そして、次の出力を予測し、可能であればそれを次の入力として使用しようとします。デコーダは、埋め込み層、GRU層、線形層で構成されています。埋め込み層は出力のルックアップテーブルを作成し、それをGRU層に渡して予測出力状態を計算します。その後、線形層が活性化関数を計算し、予測出力の真の値を決定します。

class Encoder(nn.Module):
   def __init__(self, input_dim, hidden_dim, embbed_dim, num_layers):
       super(Encoder, self).__init__()

       #set the encoder input dimesion , embbed dimesion, hidden dimesion, and number of layers
       self.input_dim = input_dim
       self.embbed_dim = embbed_dim
       self.hidden_dim = hidden_dim
       self.num_layers = num_layers

       #initialize the embedding layer with input and embbed dimention
       self.embedding = nn.Embedding(input_dim, self.embbed_dim)
       #intialize the GRU to take the input dimetion of embbed, and output dimention of hidden and
       #set the number of gru layers
       self.gru = nn.GRU(self.embbed_dim, self.hidden_dim, num_layers=self.num_layers)

   def forward(self, src):
       embedded = self.embedding(src).view(1,1,-1)
       outputs, hidden = self.gru(embedded)
       return outputs, hidden

class Decoder(nn.Module):
   def __init__(self, output_dim, hidden_dim, embbed_dim, num_layers):
       super(Decoder, self).__init__()

#set the encoder output dimension, embed dimension, hidden dimension, and number of layers
       self.embbed_dim = embbed_dim
       self.hidden_dim = hidden_dim
       self.output_dim = output_dim
       self.num_layers = num_layers

# initialize every layer with the appropriate dimension. For the decoder layer, it will consist of an embedding, GRU, a Linear layer and a Log softmax activation function.
       self.embedding = nn.Embedding(output_dim, self.embbed_dim)
       self.gru = nn.GRU(self.embbed_dim, self.hidden_dim, num_layers=self.num_layers)
       self.out = nn.Linear(self.hidden_dim, output_dim)
       self.softmax = nn.LogSoftmax(dim=1)

   def forward(self, input, hidden):
# reshape the input to (1, batch_size)
       input = input.view(1, -1)
       embedded = F.relu(self.embedding(input))
       output, hidden = self.gru(embedded, hidden)
       prediction = self.softmax(self.out(output[0]))
       return prediction, hidden

class Seq2Seq(nn.Module):
   def __init__(self, encoder, decoder, device, MAX_LENGTH=MAX_LENGTH):
       super().__init__()

#initialize the encoder and decoder
       self.encoder = encoder
       self.decoder = decoder
       self.device = device

   def forward(self, source, target, teacher_forcing_ratio=0.5):
       input_length = source.size(0) #get the input length (number of words in sentence)
       batch_size = target.shape[1]
       target_length = target.shape[0]
       vocab_size = self.decoder.output_dim

#initialize a variable to hold the predicted outputs
       outputs = torch.zeros(target_length, batch_size, vocab_size).to(self.device)

#encode every word in a sentence
       for i in range(input_length):
           encoder_output, encoder_hidden = self.encoder(source[i])

#use the encoder's hidden layer as the decoder hidden
       decoder_hidden = encoder_hidden.to(device)

#add a token before the first predicted word
       decoder_input = torch.tensor([SOS_token], device=device)  # SOS

#topk is used to get the top K value over a list
#predict the output word from the current target word. If we enable the teaching force, then the next decoder input is the next word, else, use the decoder output highest value.
       for t in range(target_length):
           decoder_output, decoder_hidden = self.decoder(decoder_input, decoder_hidden)
           outputs[t] = decoder_output
           teacher_force = random.random() < teacher_forcing_ratio
           topv, topi = decoder_output.topk(1)
           input = (target[t] if teacher_force else topi)
           if(teacher_force == False and input.item() == EOS_token):
               break

       return outputs

ステップ 3) モデルのトレーニング

Seq2seq モデルのトレーニング プロセスは、各文のペアを Lang インデックスから Tensor に変換することから始まります。シーケンス ツー シーケンス モデルでは、オプティマイザとして SGD を使用し、損失を計算するために NLLLoss 関数を使用します。トレーニング プロセスは、文のペアをモデルに入力して正しい出力を予測することから始まります。各ステップで、モデルからの出力は正しい単語で計算され、損失が見つかり、パラメータが更新されます。したがって、75000 回の反復を使用するため、シーケンス ツー シーケンス モデルはデータセットから 75000 個のランダムなペアを生成します。

teacher_forcing_ratio = 0.5

def clacModel(model, input_tensor, target_tensor, model_optimizer, criterion):
   model_optimizer.zero_grad()

   input_length = input_tensor.size(0)
   loss = 0
   epoch_loss = 0
   # print(input_tensor.shape)

   output = model(input_tensor, target_tensor)

   num_iter = output.size(0)
   print(num_iter)

#calculate the loss from a predicted sentence with the expected result
   for ot in range(num_iter):
       loss += criterion(output[ot], target_tensor[ot])

   loss.backward()
   model_optimizer.step()
   epoch_loss = loss.item() / num_iter

   return epoch_loss

def trainModel(model, source, target, pairs, num_iteration=20000):
   model.train()

   optimizer = optim.SGD(model.parameters(), lr=0.01)
   criterion = nn.NLLLoss()
   total_loss_iterations = 0

   training_pairs = [tensorsFromPair(source, target, random.choice(pairs))
                     for i in range(num_iteration)]

   for iter in range(1, num_iteration+1):
       training_pair = training_pairs[iter - 1]
       input_tensor = training_pair[0]
       target_tensor = training_pair[1]

       loss = clacModel(model, input_tensor, target_tensor, optimizer, criterion)

       total_loss_iterations += loss

       if iter % 5000 == 0:
           avarage_loss= total_loss_iterations / 5000
           total_loss_iterations = 0
           print('%d %.4f' % (iter, avarage_loss))

   torch.save(model.state_dict(), 'mytraining.pt')
   return model

ステップ 4) モデルをテストする

Seq2seq Pyの評価プロセスTorch はモデルの出力を確認するためのものです。シーケンス・トゥ・シーケンスモデルの各ペアがモデルに入力され、予測された単語が生成されます。その後、各出力の最高値を調べて正しいインデックスを見つけます。最後に、モデルの予測結果と実際の文を比較します。

def evaluate(model, input_lang, output_lang, sentences, max_length=MAX_LENGTH):
   with torch.no_grad():
       input_tensor = tensorFromSentence(input_lang, sentences[0])
       output_tensor = tensorFromSentence(output_lang, sentences[1])

       decoded_words = []

       output = model(input_tensor, output_tensor)
       # print(output_tensor)

       for ot in range(output.size(0)):
           topv, topi = output[ot].topk(1)
           # print(topi)

           if topi[0].item() == EOS_token:
               decoded_words.append('')
               break
           else:
               decoded_words.append(output_lang.index2word[topi[0].item()])
   return decoded_words

def evaluateRandomly(model, source, target, pairs, n=10):
   for i in range(n):
       pair = random.choice(pairs)
       print('source {}'.format(pair[0]))
       print('target {}'.format(pair[1]))
       output_words = evaluate(model, source, target, pair)
       output_sentence = ' '.join(output_words)
       print('predicted {}'.format(output_sentence))

それでは、Seq to Seq を使用してトレーニングを開始しましょう。反復回数は 75000、RNN レイヤー数は 1、隠れ層のサイズは 512 とします。

lang1 = 'eng'
lang2 = 'ind'
source, target, pairs = process_data(lang1, lang2)

randomize = random.choice(pairs)
print('random sentence {}'.format(randomize))

#print number of words
input_size = source.n_words
output_size = target.n_words
print('Input : {} Output : {}'.format(input_size, output_size))

embed_size = 256
hidden_size = 512
num_layers = 1
num_iteration = 100000

#create encoder-decoder model
encoder = Encoder(input_size, hidden_size, embed_size, num_layers)
decoder = Decoder(output_size, hidden_size, embed_size, num_layers)

model = Seq2Seq(encoder, decoder, device).to(device)

#print model
print(encoder)
print(decoder)

model = trainModel(model, source, target, pairs, num_iteration)
evaluateRandomly(model, source, target, pairs)

ご覧のとおり、予測された文はあまりよく一致していないため、より高い精度を得るには、より多くのデータでトレーニングし、シーケンス間学習を使用して反復回数とレイヤー数を追加する必要があります。

random sentence ['tom is finishing his work', 'tom sedang menyelesaikan pekerjaannya']
Input : 3551 Output : 4253
Encoder(
  (embedding): Embedding(3551, 256)
  (gru): GRU(256, 512)
)
Decoder(
  (embedding): Embedding(4253, 256)
  (gru): GRU(256, 512)
  (out): Linear(in_features=512, out_features=4253, bias=True)
  (softmax): LogSoftmax()
)
5000 4.0906
10000 3.9129
15000 3.8171
20000 3.8369
25000 3.8199
30000 3.7957
75000 3.7044

よくあるご質問

Seq2Seqモデルは、ある配列を別の配列に変換するため、入力と出力の長さが異なるタスクに適しています。一般的な用途としては、機械翻訳、テキスト要約、質問応答、音声認識、チャットボットの応答生成などがあります。

エンコーダは入力シーケンスを読み込み、それを隠れ状態ベクトルに圧縮します。デコーダはその状態を受け取り、出力シーケンスをトークンごとに生成し、各予測結果を次の入力として再利用します。

GRU(ゲート付きリカレントユニット)は、リセットゲートと更新ゲートを用いてメモリを制御することで、通常のRNNよりも長いシーケンスを効率的に処理できます。また、LSTMよりも軽量であるため、低スペックのハードウェアでも高速な学習が可能です。

教師強制法は、学習中にモデル自身の予測ではなく、真のターゲット単語を次のデコーダー入力として供給します。teacher_forcing_ratioによって制御され、収束を速め、出力シーケンス全体にわたるエラーの蓄積を軽減します。

SOS(シーケンス開始)トークンはデコーダーに生成を開始するように指示し、 EOS (シーケンスの終了)トークンは、文の終わりを示します。これらを組み合わせることで、モデルは可変長の入力と出力を処理できるようになります。

機械学習において、seq2seqは配列変換のためのコアとなる教師ありアプローチです。ここでは、 PyTorchそれによって、ソース文をターゲット文にマッピングすることを学習し、要約システムや対話システムにも拡張されます。

GPTなどの最新のAIモデルは、seq2seqエンコーダー・デコーダーの概念にアテンション機構を加えたトランスフォーマーを使用しています。現在ではほとんどのタスクでトランスフォーマーが主流となっていますが、古典的なseq2seqを学ぶことで、これらのシステムの基盤を理解することができます。

精度が低い場合、通常は学習データが少なすぎるか、反復回数が少なすぎることを意味します。データセットのサイズを増やし、反復回数とRNN層の数を増やし、さらに長い文章の翻訳品質を向上させるためにアテンション機構を追加することを検討してください。