python - 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.
解决方案
您应该能够通过 执行此操作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)
改为使用。
推荐阅读
- reactjs - 使用无效数据调用的函数 addDoc()。不支持的字段值:未定义
- java - 使用 Ecpise 从数据库中检索列表时出现问题
- apache-spark - Linux 上的 Spark 错误:线程“main”中的异常 java.io.IOException:无法运行程序“python”:错误 = 2,没有这样的文件或目录
- c - 这个例外是什么意思?格式 %d 需要类型为“int”的参数,但参数 2 的类型为“long long unsigned int”[-Wformat]
- r - Highcharter 工具提示不适用于许多系列
- javascript - backgroundColor 以空字符串的形式出现,当我设置它的值时不会在屏幕上改变
- javascript - 如何使用 javascript 更改导航上的活动导航栏图标
- linux - 如何抑制 grep 的错误输出,使其仅返回退出状态?
- database - MongoDB:如何处理两个用户同时上传相同的用户名或密码
- github - 我如何从 Github 安装文件