小编njk*_*njk的帖子

为操作编写自定义基于Python的渐变函数?(没有C++实现)

我正在尝试为'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)

python gradient-descent tensorflow

5
推荐指数
1
解决办法
3935
查看次数

TensorFlow批量外产品

我有以下两个张量:

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()但没有成功.

tensorflow

4
推荐指数
1
解决办法
2344
查看次数

在 Python 3 中调用 super() 之前覆盖父类属性

考虑以下示例。该类Parent有一个名为 的属性attr。和Child1都有Child2一个同名的属性。Child1和之间的唯一区别Child2是在覆盖父级属性之前Child1调用。相反,似乎不会覆盖父级的属性,因为该属性是在调用之前定义的。有没有办法在调用之前定义它时覆盖父级?super()attrChild2attrsuper()Child2attrsuper()

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)

python inheritance attributes class python-3.x

2
推荐指数
1
解决办法
1万
查看次数