上下文管理器可以将两个两个相关的操作合二为一。例如:
with open('some_file', 'w') as opened_file:
opened_file.write('Hola!')
上面的代码等价于:
file = open('some_file', 'w')
try:
file.write('Hola!')
finally:
file.close()
def grad(model, inputs, targets):
with tf.GradientTape() as tape:
loss_value = loss(model, inputs, targets)
return loss_value, tape.gradient(loss_value, model.trainable_variables)
它相当于什么?