埋め込み(Embedding)層

Kerasで学ぶ言語モデリングのためのRecurrent Neural Networks (RNNs)

David Cecchini

Data Scientist

なぜ埋め込みか

利点:

  • 次元削減
    one_hot = np.array((N, 100000))
    embedd = np.array((N, 300))
    
  • 高密度表現
    • king - man + woman = queen
  • 転移学習

欠点:

  • 学習パラメータが多く、学習に時間がかかる
Kerasで学ぶ言語モデリングのためのRecurrent Neural Networks (RNNs)

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で学ぶ言語モデリングのためのRecurrent Neural Networks (RNNs)

転移学習

言語モデルの転移学習

  • 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で学ぶ言語モデリングのためのRecurrent Neural Networks (RNNs)

GloVe 事前学習ベクトルの使用

公式サイト: https://nlp.stanford.edu/projects/glove/

# Get hte GloVE vectors
def get_glove_vectors(filename="glove.6B.300d.txt"):
    # Get all word vectors from pre-trained model
    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で学ぶ言語モデリングのためのRecurrent Neural Networks (RNNs)

特定タスク向けの GloVe 利用

# Filter GloVE vectors to specific task
def filter_glove(vocabulary_dict, glove_dict, wordvec_dim=300):

# Create a matrix to store the vectors 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: # words not found in the glove_dict will be all-zeros. embedding_matrix[i] = embedding_vector
return embedding_matrix
Kerasで学ぶ言語モデリングのためのRecurrent Neural Networks (RNNs)

Let's practice!

Kerasで学ぶ言語モデリングのためのRecurrent Neural Networks (RNNs)

Preparing Video For Download...