在Tensorflow中的张量上循环

2024-10-06 12:05:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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.

我使用TF2.4.1运行它,但我是在Beam上下文(出于TFX目的)下运行的,这意味着操作是在graph操作下完成的

谢谢


Tags: 代码innumpyfortfmaskelementsboolean
1条回答
网友
1楼 · 发布于 2024-10-06 12:05:41

问题是这样解决的:

    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)

相关问题 更多 >