Stacks a list of rank-`R` tensors into one rank-`(R+1)` tensor. Packs the list of tensors in `values` into a tensor with rank one higher than each tensor in `values`, by packing them along the `axis` dimension. Given a list of length `N` of tensors of shape `(A, B, C)`; if `axis == 0` then
(values, axis=0, name="stack")
| 1099 | @tf_export("stack") |
| 1100 | @dispatch.add_dispatch_support |
| 1101 | def stack(values, axis=0, name="stack"): |
| 1102 | """Stacks a list of rank-`R` tensors into one rank-`(R+1)` tensor. |
| 1103 | |
| 1104 | Packs the list of tensors in `values` into a tensor with rank one higher than |
| 1105 | each tensor in `values`, by packing them along the `axis` dimension. |
| 1106 | Given a list of length `N` of tensors of shape `(A, B, C)`; |
| 1107 | |
| 1108 | if `axis == 0` then the `output` tensor will have the shape `(N, A, B, C)`. |
| 1109 | if `axis == 1` then the `output` tensor will have the shape `(A, N, B, C)`. |
| 1110 | Etc. |
| 1111 | |
| 1112 | For example: |
| 1113 | |
| 1114 | ```python |
| 1115 | x = tf.constant([1, 4]) |
| 1116 | y = tf.constant([2, 5]) |
| 1117 | z = tf.constant([3, 6]) |
| 1118 | tf.stack([x, y, z]) # [[1, 4], [2, 5], [3, 6]] (Pack along first dim.) |
| 1119 | tf.stack([x, y, z], axis=1) # [[1, 2, 3], [4, 5, 6]] |
| 1120 | ``` |
| 1121 | |
| 1122 | This is the opposite of unstack. The numpy equivalent is |
| 1123 | |
| 1124 | ```python |
| 1125 | tf.stack([x, y, z]) = np.stack([x, y, z]) |
| 1126 | ``` |
| 1127 | |
| 1128 | Args: |
| 1129 | values: A list of `Tensor` objects with the same shape and type. |
| 1130 | axis: An `int`. The axis to stack along. Defaults to the first dimension. |
| 1131 | Negative values wrap around, so the valid range is `[-(R+1), R+1)`. |
| 1132 | name: A name for this operation (optional). |
| 1133 | |
| 1134 | Returns: |
| 1135 | output: A stacked `Tensor` with the same type as `values`. |
| 1136 | |
| 1137 | Raises: |
| 1138 | ValueError: If `axis` is out of the range [-(R+1), R+1). |
| 1139 | """ |
| 1140 | if axis == 0: |
| 1141 | try: |
| 1142 | # If the input is a constant list, it can be converted to a constant op |
| 1143 | return ops.convert_to_tensor(values, name=name) |
| 1144 | except (TypeError, ValueError): |
| 1145 | pass # Input list contains non-constant tensors |
| 1146 | |
| 1147 | value_shape = ops.convert_to_tensor(values[0], name=name)._shape_tuple() # pylint: disable=protected-access |
| 1148 | if value_shape is not None: |
| 1149 | expanded_num_dims = len(value_shape) + 1 |
| 1150 | if axis < -expanded_num_dims or axis >= expanded_num_dims: |
| 1151 | raise ValueError("axis = %d not in [%d, %d)" % |
| 1152 | (axis, -expanded_num_dims, expanded_num_dims)) |
| 1153 | |
| 1154 | return gen_array_ops.pack(values, axis=axis, name=name) |
| 1155 | |
| 1156 | |
| 1157 | # pylint: disable=invalid-name |
no test coverage detected