简体   繁体   中英

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(1), -10, log(2), -10 ]

In another word, I want to have a function like 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). 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正是这样的工作: httpstf.where

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM