--28.순환신경망 - 분류.ipynb--
'''
He follows the cat. He loves the cat
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
10 11 12 13 10 14 12 13
각 단어마다 고유한 정수값 부여. 동일 단어에는 동일한 정수 매핑
단어의 의미나 크기와는 관련 없다.
일반적으로, 영어문장의 경우 모두 소문자로 바꾸고 구둣점등을 삭제한 다음 공백을 기준으로 단어 분리
이렇게 분리된 단어를 토큰(token) 이라 부릅니다.
하나의 샘플은 여러개의 토큰으로 이루어져 있고, '1개의 토큰'이 '하나의 타임 스텝'에 해당된다.
※ 간단한 문제라면 영어 말뭉치에서는 '토큰' 과 '단어'는같다고 보아도 무방하나, 한글은 다릅니다
한글은 조사, 어미변형등이 발달되어 있어서 단순히 공백으로 나누는 것만으로는 부족하기에
반드시 형태소 분석을 통해 토큰을 만들어야 합니다 → KoNLPy 사용
'''
None
'''
토큰에 할당되는 정수중 특별한 용도로 예약되어 있는 경우도 있다
ex)
0 - 패딩
1 - 문장의 시작
2 - 어휘 사전에 없는 토큰
'어휘사전' : 훈련세트에서 '고유한 단어'를 뽑아 만든 목록
'''
None
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
import tensorflow as tf
from tensorflow import keras
tf.keras.utils.set_random_seed(42) # 랜덤 시드 사용
tf.config.experimental.enable_op_determinism()
base_path = r'/content/drive/MyDrive/dataset'
from tensorflow.keras.datasets import imdb
(train_input, train_target), (test_input,test_target) = imdb.load_data(num_words=10000)
train_input.shape, test_input.shape
train_input.dtype # dtype('O') <- 데이터 원소가 Python Object 라는 뜻.
print(train_input[0]) # 첫번째 샘플 확인 => list!
len(train_input[0]) # 첫번째 리뷰의 단어개수
len(train_input[1]) # 두번째 리뷰의 단어개수
train_target[:20]
word_index = imdb.get_word_index()
type(word_index)
len(word_index)
print(word_index)
word_index['woods'] # 특정 단어 -> 인덱스
reverse_word_index = {value : key for key, value in word_index.items()}
print(reverse_word_index)
reverse_word_index[1408]
reverse_word_index[1] # 가장 많이 등장한 단어
def decode_review(encoded_review):
return ' '.join([reverse_word_index.get(i - 3, '?') for i in encoded_review])
i = 1
decoded_review = decode_review(train_input[1])
print(train_input[i]) # 토큰 인덱스 값
print(decoded_review) # decode 된 문자열
print(train_target[i])
(train_input, train_target), (test_input,test_target) = imdb.load_data(num_words=500)
from sklearn.model_selection import train_test_split
train_input, val_input, train_target, val_target = train_test_split(train_input, train_target, test_size=0.2, random_state=42)
train_input.shape, val_input.shape
lengths = np.array([len(x) for x in train_input])
np.min(lengths), np.max(lengths), np.mean(lengths), np.median(lengths)
plt.hist(lengths)
plt.xlabel('lengths')
plt.ylabel('frquency')
plt.show()
from tensorflow.keras.preprocessing.sequence import pad_sequences
len(train_input[0]), len(train_input[5])
max_len = 100
train_seq = pad_sequences(
sequences=train_input,
maxlen=max_len # 100개의 단어로 패딩
# 100개의 단어보다 많으면 잘려지고
# 100개의 단어보다 작으면 padding으로 채워진
)
train_seq.shape
len(train_seq[0]), len(train_seq[5])
print(train_seq[0])
print(train_input[0][:100]) # 원복 앞부분
print(train_input[0][-100:]) # 원본 뒷부분
print(train_seq[5]) # 원래 train_input[5] 는 96개 였다. 패딩('0')이 4개가 들어갔다.