python - tensorflow 梯度为 None ('No gradients provided for any variable' )

标签 python tensorflow

当我运行以下脚本时,我收到错误消息“没有为任何变量提供渐变”。 “grads”变量是“None”值的列表。这么简单的脚本可能会出什么问题?

import tensorflow as tf
import numpy as np
tf.enable_eager_execution()


class Model(tf.keras.Model):
    def __init__(self):
        super(Model, self).__init__()
        self.layer = tf.keras.layers.Dense(4, activation = "linear")

    def call(self, x):
        y = self.layer(x)

        return y

model = Model()
model._set_inputs(tf.zeros((1, 5)))

optimizer = tf.train.GradientDescentOptimizer(0.5)


# gibberish data
x_train = np.array([[0, 0, 0, 0, 1]], dtype=np.float32)
y_train = np.array([[0.1, 0.1, 0.4, 0.4]])

y_pred = model.call(x_train)

with tf.GradientTape() as tape:
    loss = tf.losses.mean_squared_error(y_train, y_pred)

grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))

最佳答案

模型预测线

y_pred = model.call(x_train)

必须位于 with tf.GradientTape() as Tape: 范围内。

关于python - tensorflow 梯度为 None ('No gradients provided for any variable' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56307523/

相关文章:

python - Django一对多表单

tensorflow - 将 TensorBoard 2 中的 2 个图与 TensorFlow 2 合并

python - 从 NumPy 版本在 Tensorflow 中构建 Softmax 的导数

machine-learning - 如何正确输入形状或输入尺寸?

python - "No module named yum"centos7

python - 为什么在递归情况下出现 "Function not Defined"错误?

python - 将大型 numpy 数组与自身相乘时出现奇怪的结果

python - 从 __pycache__ 恢复

python - tensorflow Keras : Can `Conv2d` layers now accept multispectral images meaning bands greater than 3

python - Keras 自定义目标需要张量评估