Embedding 层

使用 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 中未找到的词将为全零。 embedding_matrix[i] = embedding_vector
return embedding_matrix
使用 Keras 构建语言建模的循环神经网络(RNN)

Passons à la pratique !

使用 Keras 构建语言建模的循环神经网络(RNN)

Preparing Video For Download...