Helper method to recursively apply a function to structure of tensors. The structure of the tensors should take the form similar to fetches in `tf.compat.v1.Session` and includes single `Tensor`, `list`, nested `list`, `tuple`, `namedtuple`, or `dict`. Args: tensors: Single `Tensor`,
(tensors, apply_fn)
| 28 | |
| 29 | |
| 30 | def _recursive_apply(tensors, apply_fn): |
| 31 | """Helper method to recursively apply a function to structure of tensors. |
| 32 | |
| 33 | The structure of the tensors should take the form similar to fetches in |
| 34 | `tf.compat.v1.Session` and includes single `Tensor`, `list`, nested `list`, |
| 35 | `tuple`, |
| 36 | `namedtuple`, or `dict`. |
| 37 | |
| 38 | Args: |
| 39 | tensors: Single `Tensor`, `list`, nested `list, `tuple`, `namedtuple`, or |
| 40 | `dict`. |
| 41 | apply_fn: Function to apply to each `Tensor` and should return a `Tensor`. |
| 42 | |
| 43 | Returns: |
| 44 | Returns the modified tensors with the same structure. |
| 45 | Raises: |
| 46 | `TypeError` if undefined type in the tensors structure. |
| 47 | """ |
| 48 | tensors_type = type(tensors) |
| 49 | if tensors_type is ops.Tensor: |
| 50 | return apply_fn(tensors) |
| 51 | elif isinstance(tensors, variables.Variable): |
| 52 | return apply_fn(tensors.value()) |
| 53 | elif isinstance(tensors, (list, tuple)): |
| 54 | tensors = [_recursive_apply(t, apply_fn) for t in tensors] |
| 55 | if tensors_type is list: |
| 56 | return list(tensors) |
| 57 | elif tensors_type is tuple: |
| 58 | return tuple(tensors) |
| 59 | return tensors_type(*tensors) # collections.namedtuple |
| 60 | elif tensors_type is dict: |
| 61 | return dict([(k, _recursive_apply(v, apply_fn)) for k, v in tensors.items() |
| 62 | ]) |
| 63 | else: |
| 64 | raise TypeError('_recursive_apply argument %r has invalid type %r' % |
| 65 | (tensors, tensors_type)) |
| 66 | |
| 67 | |
| 68 | class _ControlOutputCache(object): |