gpt4 book ai didi

python - 启用急切执行时不支持 tf.gradients。使用 tf.GradientTape 代替

转载 作者:行者123 更新时间:2023-12-04 15:57:29 25 4
gpt4 key购买 nike

from tensorflow.keras.applications import VGG16
from tensorflow.keras import backend as K

model = VGG16(weights='imagenet',
include_top=False)

layer_name = 'block3_conv1'
filter_index = 0

layer_output = model.get_layer(layer_name).output
loss = K.mean(layer_output[:, :, :, filter_index])

grads = K.gradients(loss, model.input)[0]
我无法执行 grads = K.gradients(loss, model.input)[0] ,它会产生一个错误: tf.gradients is not supported when eager execution is enabled. Use tf.GradientTape instead

最佳答案

您有两个选项也可以解决此错误:

  • .gradients 在 TF2 中被删除 - 按照此处的建议将梯度替换为 GradientTape https://github.com/tensorflow/tensorflow/issues/33135
  • 只需使用 tf1 的兼容模式禁用急切执行约束形式 tf2

  • 解决方案 2 的示例运行代码:
    from tensorflow.keras.applications import VGG16
    from tensorflow.keras import backend as K
    import tensorflow as tf
    tf.compat.v1.disable_eager_execution()


    model = VGG16(weights='imagenet',
    include_top=False)

    layer_name = 'block3_conv1'
    filter_index = 0

    layer_output = model.get_layer(layer_name).output
    loss = K.mean(layer_output[:, :, :, filter_index])

    grads = K.gradients(loss, model.input)[0]

    关于python - 启用急切执行时不支持 tf.gradients。使用 tf.GradientTape 代替,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66221788/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com