如何为 TensorFlow 张量转换基于 numpy 的函数?

How to convert numpy based function for TensorFlow tensor?

我正在尝试使用 TensorFlow here 中可用的 tf.xyz 模块来实现以下功能。下面这个基于 NumPy 的函数将 3D 矩阵作为输入,使用最后一列的值和 returns 满足条件的前两列的值检查条件。

我很难将这个基于 NumPy 的模块转换为 TensorFlow 张量,我想将其作为 lambda 层添加到我的模型中。有什么建议吗?

我尝试使用 tf.greater()tf.slice(),但没有得到与函数的 NumPy 版本相同的输出。

# NumPy based function on 3D matrix:
def fun1(arr):
   return arr[arr[:,2] > 0.95][:,:2]  

input_matrix = np.array([[[1, 2, 0.99], [11, 22, 0.80], [111, 222, 0.96]]])

>> input_matrix
[[[  1.     2.     0.99]
[ 11.    22.     0.8 ]
[111.   222.     0.96]]]

>> np.array([fun1(i) for i in input_matrix])
array([[[  1.,   2.],
        [111., 222.]]])

要在 tensorflow 中执行与 numpy 的布尔索引等效的操作,您可以使用 boolean_mask 函数 (documented here)。例如:

import tensorflow as tf

def f(x):
    first_two_cols = x[:, :, :2]
    mask = x[:, :, 2] > 0.95
    return tf.boolean_mask(first_two_cols, mask)

input_tensor = tf.convert_to_tensor([[[1, 2, 0.99], [11, 22, 0.80], [111, 222, 0.96]]])

with tf.Session():
    output = f(x).eval()

>> output
array([[  1.,   2.],
       [111., 222.]], dtype=float32)