【问题标题】:keras - embedding layer, can I alter values of a trained embedding layer in the pipeline of a model?keras - 嵌入层,我可以更改模型管道中经过训练的嵌入层的值吗?
【发布时间】:2018-07-07 06:08:16
【问题描述】:

我正在关注此页面上的示例: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 维向量。

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

有没有我可以做到的?

在此先感谢

【问题讨论】:

    标签: keras embedding


    【解决方案1】:

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

    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'])
      

    【讨论】:

    • 谢谢。这一切都必须在之前的模型调用“编译”并拟合数据之后发生吗?
    • 你需要重新调整你的模型——因为它的架构发生了变化。
    • 谢谢 我明白改装...我的意思是以前的模型,我想它必须安装才能获得权重,对吧?然后我在修改矩阵后使用你的代码重新拟合模型
    • 对。你的方法似乎是合理的。您可以对其进行冻结和不冻结层测试。
    • 嗨 - 我的回答是否有帮助 - 如果是的话,我会很感激接受和支持 :)
    猜你喜欢
    • 2018-12-21
    • 2020-01-16
    • 1970-01-01
    • 2020-09-03
    • 2018-12-16
    • 1970-01-01
    • 2017-07-07
    • 2019-06-11
    • 1970-01-01
    相关资源
    最近更新 更多