【发布时间】:2021-01-22 03:40:57
【问题描述】:
在以下取自Keras documentation 的示例中,我想了解grads 是如何计算的。梯度grads 是否对应于使用批处理(x_batch_train, y_batch_train) 计算的平均梯度?换句话说,算法是否使用小批量中的每个样本计算每个变量的梯度,然后平均得到grads?
for epoch in range(epochs):
print("\nStart of epoch %d" % (epoch,))
# Iterate over the batches of the dataset.
for step, (x_batch_train, y_batch_train) in enumerate(train_dataset):
# Open a GradientTape to record the operations run
# during the forward pass, which enables auto-differentiation.
with tf.GradientTape() as tape:
# Run the forward pass of the layer.
# The operations that the layer applies
# to its inputs are going to be recorded
# on the GradientTape.
logits = model(x_batch_train, training=True) # Logits for this minibatch
# Compute the loss value for this minibatch.
loss_value = loss_fn(y_batch_train, logits)
# Use the gradient tape to automatically retrieve
# the gradients of the trainable variables with respect to the loss.
grads = tape.gradient(loss_value, model.trainable_weights)
# Run one step of gradient descent by updating
# the value of the variables to minimize the loss.
optimizer.apply_gradients(zip(grads, model.trainable_weights))
【问题讨论】:
标签: tensorflow keras neural-network tensorflow2.0 gradient-descent