简体   繁体   English

ValueError:没有为任何变量提供渐变:['Variable:0']

[英]ValueError: No gradients provided for any variable: ['Variable:0']

I am trying to prepare an example notebook for showing how to create adversarial examples in TensorFlow 2.x following this tutorial .我正在尝试准备一个示例笔记本,用于展示如何按照本教程在 TensorFlow 2.x 中创建对抗性示例。

I have been able to port some of it but I am now stuck with a weird problem of ValueError: No gradients provided for any variable: ['Variable:0'].我已经能够移植其中的一些,但我现在遇到了一个奇怪的ValueError: No gradients provided for any variable: ['Variable:0']. and can't seem to figure out why.并且似乎无法弄清楚为什么。

Here's how I load the image for which I am trying to create an adversary:以下是我加载要创建对手的图像的方式:

def preprocess_image(image_pixels):
    # image_pixels = preprocess_input(image_pixels)
    image_pixels = cv2.resize(image_pixels, (224, 224))
    image_pixels = np.expand_dims(image_pixels, axis=0)

    return image_pixels

# Load and preprocess image but a but without any preprocess_input
sample_image = show_image("pig.jpg")
preprocessed_image = preprocess_image(sample_image)

# Initialize the perturbation quantity
image_tensor = tf.convert_to_tensor(preprocessed_image, dtype=tf.float32)
delta = tf.Variable(tf.zeros_like(image_tensor), trainable=True)

Here's how my training loop looks like -这是我的训练循环的样子 -

for t in range(30):
    inp = preprocess_input(image_tensor + delta)
    with tf.GradientTape() as tape:
        tape.watch(delta)
        pred = resnet50(inp)
        loss = - scc_loss(
                tf.convert_to_tensor([341]),
                pred
            )
        if t % 5 == 0:
            print(t, loss.numpy())

        # Get the gradients
        gradients = tape.gradient(loss, delta)

        # Update the weights
        optimizer.apply_gradients([(gradients, delta)])

        # Clip so that the delta values are within [0,1]
        delta.assign(clip_eps(delta))

where, preprocess_input is tf.keras.applications.resnet50 and my model is a pre-trained ResNet50.其中, preprocess_inputtf.keras.applications.resnet50而我的 model 是预训练的 ResNet50。 The optimizer is defined as optimizer = tf.keras.optimizers.SGD(learning_rate=1e-1) .优化器定义为optimizer = tf.keras.optimizers.SGD(learning_rate=1e-1) Error is listed below:错误如下:

0 -0.00041249825
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-284-174284e3aea4> in <module>()
     15 
     16         # Update the weights
---> 17         optimizer.apply_gradients([(gradients, delta)])
     18 
     19         # Clip so that the delta values are within [0,1]

1 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py in apply_gradients(self, grads_and_vars, name, experimental_aggregate_gradients)
    472       ValueError: If none of the variables have gradients.
    473     """
--> 474     grads_and_vars = _filter_grads(grads_and_vars)
    475     var_list = [v for (_, v) in grads_and_vars]
    476 

/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py in _filter_grads(grads_and_vars)
   1201   if not filtered:
   1202     raise ValueError("No gradients provided for any variable: %s." %
-> 1203                      ([v.name for _, v in grads_and_vars],))
   1204   if vars_with_empty_grads:
   1205     logging.warning(

ValueError: No gradients provided for any variable: ['Variable:0'].

Here's where the entire Colab notebook can be found.这里可以找到整个 Colab 笔记本。 Appreciate any help/pointers.感谢任何帮助/指针。

Your delta (the trainable variable) is not participating in any operation inside the tape.您的delta (可训练变量)不参与磁带内的任何操作。 It can't be watched if it is not doing anything.如果它不做任何事情,它就无法被观看。

To have a better performance, since you're using eager execution, use training=False when you use a model that is not supposed to be updated (the tape will watch every trainable kernel in the models unless you do this, any batch normalization and dropout will also behave different) -- Since you said you're using a ResNet for preprocessing, I assume this ResNet should use training=False .为了获得更好的性能,由于您使用的是急切执行,因此当您使用不应更新的 model 时使用training=False (磁带将监视模型中每个可训练的 kernel 除非您这样做,任何批量标准化和dropout 也会表现不同)——既然你说你使用 ResNet 进行预处理,我假设这个 ResNet 应该使用training=False

for t in range(30):
    with tf.GradientTape() as tape:
        tape.watch(delta)
        inp = preprocess_input(image_tensor + delta)
        pred = resnet50(inp)
        loss = - scc_loss(
                tf.convert_to_tensor([341]),
                pred
            )
        if t % 5 == 0:
            print(t, loss.numpy())

#these things should not be inside the tape:
    # Get the gradients
    gradients = tape.gradient(loss, delta)

    # Update the weights
    optimizer.apply_gradients([(gradients, delta)])

    # Clip so that the delta values are within [0,1]
    delta.assign(clip_eps(delta))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TensorFlow 错误:ValueError:没有为任何变量提供梯度 - TensorFlow Error: ValueError: No gradients provided for any variable TF Keras - ValueError:没有为任何变量提供梯度 - TF Keras - ValueError: No gradients provided for any variable Keras ValueError:没有为任何变量提供梯度 - Keras ValueError: No gradients provided for any variable ValueError:没有为策略梯度中的任何变量提供梯度 - ValueError: No gradients provided for any variable in policy gradient Tensorflow ValueError:没有为任何变量提供梯度: - Tensorflow ValueError: No gradients provided for any variable: 训练 CNN:ValueError:没有为任何变量提供梯度 - Training CNN: ValueError: No gradients provided for any variable Adam 优化器:ValueError:没有为任何变量提供梯度 - Adam optimizer: ValueError: No gradients provided for any variable ValueError:没有为任何变量提供梯度 - Tensorflow 2.0 - ValueError: No gradients provided for any variable - Tensorflow 2.0 Tensorflow | ValueError:没有为任何变量提供梯度 - Tensorflow | ValueError: No gradients provided for any variable Python,Tensorflow ValueError:没有为任何变量提供梯度 - Python, Tensorflow ValueError: No gradients provided for any variable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM