我试图为张量流定义新的运算量和梯度。 我找到了以下链接: https://gist.github.com/harpone/3453185b41d8d985356cbe5e57d67342
只要输入维度等于输出维度,它就可以正常工作。 我要发送2个大小为(1,)的参数,每个参数的操作大小为N=(65536,),每个参数的梯度都是相同的,N=(65536,)。在
我的输入是:x(1,),y(1,)
输出:
op N=(65536,)
grad of x: N=(65536,)
grad of y: N=(65536,)
或者 输入par(2,) 输出梯度N=(65536,2)
在训练中,我将使用reduce_sum,因此我将得到2个数字(作为参数),并且梯度下降应该可以正常工作。在
但它不起作用,我得到以下信息:
^{pr2}$我的代码:
import...
def my_op(x,y):
op_output=getOutput(x,y) # size of N=(65536,)
return op_output
def callGrad(op,grad):
x = op.input[0]
y = op.input[1]
Gx=calculateGradx(x,y); # size of N=(65536,);
Gy=calculateGrady(x,y); # size of N=(65536,);
return Gx,Gy
def pyfunc(func,inp,Tout,stateful=True,name=None,grad=None)
rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+8))
tf.RegisterGradient(rnd_name)(grad)
g= tf.get_default_graph()
with g.gradient_override_map({"PyFuc": rnd_name});
return tf.py_func(func, inp, Tout, stateful=stateful, name=name)
from tensorflow.python.framework import ops
def tf_ops(x,y, name=None)
with ops.name_scope(name, "myOp", [x,y]) as name:
z = py_func(my_op,
[x,y],[tf.float32],name=name,grad=callGrad);
return z[0];
with tf.Session() as sess:
N=1; # for N=65536 it works but I want only one parameter
x=tf.constant(np.ones(N));
y=tf.constant(np.ones(N));
z=tf_op(x,y);
gr=tf.gradients(z,[x,y]);
init = tf.global_variables_initializer();
sess.run(init)
print(x.eval(), y.eval(),z.eval(), gr[0].eval(), gr[1].eval())
重要提示:我不想在梯度中求和,因为我将使用自动微分,所以我想得到以下成本函数: 总和((参考操作(x,y))^2)
梯度 -2*总和((参考操作(x,y))*dOp/dx)),-2*总和((参考操作(x,y))*dOp/dy))
所以dOp/dx应该与Op相同,即N=(65536,)
目前没有回答
相关问题 更多 >
编程相关推荐