首页 > 解决方案 > How can I determine whether a intermediate results has or has no data?

问题描述

How can I implement "if there exist items in a Tensor then calculate the average value of it, else assign it a certain value"? take tf.gather_nd() for example choosing some rows from source_tensor with shape (?, 2)

result = tf.gather_nd(source_tensor, indices)

should get the items from source_tensor according indices, but if indices is am empty list [], tf.gather_nd will, the program will continue and there is nothing in result.

So I wonder that is there a way to determine if the result is empty (that is it has no data) when building the computational graph of tensorflow? and if so, I want to assign it constant value manually.

Because what I'm going to do next is

tf.reduce_mean(result)

if the result has no data, tf.reduce_mean(result) will produce nan.

标签: pythontensorflowshapedimensionstensor

解决方案


您应该能够通过 执行此操作tf.cond,它根据某些条件执行两个分支之一。我还没有测试过下面的代码,所以请报告它是否有效。

mean = tf.cond(tf.size(result), lambda: tf.reduce_mean(result), lambda: some_constant)

这个想法是检查是否result包含任何项目(如果为空tf.size,则应返回 0 )。result您可能需要将其显式转换为布尔条件,即tf.cast(tf.size(result), tf.bool)改为使用。


推荐阅读