【问题标题】:Gradient error occurred when calculate two embeddings on eager mode在 Eager 模式下计算两个嵌入时发生梯度错误
【发布时间】:2018-04-02 03:33:49
【问题描述】:

当我尝试在 Eager 模式下使用 tensorflow 重写 dynet project 时,出现以下错误:

tensorflow.python.framework.errors_impl.InvalidArgumentError: cannot compute ConcatV2 as input #1 was expected to be a float tensor but is a int32 tensor [Op:ConcatV2] name: concat

我试图定位错误并简化代码,然后发现在eager模式下在一个动态图中计算两个embedding时,会出现错误。

在静态图模式下添加两个embedding没有错误。

with tf.Graph().as_default():
    emb = tf.keras.layers.Embedding(10000, 50)
    emb2 = tf.keras.layers.Embedding(10000, 50)
    y_ = emb(tf.constant(100)) + emb2(tf.constant(100))
    y = tf.ones((1, 50))
    loss = tf.reduce_sum(y - y_)
    optimizer = tf.train.MomentumOptimizer(0.2,0.5).minimize(loss)
    init = tf.global_variables_initializer()
    with tf.Session() as sess:
        sess.run(init)
       sess.run(fetches=[loss, optimizer])

但是当我在 Eager 模式下运行以下代码时,出现了错误。

tfe.enable_eager_execution()

def loss(y):
    emb = tf.keras.layers.Embedding(10000,50)
    emb2 = tf.keras.layers.Embedding(10000,50)
    y_ = emb(tf.constant(100)) + emb2(tf.constant(100))
    return tf.reduce_sum(y - y_)

y = tf.ones((1, 50))
grads = tfe.implicit_gradients(loss)(y)
tf.train.MomentumOptimizer(0.2, 0.5).apply_gradients(grads)

Eager 模式下的代码有什么问题,如何计算 Eager 模式下的两个嵌入?

【问题讨论】:

    标签: tensorflow embedding eager dynet


    【解决方案1】:

    这里发生了两件事:

    1. 我认为这是一个因急切执行而引入的错误,我为此提交了https://github.com/tensorflow/tensorflow/issues/18180。我认为这在 1.6 版中不存在,所以也许你可以在此期间尝试一下。

    2. 也就是说,我注意到您在损失函数中定义了一个Embedding 层对象。这意味着每次调用loss 都会创建一个新的Embedding,这可能不是您想要的。相反,您可能希望将代码重组为:

      emb = tf.keras.layers.Embedding(10000,50) emb2 = tf.keras.layers.Embedding(10000,50)

      定义损失(y): y_ = emb(tf.constant(100)) + emb2(tf.constant(100)) 返回 tf.reduce_sum(y - y_)

    通过急切执行,参数所有权更加“Pythonic”,因为与Embedding 对象(embemb2)关联的参数具有创建它们的对象的生命周期。

    希望对您有所帮助。

    【讨论】:

    • 感谢您更正我的代码,我将尝试改用 1.6
    猜你喜欢
    • 2019-11-04
    • 1970-01-01
    • 2018-11-17
    • 2022-10-23
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    相关资源
    最近更新 更多