Python 为什么在下面的函数中梯度是不相连的?
我正在实施一个客户操作,必须计算其梯度。功能如下:Python 为什么在下面的函数中梯度是不相连的?,python,keras,gradient,tensorflow2.0,gradienttape,Python,Keras,Gradient,Tensorflow2.0,Gradienttape,我正在实施一个客户操作,必须计算其梯度。功能如下: def difference(prod,box): result = tf.Variable(tf.zeros((prod.shape[0],box.shape[1]),dtype=tf.float16)) for i in tf.range(0,prod.shape[0]): for j in tf.range(0,box.shape[1]): result[i,j].assign((t
def difference(prod,box):
result = tf.Variable(tf.zeros((prod.shape[0],box.shape[1]),dtype=tf.float16))
for i in tf.range(0,prod.shape[0]):
for j in tf.range(0,box.shape[1]):
result[i,j].assign((tf.reduce_prod(box[:,j])-tf.reduce_prod(prod[i,:]))/tf.reduce_prod(box[:,j]))
return result
我无法计算有关box的渐变,tape.gradient()返回的是None,下面是我为计算渐变而编写的代码
prod = tf.constant([[3,4,5],[4,5,6],[1,3,3]],dtype=tf.float16)
box = tf.Variable([[4,5],[5,6],[5,7]],dtype=tf.float16)
with tf.GradientTape() as tape:
tape.watch(box)
loss = difference(prod,box)
print(tape.gradient(loss,box))
我无法找到未连接渐变的原因。是结果变量导致的吗?请建议另一种实现方式。是的,为了计算梯度,我们需要对变量进行一组(可微)运算 您应该根据2个输入张量重新编写
差异。我认为(尽管我很高兴地承认我不是100%确定!)正是使用“赋值”使渐变带倒下
也许是这样的:
def差异(产品、包装箱):
框体红色=tf。减少生产(框体,轴=0)
生产线红色=tf。减少生产线(生产线,轴=1)
返回(tf.expand\u dims(框红色,0)-tf.expand\u dims(产品红色,1))/tf.expand\u dims(框红色,0)
将得到您想要的结果我想最好避免使用新变量来跟踪梯度。