【问题标题】:gradient using tf.GradientTape() wrt inputs is None (Tensorflow 2.4)使用 tf.GradientTape() wrt 输入的梯度为无(Tensorflow 2.4)
【发布时间】:2021-07-22 02:04:51
【问题描述】:

这是我的模型。我正在使用 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 作为渐变 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

我做错了什么?

谢谢

【问题讨论】:

    标签: python tensorflow gradienttape


    【解决方案1】:

    TensorFlow 中的Embedding 层不可微。 来源:https://github.com/keras-team/keras/issues/12270

    【讨论】:

      猜你喜欢
      • 2020-03-27
      • 1970-01-01
      • 1970-01-01
      • 2020-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-14
      • 2018-02-20
      相关资源
      最近更新 更多