【问题标题】:Loop over a tensor in Tensorflow在 Tensorflow 中循环一个张量
【发布时间】:2021-05-10 20:05:26
【问题描述】:

我想循环一个 Tensorflow 张量,我的代码是这样的:

elements = tf.constant([1,2,3])
x = tf.constant([1.000001, 1.1, 2.1, 2.00004, 3.001])
EPSILON = 0.0001
for elem in elements:
    mask = tf.experimental.numpy.isclose(x, elem, atol=EPSILON, rtol=0)
    x = tf.boolean_mask(x, ~mask)

在Tensorflow中如何在图形模式下做到这一点?我收到以下错误:

    OperatorNotAllowedInGraphError: iterating over `tf.Tensor` is not allowed: AutoGraph did convert this function. This might indicate you are trying to use an unsupported feature.

我正在使用 TF 2.4.1 运行它,但我在 Beam 上下文中执行它(用于 TFX 目的),这意味着操作是在图形操作下完成的。

谢谢!

【问题讨论】:

标签: python tensorflow apache-beam tfx


【解决方案1】:

这样解决了:

    mask = tf.map_fn(fn=lambda t: ~tf.experimental.numpy.isclose(
        x, t, atol=EPSILON, rtol=0
    ), elems=elements)

    mask = tf.reduce_min(mask, axis=0)
    x = tf.boolean_mask(x, mask)

【讨论】:

    猜你喜欢
    • 2018-06-05
    • 2018-07-15
    • 2019-04-28
    • 2021-07-01
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 2017-09-05
    • 2018-08-23
    相关资源
    最近更新 更多