不,代码行为正确,你有一个理论问题。
t_mult 是 im1 和 im2 的元素乘积。显然,δ(im1 * im2)/δim2 确实会产生 im1,所以tf.gradiens( t_mult, t_im2 ) 将产生im1。
当您应用 tf.reduce_sum() 时,基本上您将沿轴的所有元素相加,这不会改变,因为 tf.gradiens() 只取 偏导数 和全和随im1 的每个元素而变化。因此grad = tf.gradients( t_corr, t_im2 ) 也产生im1。
-
然而,当你占领广场时,情况就会发生变化。由于您要对沿轴的元素总和进行平方,因此它们之间会有交互作用,您不仅会得到平方项,还会得到每对的叉积。这会在正方形上添加一堆线性项,当你取导时,你不仅会得到 δx2/ δx = 2x 但还有很多其他与元素之间相互作用的术语。
李>
真正的问题在于这一行:# Euclidiean Norm: 1/2 ||t_corr||^2 = df/im0 = im1 因为Euclidean norm 的真正公式是 √Σxi子>2。但这也不会产生干净的im0,因为如果您取平方根,您将再次进行交互。如果你想找回im0,你需要计算loss1 = tf.reduce_sum( 0.5 * tf.square( t_mult ), axis = 1 ),一旦你得到导数,你必须除以另一个图像的平方。不确定您要实现什么,但此代码(已测试):
from __future__ import print_function
import tensorflow as tf
import numpy as np
im1 = np.ascontiguousarray(np.arange(36).reshape((1,3,3,4))).astype(np.float32)
t_im1 = tf.constant( im1 )
im2 = np.ascontiguousarray(np.arange(36,72).reshape((1,3,3,4))).astype(np.float32)
t_im2 = tf.constant( im2 )
t_mult = tf.multiply( t_im1, t_im2 )
t_corr = tf.reduce_sum(t_mult, axis=[1])
grad = tf.gradients( ys=t_corr, xs= t_im2, name = "grad" )
# Euclidiean Norm: 0.5 * sqrt( sum( ||t_mult||^2 ) ) = d f/d im1 = im2
loss1 = tf.reduce_sum( 0.5 * tf.square( t_mult ), axis = 1 )
grad_norm = tf.gradients( ys = loss1, xs = t_im1, name = "grad_norm" ) / t_im2 ** 2
with tf.Session() as sess:
fetch = [ t_im1, grad[ 0 ], grad_norm[ 0 ] ]
res = sess.run( fetch )
for idx, v in enumerate( res ):
print( " =========================")
print( fetch[ idx ].name )
print()
print( v )
将输出:
==========================
常数:0
[[[[ 0.1.2.3.]
[ 4. 5. 6. 7.]
[8. 9. 10. 11.]]
[[12. 13. 14. 15.]
[16. 17. 18. 19.]
[20. 21. 22. 23.]]
[[24. 25. 26. 27.]
[28. 29. 30. 31.]
[32. 33. 34. 35.]]]]
==========================
毕业/Mul_grad/Mul_1:0
[[[[ 0.1.2.3.]
[ 4. 5. 6. 7.]
[8. 9. 10. 11.]]
[[12. 13. 14. 15.]
[16. 17. 18. 19.]
[20. 21. 22. 23.]]
[[24. 25. 26. 27.]
[28. 29. 30. 31.]
[32. 33. 34. 35.]]]]
==========================
跨步切片:0
[[[[ 0.1.2.3.]
[ 4. 5. 6. 7.]
[8. 9. 10. 11.]]
[[12. 13. 14. 15.]
[16. 17. 18. 19.]
[20. 21. 22. 23.]]
[[24. 25. 26. 27.]
[28. 29. 30. 31.]
[32. 33. 34. 35.]]]]