[英]how to customize an element-wise function on tensor in tensorflow?
Say, I have a tensor, it might contain positive and negative values: 说,我有一个张量,它可能包含正负值:
[ 1, -1, 2, -2 ]
Now, I want to apply log(x) for positive values, and a constant -10 for negative values: 现在,我想对正值应用log(x),对负值应用常量-10:
[ log(1), -10, log(2), -10 ]
In another word, I want to have a function like numpy.vectorize
. 换句话说,我想要一个像numpy.vectorize
这样的函数。 Is this possible in tensorflow? 这在张量流中是否可行?
One possible way is to use a non-learnable variable, but I don't know if it can properly do back propagation. 一种可能的方法是使用不可学习的变量,但我不知道它是否可以正确地进行反向传播。
tf.map_fn()
enables you to map an arbitrary TensorFlow subcomputation across the elements of a vector (or the slices of a higher-dimensional tensor). tf.map_fn()
使您可以跨矢量元素(或更高维张量的切片tf.map_fn()
映射任意TensorFlow子计算。 For example: 例如:
a = tf.constant([1.0, -1.0, 2.0, -2.0])
def f(elem):
return tf.where(elem > 0, tf.log(elem), -10.0)
# Alternatively, if the computation is more expensive than `tf.log()`, use
# `tf.cond()` to ensure that only one branch is executed:
# return tf.where(elem > 0, lambda: tf.log(elem), lambda: -10.0)
result = tf.map_fn(f, a)
我发现它, tf.where
正是这样的工作: https : tf.where
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.