张量流图构造中没有形状错误,但在图计算过程中出现形状不匹配错误

No shape error in tensorflow graph construction but getting shape mismatch error during graph computation

tensorflow图构造没有出现错误,但是我在tf.gradients的图计算过程中出现形状不匹配错误(我猜错误是在反向传播中)。

这是我得到的错误:

InvalidArgumentError (see above for traceback):
Input to reshape is a tensor with 16777216 values, but the requested shape has 4096
[[Node: gradients/truediv_grad/Reshape = Reshape[T=DT_FLOAT, Tshape=DT_INT32, _device="/job:localhost/replica:0/task:0 /device:GPU:0"](gradients/truediv_grad/Sum, gradients/truediv_grad/Shape)]]

我使用两种技术解决了这个问题:

1.Apparently 如果您正在创建自定义操作和渐变,您需要非常明确地使用 set_shapetf.reshape

向 tensorflow 提供形状信息

2.Also 当您使用将 op 和 grad 作为输入的 tf.register_gradient 注册梯度时,在链接梯度时需要小心,即 dy/dx = dy/dz*dz/dx。 假设 dy/dz 是我们创建的自定义梯度,dz/dx 是根据微分链规则的先前操作的梯度。

tf.register_gradient(Mygrad)
def Mygrad(op,grad):
*****do stuff with op.inputs and calculate custom grads say cust_grad or dy/dz****
return cust_grad*grad

我将其更改为以下内容:

tf.register_gradient(Mygrad)
def Mygrad(op,grad):
*****do stuff with op.inputs and calculate custom grads say cust_grad or dy/dz****
return tf.matmul(tf.reshape(cust_grad,[calculated_shape]),tf.reshape(grad,expeced_shape))