keras - 嵌入层,我可以改变模型管道中经过训练的嵌入层的值吗?

keras - embedding layer, can I alter values of a trained embedding layer in the pipeline of a model?

我正在关注此页面上的示例:https://machinelearningmastery.com/use-word-embedding-layers-deep-learning-keras/

使用嵌入层在数据上训练词嵌入,如下所示:

model = Sequential()
model.add(Embedding(100, 8, input_length=max_length))
model.add(Flatten())
model.add(Dense(1, activation='sigmoid'))
# compile the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc'])
# summarize the model
print(model.summary())

该模型首先从数据中学习词嵌入,为每个词创建一个 8 维向量。

我想做的是,在学习了这个嵌入之后,我想通过在每个向量的末尾添加两个维度来改变矩阵(或每个单词的向量)。我将有另一个过程来计算这两个维度的值。

有什么办法可以做到吗?

非常感谢

是的 - 这是可能的。尝试使用以下程序执行此操作:

  1. 提取权重矩阵:

    weight_matrix = model.layers[0].get_weights()[0] # Matrix shape (100, 8).
    
  2. 附加你的载体:

    new_weight_matrix = your_append(weight_matrix)
    # Be sure that new_weight_matrix has shape of (100, 10)
    
  3. 构建模型的调整副本:

    new_model = Sequential()
    new_model.add(Embedding(100, 10, input_length=max_length)) # Notice a change
    new_model.add(Flatten())
    new_model.add(Dense(1, activation='sigmoid'))
    
  4. (可选)冻结层:如果您想冻结嵌入集:

    new_model = Sequential()
    new_model.add(Embedding(100, 10, input_length=max_length
        trainable=False)) # Notice a change
    new_model.add(Flatten())
    new_model.add(Dense(1, activation='sigmoid'))
    
  5. 编译新模型:

    new_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc'])