我一直在玩耍并尝试在 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 的工作原理可能有误解吗?