使用tf.GradientTape()wrt输入的梯度为无(Tensorflow 2.4)

2024-04-28 23:23:17 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的模型。Im使用Tensorflow 2.4.1

model = tf.keras.Sequential([
    tf.keras.layers.Embedding(input_dim=1000,
                              output_dim=64,
                              name='embedding',
                              mask_zero=True),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),
    tf.keras.layers.Dense(16, activation='relu'),
    tf.keras.layers.Dense(4, name='logits')
])

metrics = [tf.keras.metrics.SparseCategoricalAccuracy()]

# compile the model
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=metrics)

当我运行下面的代码时,我得到None作为gradient wrt输入

def compute_gradients(t, target_class_idx):
    with tf.GradientTape() as tape:
        tape.watch(t)
        logits = model(t)
        probs = tf.nn.softmax(logits, axis=-1)[:, target_class_idx]
    grads = tape.gradient(probs, t)
    return grads

这是一个示例输入和调用

sample_tensor = tf.random.uniform(shape=(1, 50))

path_gradients = compute_gradients(
    t=sample_tensor,
    target_class_idx=0)

print(path_gradients)

None

我做错了什么

谢谢


Tags: nametruetargetmodellayerstfclasskeras