使用GradientTape()计算TensorFlow v.2中的Jacobian矩阵

时间:2019-05-05 16:42:53

标签: tensorflow machine-learning deep-learning lstm

我目前正在尝试在TensorFlow 2中使用GradientTape()batch_jacobian在训练循环中计算雅可比矩阵。可悲的是,我仅获得None值...

我当前的尝试如下:

for step, (batch_x, batch_y) in enumerate(train_data):

            with tf.GradientTape(persistent=True) as g:
                g.watch(batch_x)
                g.watch(batch_y)
                logits = self.retrained(batch_x, is_training=True)
                loss = lstm.cross_entropy_loss(logits, batch_y)
                acc = lstm.accuracy(logits, batch_y)
            avg_loss += loss
            avg_acc += acc

            gradients = g.gradient(loss, self.retrained.trainable_variables)
            J = g.batch_jacobian(logits, batch_x, experimental_use_pfor=False)
            print(J.numpy())
            self.optimizer.apply_gradients(zip(gradients, self.retrained.trainable_variables))

1 个答案:

答案 0 :(得分:1)

以下代码使用了tensorflow 2:

import tensorflow as tf

在这里,我创建了一个简单的神经网络,然后对它进行了部分推导。输入:

model = tf.keras.Sequential([
tf.keras.layers.Flatten(input_shape=(2,1)),
tf.keras.layers.Dense(3),
tf.keras.layers.Dense(2)])

现在,我使用GradientTape来计算Jacobian矩阵(对于输入:x = 2.0,y = 3.0):

x = tf.Variable([[2.0]])
y = tf.Variable([[3.0]])

with tf.GradientTape(persistent=True) as t:
    t.watch([x,y])
    z = tf.concat([x,y],1)
    f1 = model(z)[0][0]
    f2 = model(z)[0][1]


df1_dx = t.gradient(f1, x).numpy()
df1_dy = t.gradient(f1, y).numpy()
df2_dx = t.gradient(f2, x).numpy()
df2_dy = t.gradient(f2, y).numpy()

del t
print(df1_dx,df1_dy)
print(df2_dx,df2_dy)

请记住,神经网络的权重是随机初始化的,因此,雅可比矩阵或打印输出如下:

[[-0.832729]] [[-0.19699946]]
[[-0.5562407]] [[0.53551793]]

希望这很有帮助。 我试图解释如何更详细地计算函数(明确编写)和神经网络的雅可比矩阵here