Py를 이용한 Seq2seq(시퀀스 대 시퀀스) 모델Torch

⚡ 스마트 요약

Seq2Seq는 두 개의 순환 신경망을 사용하여 입력 시퀀스를 출력 시퀀스로 매핑하는 인코더-디코더 아키텍처로, 입력과 출력 길이가 다른 기계 번역 및 기타 자연어 처리 작업에 사용됩니다.

  • 🧠 자연어 처리 기초: 자연어 처리(NLP)는 컴퓨터가 인간의 언어를 이해하고 반응할 수 있도록 해줍니다. 이는 다음과 같은 예에서 볼 수 있습니다. Google Translate.
  • 🔄 인코더-디코더: 하나의 RNN은 입력을 상태로 인코딩하고, 다른 하나의 RNN은 그 상태를 디코딩하여 출력을 생성합니다.
  • 🧮 GRU 계층: 게이트 반복 단위 track개의 숨겨진 상태와 업데이트 재설정, 업데이트 및 시퀀스 전체에 걸친 새로운 게이트.
  • 🪙 토큰 : SOS와 EOS 토큰은 학습 및 예측 과정에서 각 시퀀스의 시작과 끝을 표시합니다.
  • 🎯 교사의 강요: 예측된 단어 대신 실제 단어를 입력하면 학습이 안정화되고 속도가 빨라집니다.
  • 🤖 AI의 영향: Seq2Seq는 번역, 요약 및 챗봇의 기반이 되며, 이후의 어텐션 및 트랜스포머 모델에 영감을 주었습니다.

Seq2seq 시퀀스 대 시퀀스 모델

NLP 란 무엇입니까?

자연어 처리(NLP)는 컴퓨터가 인간의 자연어를 이해하고, 조작하고, 반응할 수 있도록 돕는 인공지능의 인기 있는 분야 중 하나입니다. NLP는 이러한 기술의 핵심 동력입니다. Google Translate 그것은 우리가 다른 언어를 이해하는 데 도움이 됩니다.

Seq2Seq란 무엇입니까?

Seq2Seq 시퀀스의 입력을 태그와 어텐션 값을 사용하여 시퀀스의 출력으로 매핑하는 인코더-디코더 기반의 기계 번역 및 언어 처리 방법입니다. 아이디어는 특수 토큰과 함께 작동하고 이전 시퀀스에서 다음 상태 시퀀스를 예측하는 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 메서드를 사용하여 단어 단위로 분할합니다. 그런 다음 시퀀스-투-시퀀스 모델을 위해 알 수 없는 단어에 인덱싱을 적용하여 딕셔너리를 생성합니다.

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는 데이터를 데이터프레임으로 읽어와서 소스 문장과 대상 문장으로 분리합니다. 각 문장에 대해 소문자로 정규화하고, 문자가 아닌 부분을 제거하고, 유니코드를 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 레이어는 다층 구조의 게이트 순환 유닛(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 모델의 학습 과정은 각 문장 쌍을 언어 인덱스를 기반으로 텐서로 변환하는 것으로 시작됩니다. 본 시퀀스-투-시퀀스 모델은 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)

보시다시피, 우리가 예측한 문장은 잘 일치하지 않으므로 더 높은 정확도를 얻으려면 더 많은 데이터로 학습하고 Sequence to Sequence 학습을 사용하여 더 많은 반복과 레이어 수를 추가해야 합니다.

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(Gated Recurrent Unit)는 리셋 게이트와 업데이트 게이트를 사용하여 메모리를 제어함으로써 일반 RNN보다 긴 시퀀스를 더 효율적으로 처리합니다. 또한 LSTM보다 가볍기 때문에 사양이 낮은 하드웨어에서도 학습 속도가 빠릅니다.

교사 강제 입력(Teacher forcing)은 학습 과정에서 모델 자체의 예측 대신 실제 목표 단어를 다음 디코더 입력으로 제공합니다. teacher_forcing_ratio 값으로 제어되는 이 기능은 수렴 속도를 높이고 출력 시퀀스 전체에 걸쳐 오류 누적을 줄입니다.

SOS(시퀀스 시작) 토큰은 디코더에게 생성을 시작하라고 지시합니다. EOS (시퀀스 끝) 토큰은 문장이 끝나는 위치를 표시합니다. 이들을 통해 모델은 가변 길이 입력과 출력을 처리할 수 있습니다.

머신러닝에서 seq2seq는 시퀀스 변환을 위한 핵심적인 지도 학습 접근 방식입니다. 여기서는 다음을 사용하여 구축되었습니다. PyTorch이 시스템은 원문 문장을 대상 문장에 매핑하는 방법을 학습하고, 요약 및 대화 시스템으로 확장됩니다.

GPT와 같은 최신 AI 모델은 트랜스포머를 사용하는데, 이는 시퀀스투시퀀스(seq2seq) 인코더-디코더 개념에 어텐션 메커니즘이 더해진 것입니다. 현재 대부분의 작업에서 트랜스포머가 주도적인 역할을 하지만, 고전적인 시퀀스투시퀀스 학습은 이러한 시스템의 기반을 여전히 잘 설명해 줍니다.

정확도가 낮은 것은 대개 학습 데이터 양이 부족하거나 반복 횟수가 너무 적기 때문입니다. 데이터셋 크기를 늘리고, 반복 횟수와 RNN 레이어 수를 추가하며, 긴 문장의 번역 품질을 향상시키기 위해 어텐션 메커니즘을 도입하는 것을 고려해 보세요.

이 게시물을 요약하면 다음과 같습니다.