Define a reduction op for labeled tensors. Args: op_name: string name of the TensorFlow op. reduce_fn: function to call to evaluate the op on a tf.Tensor. Returns: Function defining the given reduction op that acts on a LabeledTensor.
(op_name, reduce_fn)
| 878 | @tc.returns(types.FunctionType) |
| 879 | @tc.accepts(string_types, collections_abc.Callable) |
| 880 | def define_reduce_op(op_name, reduce_fn): |
| 881 | """Define a reduction op for labeled tensors. |
| 882 | |
| 883 | Args: |
| 884 | op_name: string name of the TensorFlow op. |
| 885 | reduce_fn: function to call to evaluate the op on a tf.Tensor. |
| 886 | |
| 887 | Returns: |
| 888 | Function defining the given reduction op that acts on a LabeledTensor. |
| 889 | """ |
| 890 | |
| 891 | default_name = 'lt_%s' % op_name |
| 892 | |
| 893 | @tc.returns(core.LabeledTensor) |
| 894 | @tc.accepts(core.LabeledTensorLike, ReduceAxes, tc.Optional(string_types)) |
| 895 | def op(labeled_tensor, axes=None, name=None): |
| 896 | """Computes the given reduction across the given axes of a LabeledTensor. |
| 897 | |
| 898 | See `tf.{op_name}` for full details. |
| 899 | |
| 900 | Args: |
| 901 | labeled_tensor: The input tensor. |
| 902 | axes: A set of axes or None. |
| 903 | If None, all axes will be reduced. |
| 904 | Axes must all be strings, in which case those dimensions will be |
| 905 | removed, or pairs of (name, None) or (name, label), in which case those |
| 906 | dimensions will be kept. |
| 907 | name: Optional op name. |
| 908 | |
| 909 | Returns: |
| 910 | The reduced LabeledTensor. |
| 911 | |
| 912 | Raises: |
| 913 | ValueError: if any of the axes to reduce over are not found on |
| 914 | `labeled_tensor`. |
| 915 | """ |
| 916 | with ops.name_scope(name, default_name, [labeled_tensor]) as scope: |
| 917 | labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor) |
| 918 | |
| 919 | if axes is None: |
| 920 | axes = labeled_tensor.axes.keys() |
| 921 | |
| 922 | if isinstance(axes, (string_types, tuple)): |
| 923 | axes = [axes] |
| 924 | |
| 925 | reduction_axes = {} |
| 926 | axes_to_squeeze = [] |
| 927 | for a in axes: |
| 928 | if isinstance(a, string_types): |
| 929 | # We squeeze out this axis. |
| 930 | reduction_axes[a] = a |
| 931 | axes_to_squeeze.append(a) |
| 932 | else: |
| 933 | # We keep this axis, with the user-provided labels. |
| 934 | (axis_name, label) = a |
| 935 | if label is not None: |
| 936 | # The input was a single label, so make it a list so it can be |
| 937 | # turned into an Axis. |