0

我一直在玩耍并尝试在 TensorFlow 中实现我自己的损失函数,但我总是得到None渐变。为了重现这个问题,我现在将我的程序简化为一个最小的例子。我定义了一个非常简单的模型:

import tensorflow as tf

model = tf.keras.Sequential(
    [
        tf.keras.Input(shape=(3,), name="input"),
        tf.keras.layers.Dense(64, activation="relu", name="layer2"),
        tf.keras.layers.Dense(3, activation="softmax", name="output"),
    ]
)

然后定义一个非常简单(但可能没用)的损失函数:

def dummy_loss(x):
  return tf.reduce_sum(x)

def train(model, inputs, learning_rate):
  outputs = model(inputs)
  with tf.GradientTape() as t:
    current_loss = dummy_loss(outputs)
  temp = t.gradient(current_loss, model.trainable_weights)
train(model, tf.random.normal((10, 3)), learning_rate=0.001)

t.gradient(current_loss, model.trainable_weights)只给我一个None值列表,即[None, None, None, None]. 为什么会这样?我究竟做错了什么?我对 TensorFlow 的工作原理可能有误解吗?

4

1 回答 1

1

您需要在上下文中运行(即前向传递)计算图或模型,GradientTape以便可以记录模型中的所有操作:

  with tf.GradientTape() as t:
    outputs = model(inputs)  # This line should be within context manager
    current_loss = dummy_loss(outputs)
于 2020-08-08T11:45:31.067 回答