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

标签 keras embedding

我正在关注此页面上的示例: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'])
    

关于keras - 嵌入层,我可以更改模型管道中经过训练的嵌入层的值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48486135/

相关文章:

xml - 在 SVG 中嵌入 SVG?

rdf - 具有可选属性的 JSON-LD 框架?

c++ - 导入 ctype;在 C++ 应用程序中嵌入 python

python - yolo3 Keras 中 Lambda 层的替代方案

python - TimeDistributed(BatchNormalization) 与 BatchNormalization

python - 如何在不同的conda环境下设置不同的keras后端

python - 基于中间层输出的 Keras 指标

c++ - 使用Visual Studio在C++中嵌入Julia

python - 语义分割训练时 Keras 损失为 NaN

c++ - 适合在线嵌入的SVM库