Skip to main content
 首页 » 编程设计

python之TensorFlow之跨后处理分配操作的梯度

2025年02月15日33JeffreyZhao

如果在网络的前向传播部分使用权重张量之后对权重张量应用赋值操作,TensorFlow 的反向传播在确定梯度时是否考虑赋值操作对于那个重量?例如,如果我有

weights = tf.Variable(...) 
bias = tf.Variable(...) 
output = tf.tanh(tf.matmul(weights, input) + bias) 
weight_assign_op = weights.assign(weights + 1.0) 
with tf.control_dependencies(weight_assign_op): 
    output2 = tf.identity(output) 

计算输出,然后对权重进行更改。如果输出随后用于计算损失和梯度以更新变量,那么在创建梯度时是否会考虑到 weights 的变化?也就是说,weights 的梯度是 old_weights + 1.0 的正确梯度,还是它们仍然是 old_weights 的梯度,当应用于新的权重不一定是梯度下降的“正确”梯度?

请您参考如下方法:

我最终通过实验对其进行了测试。梯度计算确实考虑了赋值操作。我使用下面的代码进行测试。运行它会产生正梯度。注释掉权重分配操作线和控制依赖线会导致负梯度。这是因为梯度要么被考虑用于 0.0 的原始起始值权重,要么被分配 2.0 后的更新权重。

import tensorflow as tf 
 
data = [[1.0], [2.0], [3.0]] 
labels = [[1.0], [2.1], [2.9]] 
 
input_data = tf.placeholder(dtype=tf.float32, shape=[3, 1]) 
input_labels = tf.placeholder(dtype=tf.float32, shape=[3, 1]) 
weights = tf.Variable(tf.constant([0.0])) 
bias = tf.Variable(tf.constant([0.0])) 
output = (weights * input_data) + bias 
weight_assign_op = weights.assign(tf.constant([2.0])) 
with tf.control_dependencies([weight_assign_op]): 
    output = tf.identity(output) 
loss = tf.reduce_sum(tf.norm(output - input_labels)) 
weight_gradient = tf.gradients(loss, weights) 
initialize_op = tf.global_variables_initializer() 
 
session = tf.Session() 
session.run([initialize_op]) 
weight_gradient_value = session.run([weight_gradient], feed_dict={input_data: data, input_labels: labels}) 
print(weight_gradient_value)