首页 文章

如何在概念上考虑标记化单词和单词嵌入之间的关系?

提问于
浏览
0

我一直在使用JJ Allaire的指南在神经网络模型中使用文字嵌入进行文本处理(https://jjallaire.github.io/deep-learning-with-r-notebooks/notebooks/6.1-using-word-embeddings.nb.html) . 我很困惑模型如何将标记化的单词序列(x_train)与使用整个数据集定义的单词嵌入(而不仅仅是训练数据)相关联 . 有没有办法概念化单词标记如何映射到单词嵌入?否则,像'king'这样的单词如何映射到单词嵌入(例如使用Glove获得) . 我正在谈论这些代码块之间的关系:

#building model 
history <- model %>% fit(
 x_train, y_train,
 epochs = 20,
 batch_size = 32,
 validation_data = list(x_val, y_val)
)

#relating model to word embeddings
model <- keras_model_sequential() %>% 
layer_embedding(input_dim = max_words, output_dim = embedding_dim, 
              input_length = maxlen) %>% 
layer_flatten() %>% 
layer_dense(units = 32, activation = "relu") %>% 
layer_dense(units = 1, activation = "sigmoid")

get_layer(model, index = 1) %>% 
 set_weights(list(embedding_matrix)) %>% 
 freeze_weights()

如何将x_train中的标记化单词链接回embedding_matrix中的单词(特别是如果嵌入层是针对所有数据进行训练的话)?

2 回答

  • 2

    简而言之

    Conceptually, the keras::layer_embedding() takes a 2D matrix [samples, word_sequences], where the values are the integer word identifiers (word index), and replaces said value with their word vector, so that it becomes a 3D matrix [samples, word_sequences, embeddings] -- in other words, where the values are word vectors, not word identifiers. 粘贴的单词向量可以来自其他地方,如上例所示,也可以在训练期间随机初始化和更新 .


    简而言之

    您传递 keras::layer_embedding() 单词序列 . train_x 是2D矩阵,其中行是样本(文档),列是单词序列 . train_x 中的值是每个单词的整数标识符(单词索引),对应于它们在单独存储的单词列表(词汇表)中的位置 . 我们可以将 train_x 样式化为:

    enter image description here

    这里,值75对应于词汇表第75位的单词 .

    您传递给 keras::set_weights()embedding_matrix 是一个2D矩阵,其中的行与您的词汇表的行匹配 . 例如,第17行 embedding_matrix 上的值是词汇表第75位的单词向量 .

    因此,如果您正在使用预先训练的嵌入,如上例所示,那么 keras::layer_embedding() 只需将单词index替换为该行 embedding_matrix 中的单词向量 . 我们可以将操作风格化为

    for (x in 1:nrow(train_x)) {
      for (y in 1:ncol(train_x)) {
        train_x[x, y] <- embedding_matrix[train_x[x, y], ]
      }
    }
    

    因此,我们以3d矩阵(立方体)结束,我们可以将其设置为:

    enter image description here

  • 0

    标记器包含两个字典,一个是单词 - >索引,另一个是索引 - >单词 . 索引显示单词的频率,因此只计算单词出现在所有数据集中的次数,单词出现的次数越多,索引就越小 .

    Word Embedding类似于字典,它将单词或索引映射到向量,比方说我们想用128 dims向量表示一个单词 . 它可以在庞大的数据集上进行训练,您可以使用GloVe或Word2Vec(skip-gram模型) . 在Keras中,您可以轻松添加嵌入图层,嵌入图层可以学习如何通过矢量表示索引 .

    我认为您的训练数据和测试数据来自相同的分布,因此单词索引或嵌入向量应该相等,这就是我们在整个数据集上训练嵌入的原因 .

相关问题