Tensorflow 在急切模式下计算两个嵌入时发生梯度错误
当我尝试在急切模式下使用tensorflow重写时,出现以下错误:Tensorflow 在急切模式下计算两个嵌入时发生梯度错误,tensorflow,embedding,eager,dynet,Tensorflow,Embedding,Eager,Dynet,当我尝试在急切模式下使用tensorflow重写时,出现以下错误: 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 我试图定位错误并简化代码,然后发现当在一个动态图中以渴望模式计算两个
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
我试图定位错误并简化代码,然后发现当在一个动态图中以渴望模式计算两个嵌入时,就会发生错误
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)
在静态图形模式下添加两个嵌入时没有错误
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])
但当我在急切模式下运行以下代码时,出现了错误
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)
“急切”模式下的代码有什么问题?如何计算“急切”模式下的两个嵌入?这里发生了两件事:
嵌入层对象。这意味着每次调用loss
都会创建一个新的嵌入
,这可能不是您想要的。相反,您可能希望将代码重组为:
emb=tf.keras.layers.嵌入(10000,50)
emb2=tf.keras.layers.emb(10000,50)
def损失(y):
y=emb(tf常数(100))+emb2(tf常数(100))
返回tf.reduce\u和(y-y\u)
嵌入
对象(emb
和emb2
)关联的参数具有创建它们的对象的生命周期
希望这能有所帮助。感谢您更正我的代码,我将改用1.6