我对计算梯度很感兴趣。Tensorflow 中 keras 模型的输入。我知道以前可以通过构建图表并使用tf.gradients
. 例如这里。但是,我想在急切模式下进行试验时(可能使用GradientTape
)来实现这一点。具体来说,如果我的网络有两个输入(x, y)
,并预测(u, v, p)
计算,例如,du/dx
用于损失。
下面的代码片段,完整的代码在这个要点。
model = tf.keras.Sequential([
tf.keras.layers.Dense(20, activation=tf.nn.relu, input_shape=(2,)), # input shape required
tf.keras.layers.Dense(20, activation=tf.nn.relu),
tf.keras.layers.Dense(20, activation=tf.nn.relu),
tf.keras.layers.Dense(20, activation=tf.nn.relu),
tf.keras.layers.Dense(3)
])
def loss(model: tf.keras.Model, inputs, outputs):
u_true, v_true = outputs[:, 0], outputs[:, 1]
prediction = model(inputs)
u_pred, v_pred = prediction[:, 0], prediction[:, 1]
loss_value = tf.reduce_mean(tf.square(u_true - u_pred)) + \
tf.reduce_mean(tf.square(v_true - v_pred))
return loss_value, u_pred, v_pred
def grad(model: tf.keras.Model, inputs, outputs):
"""
:param inputs: (batch_size, 2) -> x, y
:param outputs: (batch_size, 3) -> vx, vy, p
:return:
"""
with tf.GradientTape() as tape:
loss_value, u_pred, v_pred = loss(model, inputs, outputs)
# AttributeError: 'DeferredTensor' object has no attribute '_id'
print(tape.gradient(u_pred, model.input))
grads = tape.gradient(loss_value, model.trainable_variables)
return loss_value, grads
我尝试了一些东西,例如,tape.gradient(u_pred, model.input)
或者tape.gradient(model.output, model.input)
但是这些抛出:
AttributeError: 'DeferredTensor' object has no attribute '_id'
有没有办法在急切模式下实现这一点,如果有,怎么做?