임베딩 레이어

Keras로 배우는 언어 모델링을 위한 순환 신경망(RNN)

David Cecchini

Data Scientist

임베딩을 쓰는 이유

장점:

  • 차원 축소
    one_hot = np.array((N, 100000))
    embedd = np.array((N, 300))
    
  • 밀집 표현
    • king - man + woman = queen
  • 전이 학습

단점:

  • 학습할 매개변수가 많아 학습이 오래 걸림
Keras로 배우는 언어 모델링을 위한 순환 신경망(RNN)

Keras에서의 사용 방법

Keras에서:

from tensorflow.keras.layers import Embedding

model = Sequential() # 첫 번째 레이어로 사용 model.add(Embedding(input_dim=100000,
output_dim=300,
trainable=True,
embeddings_initializer=None,
input_length=120))
Keras로 배우는 언어 모델링을 위한 순환 신경망(RNN)

전이 학습

언어 모델 전이 학습

  • GloVE
  • word2vec
  • BERT

Keras에서:

from tensorflow.keras.initializers import Constant

model.add(Embedding(input_dim=vocabulary_size, output_dim=embedding_dim,
embeddings_initializer=Constant(pre_trained_vectors))
Keras로 배우는 언어 모델링을 위한 순환 신경망(RNN)

GloVE 사전학습 벡터 사용

공식 사이트: https://nlp.stanford.edu/projects/glove/

# GloVE 벡터 가져오기
def get_glove_vectors(filename="glove.6B.300d.txt"):
    # 사전학습된 모델에서 모든 단어 벡터 로드
    glove_vector_dict = {}
    with open(filename) as f:
        for line in f:

values = line.split()
word = values[0] coefs = values[1:]
glove_vector_dict[word] = np.asarray(coefs, dtype='float32')
return glove_vector_dict
Keras로 배우는 언어 모델링을 위한 순환 신경망(RNN)

특정 작업에 GloVE 적용

# 작업에 맞게 GloVE 벡터 필터링
def filter_glove(vocabulary_dict, glove_dict, wordvec_dim=300):

# 벡터를 담을 행렬 생성 embedding_matrix = np.zeros((len(vocabulary_dict) + 1, wordvec_dim))
for word, i in vocabulary_dict.items(): embedding_vector = glove_dict.get(word)
if embedding_vector is not None: # glove_dict에 없는 단어는 모두 0으로 남습니다. embedding_matrix[i] = embedding_vector
return embedding_matrix
Keras로 배우는 언어 모델링을 위한 순환 신경망(RNN)

연습해 봅시다!

Keras로 배우는 언어 모델링을 위한 순환 신경망(RNN)

Preparing Video For Download...