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中的函数集中随机选择


猜你喜欢
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- 沿轴计算直方图 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12