AttributeError: ‘tensorflow.python.framework.ops.EagerTensor‘ object has no attribute ‘_in_graph_mod

The reason for the bug is that the tf.keras optimizers apply gradients to variable objects (of type tf.Variable), while you are trying to apply gradients to tensors (of type tf.Tensor). Tensor objects are not mutable in TensorFlow, thus the optimizer cannot apply gradients to it.

img = tf.Variable(img)
opt = tf.optimizers.Adam(learning_rate=lr, decay = 1e-6)

for _ in range(epoch):
    with tf.GradientTape() as tape:
        tape.watch(img)
        y = model(img.value())[:, :, :, filter]
        loss = -tf.math.reduce_mean(y)

    grads = tape.gradient(loss, img)
    opt.apply_gradients(zip([grads], [img]))

Also, it is recommended to calculate the gradients outside the tape’s context. This is because keeping it in will lead to the tape tracking the gradient calculation itself, leading to higher memory usage. This is only desirable if you want to calculate higher-order gradients. Since you don’t need those, I have kept them outside.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据提供的引用内容,我可以给出以下回答: 在解决"AttributeError: module 'tensorflow.compat.v1' has no attribute 'contrib'"的问题时,您可以尝试以下方法: 1. 确保您使用的是兼容版本的TensorFlow。在TensorFlow 2.0及更高版本中,"contrib"模块已被移除。如果您的代码是基于旧版本的TensorFlow编写的,您可以尝试使用TensorFlow 1.x的兼容模式来解决此问题。可以使用以下代码导入TensorFlow 1.x的兼容模块: ```python import tensorflow.compat.v1 as tf tf.disable_v2_behavior() ``` 2. 检查您的TensorFlow安装是否完整。有时候,由于安装过程中的错误或中断,某些模块可能没有正确安装。您可以尝试重新安装TensorFlow来解决此问题。 关于"AttributeError: 'tensorflow.python.framework.ops.EagerTensor' object has no attribute 'device_buffer'"的问题,这个错误通常发生在使用TensorFlowEager Execution模式时。Eager Execution模式是TensorFlow 2.0默认的执行模式,它允许您立即执行操作并获得结果,而不需要构建计算图。 这个错误通常发生在尝试使用某些特定的TensorFlow操作时,这些操作可能不支持Eager Execution模式。为了解决这个问题,您可以尝试以下方法: 1. 将代码转换为使用TensorFlowGraph Execution模式。在Graph Execution模式下,您需要先构建计算图,然后再执行操作。可以使用以下代码将Eager Execution模式切换为Graph Execution模式: ```python import tensorflow as tf tf.compat.v1.disable_eager_execution() ``` 2. 检查您的代码中是否使用了不支持Eager Execution模式的操作。您可以查阅TensorFlow的官方文档或API文档,了解哪些操作不支持Eager Execution模式,并尝试使用其他替代操作或方法来解决问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值