Script Language Operators
tf.py_func
在 tensorflow 中 缺乏 需要的 函数接口 时,负责将任意的 python/numpy functions 包装成 TensorFlow op。
tf.py_func (func, inp, Tout, stateful=True, name=None)
其中, inp参数项
必须是 list型
,哪怕 list 里只有一个元素;而 inp参数项
在只有一个元素时可以 不必为 list型
。
示例一:
import tensorflow as tf
import numpy as np
inputs = 1.
my_func = lambda x : np.sinh(x)
y = tf.py_func(my_func, [inputs], tf.float32)
sess = tf.InteractiveSession()
print y.eval()
1.1752
示例二:
import tensorflow as tf
import numpy as np
array1 = np.array([[1, 2], [3, 4]], dtype=np.float32)
array2 = np.array([[5, 6], [7, 8]], dtype=np.float32)
def add_minus_dot(array1, array2):
return array1 + array2, array1 - array2, np.dot(array1, array2)
y1, y2, y3 = tf.py_func(add_minus_dot, [array1, array2], [tf.float32, tf.float32, tf.float32])
with tf.Session() as sess:
_y1, _y2, _y3 = sess.run([y1, y2, y3])
print _y1
print
print _y2
print
print _y3
[[ 6. 8.]
[ 10. 12.]]
[[-4. -4.]
[-4. -4.]]
[[ 19. 22.]
[ 43. 50.]]