我正在尝试为'my_op'编写一个自定义渐变函数,为了示例,它只包含对tf.identity()的调用(理想情况下,它可以是任何图形).
import tensorflow as tf
from tensorflow.python.framework import function
def my_op_grad(x):
return [tf.sigmoid(x)]
@function.Defun(a=tf.float32, python_grad_func=my_op_grad)
def my_op(a):
return tf.identity(a)
a = tf.Variable(tf.constant([5., 4., 3., 2., 1.], dtype=tf.float32))
sess = tf.Session()
sess.run(tf.initialize_all_variables())
grad = tf.gradients(my_op(a), [a])[0]
result = sess.run(grad)
print(result)
sess.close()
Run Code Online (Sandbox Code Playgroud)
不幸的是我收到以下错误:
Traceback (most recent call last):
File "custom_op.py", line 19, in <module>
grad = tf.gradients(my_op(a), [a])[0]
File "/Users/njk/tfm/lib/python3.5/site-packages/tensorflow/python/framework/function.py", line 528, in __call__
return call_function(self._definition, *args, **kwargs)
File "/Users/njk/tfm/lib/python3.5/site-packages/tensorflow/python/framework/function.py", line 267, in call_function
compute_shapes=False)
File "/Users/njk/tfm/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 2285, in create_op
raise …
Run Code Online (Sandbox Code Playgroud) 我有以下两个张量:
x, with shape [U, N]
y, with shape [N, V]
Run Code Online (Sandbox Code Playgroud)
我想执行批量外部产品:我想将x
第一行中每个元素的第一列中的每个元素相乘y
以获得形状的张量[U, V]
,然后是第二行中x
的第二列y
,等等上.最终张量的形状应[N, U, V]
,其中N
为将批量大小.
在TensorFlow中有没有简单的方法来实现这一目标?我试图使用batch_matmul()
但没有成功.
考虑以下示例。该类Parent
有一个名为 的属性attr
。和Child1
都有Child2
一个同名的属性。Child1
和之间的唯一区别Child2
是在覆盖父级属性之前Child1
调用。相反,似乎不会覆盖父级的属性,因为该属性是在调用之前定义的。有没有办法在调用之前定义它时覆盖父级?super()
attr
Child2
attr
super()
Child2
attr
super()
class Parent():
def __init__(self):
self.attr = "parent"
class Child1(Parent):
def __init__(self):
super().__init__()
self.attr = "child1"
class Child2(Parent):
def __init__(self):
self.attr = "child2"
super().__init__()
if __name__ == '__main__':
child1 = Child1()
print(child1.attr) # "child1"
child2 = Child2()
print(child2.attr) # "parent"
Run Code Online (Sandbox Code Playgroud)