Embedding 層

使用 Keras 建立語言模型的循環神經網路(RNN)

David Cecchini

Data Scientist

為何使用 embeddings

優點:

  • 降低維度
    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/

# 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 建立語言模型的循環神經網路(RNN)

將 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 建立語言模型的循環神經網路(RNN)

一起來練習吧!

使用 Keras 建立語言模型的循環神經網路(RNN)

Preparing Video For Download...