如何对张量执行阈值处理

use*_*085 5 python tensorflow

以下是我的代码:

...
result=tf.div(product_norm,denom)
    if(result>0.5):
        result=1
    else:
        result=0
    return result
Run Code Online (Sandbox Code Playgroud)

如果张量中的值小于 0.5,则应将其替换为 0,否则为 1。但它不断返回错误。

TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.
Run Code Online (Sandbox Code Playgroud)

sta*_*ndy 4

在这个简单的例子中,您可以使用

result = tf.cast(result + 0.5, tf.int32)
Run Code Online (Sandbox Code Playgroud)

当 if 语句变得更加复杂时,考虑使用tf.cond