모두야

CH7) RNN을 사용한 문장 생성 - (1) 본문

밑.시.딥/2권

CH7) RNN을 사용한 문장 생성 - (1)

미미밍2 2021. 9. 28. 14:10
반응형
  • 언어 모델을 사용하여 '문장 생성' 수행
    1. 말뭉치로 학습된 언어 모델을 이용하여 새로운 문장 생성
    2. 개선된 언어 모델을 이용하여 더 자연스러운 문장 생성

  • seq2seq 구조 공부하기
    : 한 시계열 데이터를 다른 시계열 데이터로 변환한다.
    : RNN 두 개를 연결한다.

RNN을 사용한 문장 생성 순서

LSTM / Time LSTM

언어 모델에게 문장을 생성 시키는 순서

- "you say goodbye and I say hello." 라는 말뭉치로 학습한 언어 모델이다.

  1. 학습 된 언어 모델에 "I"라는 단어를 입력으로 준다.
  2. 언어 모델은 [그림 7-2]와 같은 확률분포를 출력한다.
  3. 다음 단어를 새로 생성한다.
    (1) [결정적 선택] 확률이 가장 높은 단어를 선택한다. 
    (2) [확률적 선택] 단어의 확률에 맞게 선택한다.
  4. 확률 분포에 따라 "say"라는 단어가 선택 되었다.
  5. 다음 단어를 샘플링한다.
  6. 원하는 만큼 반복한다. (<eos> 종결 기호)
생성된 문장은 훈련 데이터에 존재하지 않는, 새롭게 생성된 문장이다. 훈련 데이터에서 사용된 단어의 정렬 패턴을 학습하였다.


문장 생성 구현

class BetterRnnlmGen(BetterRnnlm):
    def generate(self, start_id, skip_ids=None, sample_size=100):
        word_ids = [start_id]

        x = start_id
        while len(word_ids) < sample_size:
            x = np.array(x).reshape(1, 1)
            score = self.predict(x).flatten()
            p = softmax(score).flatten()

            sampled = np.random.choice(len(p), size=1, p=p)
            if (skip_ids is None) or (sampled not in skip_ids):
                x = sampled
                word_ids.append(int(x))

        return word_ids

    def get_state(self):
        states = []
        for layer in self.lstm_layers:
            states.append((layer.h, layer.c))
        return states

    def set_state(self, states):
        for layer, state in zip(self.lstm_layers, states):
            layer.set_state(*state)
# coding: utf-8
import sys
sys.path.append('..')
from common.np import *
#from rnnlm_gen import BetterRnnlmGen
from dataset import ptb


corpus, word_to_id, id_to_word = ptb.load_data('train')
vocab_size = len(word_to_id)
corpus_size = len(corpus)


model = BetterRnnlmGen()
model.load_params('BetterRnnlm.pkl')

# start 문자와 skip 문자 설정
start_word = 'you'
start_id = word_to_id[start_word]
skip_words = ['N', '<unk>', '$']
skip_ids = [word_to_id[w] for w in skip_words]
# 문장 생성
word_ids = model.generate(start_id, skip_ids)
txt = ' '.join([id_to_word[i] for i in word_ids])
txt = txt.replace(' <eos>', '.\n')

print(txt)


model.reset_state()

start_words = 'the meaning of life is'
start_ids = [word_to_id[w] for w in start_words.split(' ')]

for x in start_ids[:-1]:
    x = np.array(x).reshape(1, 1)
    model.predict(x)

word_ids = model.generate(start_ids[-1], skip_ids)
word_ids = start_ids[:-1] + word_ids
txt = ' '.join([id_to_word[i] for i in word_ids])
txt = txt.replace(' <eos>', '.\n')
print('-' * 50)
print(txt)
you can be used that the aim of a president all of the works he says.
 i think the implication of enthusiasm is that it will conduct a justice department in u.s.-soviet and sometimes perceived it does n't mean we have the fire of red bags or the most controversial will be established of other floor builders and developers whose amounts of money alternatively would continue to follow.
 if the competition gets roughly nine years ago we 've turned effective to go itself to what grave contacts.
 to an orthodox president this week 's most influential talk
--------------------------------------------------
the meaning of life is especially important.
 mr. andersson is serious about policies argued there are great business.
 rating the theme of this business has been a corry course.
 with one and vice president john greenberg got a stock split show the increasing earnings rate and the rating obtained by mr. drabinsky with mr. edelman who was declared.
 currently the central bank dorrance is pushing the eye 's possible chief financial officer could be able to recommend a hostile takeover attempt by laurence w. dorrance iii is booming 's investment banker and in new york about the article.
 deutsche

 

반응형