在 Tensorflow 中使用 Numpy 数组条件运算掩码

Using Numpy Array Conditional Operation Mask with Tensorflow

我是 Tensoflow 的新手,我尝试在自定义 RNN 项目中实现它以了解更多关于神经网络如何工作的信息。

我的问题很简单,但我似乎没有找到满意的答案。

我习惯了 Numpy 和使用条件掩码对数组进行操作,但我找不到用 Tensors 转换它的方法

def ELu(in_array):
    in_array[in_array<= 0] = math.e ** in_array[in_array<= 0] - 1
    return in_array

>>>print(ELu(np.array([1.0,0.0,-1.0])))

给我

[ 1.          0.         -0.63212056]

我想编辑那个函数,以便在我做这样的事情时能够给我一个类似的张量

>>>print(ELu(tf.convert_to_tensor([1.0,0.0,-1.0])))

哪个应该给我

<tf.Tensor: shape=(3,), dtype=float32, numpy=array([ 1.,  0., -0.63212056], dtype=float32)>

但是使用类似的方式访问张量 in_array[in_array<= 0] 不起作用

使用tensor_scatter_nd_update():

import math
def ELu(in_array):
  mask = in_array <= 0
  inds = tf.where(mask)
  updates = tf.boolean_mask(in_array, mask)
  updates = math.e ** updates - 1.
  res = tf.tensor_scatter_nd_update(in_array, inds, updates)
  return res