How to randomly select from set of functions in TensorFlow using tf.function(如何使用tf.unction从TensorFlow中的函数集中随机选择)
本文介绍了如何使用tf.unction从TensorFlow中的函数集中随机选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的问题是:在预处理过程中,我希望使用tf.data.Dataset
和tf.function
API将从一组函数中随机选择的函数应用于数据集示例。
具体地说,我的数据是3D体积,我希望从一组24个预定义的旋转函数中应用旋转。我想在tf.function
中编写这段代码,这样就限制了numpy
和列表索引之类的包的使用。
例如,我想做这样的事情:
import tensorflow as tf
@tf.function
def func1(tensor):
# Apply some rotation here
...
@tf.function
def func2(tensor):
...
...
@tf.function
def func24(tensor):
...
@tf.function
def apply(tensor):
list_of_funcs = [func1, func2, ..., func24]
# Randomly sample from 0-23
a = tf.random.uniform([1], minval=0, maxval=23, dtype=tf.int32)
return list_of_funcs[a](tensor)
但是,我无法将list_of_funcs
索引为TypeError: list indices must be integers or slices, not Tensor
。此外,我无法将这些函数(AFAIK)收集到tf.Tensor
中并使用tf.gather
。
所以我的问题是:我如何在tf.function
中合理而灵活地从这些函数中进行采样?
推荐答案
可以使用
tf.switch_case
如
def func1(tensor):
return tensor * 1
def func2(tensor):
return tensor * 2
def func24(tensor):
return tensor * 24
class Lambda:
def __init__(self, func, arg):
self._func = func
self._arg = arg
def __call__(self):
return self._func(self._arg)
@tf.function
def apply(tensor):
list_of_funcs = [func1, func2, func24]
branch_index = tf.random.uniform(shape=[], minval=0, maxval=len(list_of_funcs), dtype=tf.int32)
output = tf.switch_case(
branch_index=branch_index,
branch_fns=[Lambda(func, tensor) for func in list_of_funcs],
)
return output
修饰符@tf.function
仅用于您希望优化的整个函数,在本例中为apply
。如果使用apply
Insidetf.data.Dataset.map
,则根本不需要装饰符。
参见
this discussion
了解为什么我们必须在此处定义类Lambda
。
这篇关于如何使用tf.unction从TensorFlow中的函数集中随机选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何使用tf.unction从TensorFlow中的函数集中随机选择


基础教程推荐
猜你喜欢
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 包装空间模型 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01