활동내용
1) 문자 단위 RNN 언어 모델
이전 시점의 예측 문자를 다음 시점의 입력으로 사용하는 문자 단위 RNN 언어 모델을 구현해봅시다. 앞서 배운 단어 단위 RNN 언어 모델과 다른 점은 단어 단위가 아니라 문자 단위를 입, 출력으로 사용하므로 임베딩층(embedding layer)을 여기서는 사용하지 않겠습니다. 여기서는 언어 모델의 훈련 과정과 테스트 과정의 차이를 이해하는데 집중합니다.
다운로드 링크 : http://www.gutenberg.org/files/11/11-0.txt
고전 소설들은 저작권에 보호받지 않으므로 무료로 다운받을 수 있습니다. 위의 링크에서 '이상한 나라의 앨리스(Alice’s Adventures in Wonderland)'라는 소설을 다운로드 합니다.
데이터를 로드하고 특수문자를 제거하고 단어를 소문자화하는 간단한 전처리를 수행합니다.
import numpyas np
import urllib.request
from tensorflow.keras.utilsimport to_categorical
# 데이터 로드
urllib.request.urlretrieve("http://www.gutenberg.org/files/11/11-0.txt", filename="11-0.txt")
f = open('11-0.txt', 'rb')
sentences = []
for sentencein f: # 데이터로부터 한 줄씩 읽는다.
sentence = sentence.strip() # strip()을 통해 \r, \n을 제거한다.
sentence = sentence.lower() # 소문자화.
sentence = sentence.decode('ascii', 'ignore') # \xe2\x80\x99 등과 같은 바이트 열 제거
if len(sentence) > 0:
sentences.append(sentence)
f.close()
전처리가 수행된 결과가 리스트에 저장되었습니다. 리스트에서 5개의 원소만 출력해보겠습니다.
sentences[:5]
['the project gutenberg ebook of alices adventures in wonderland, by lewis carroll',
'this ebook is for the use of anyone anywhere in the united states and',
'most other parts of the world at no cost and with almost no restrictions',
'whatsoever. you may copy it, give it away or re-use it under the terms',
'of the project gutenberg license included with this ebook or online at']
리스트의 원소는 문자열로 구성되어져 있는데 의미있게 문장 토큰화가 된 상태는 아닙니다. 이를 하나의 문자열로 통합하겠습니다.
total_data = ' '.join(sentences)
print('문자열의 길이 또는 총 문자의 개수: %d' % len(total_data))
문자열의 길이 또는 총 문자의 개수: 159484
하나의 문자열로 통합되었고, 문자열의 길이는 약 15만 9천입니다. 일부 출력해보겠습니다.
print(total_data[:200])
the project gutenberg ebook of alices adventuresin wonderland,by lewis carrollthis ebookisfor the use of anyone anywherein the united statesand most other parts of the world at no costandwith
이 문자열로부터 문자 집합을 만들겠습니다. 기존에는 중복을 제거한 단어들의 모음인 단어 집합(vocabulary)을 만들었으나, 이번에 만들 집합은 단어 집합이 아니라 문자 집합입니다.
char_vocab = sorted(list(set(total_data)))
vocab_size = len(char_vocab)
print ('문자 집합의 크기 : {}'.format(vocab_size))
문자 집합의 크기 : 56