Compatibility utility required to allow for both V1 and V2 behavior in TF. Until the release of TF 2.0, we need the legacy behavior of `TensorShape` to coexist with the new behavior. This utility is a bridge between the two. If you want to retrieve the Dimension instance corresponding to a c
(shape, index)
| 132 | "compat.dimension_at_index", |
| 133 | v1=["dimension_at_index", "compat.dimension_at_index"]) |
| 134 | def dimension_at_index(shape, index): |
| 135 | """Compatibility utility required to allow for both V1 and V2 behavior in TF. |
| 136 | |
| 137 | Until the release of TF 2.0, we need the legacy behavior of `TensorShape` to |
| 138 | coexist with the new behavior. This utility is a bridge between the two. |
| 139 | |
| 140 | If you want to retrieve the Dimension instance corresponding to a certain |
| 141 | index in a TensorShape instance, use this utility, like this: |
| 142 | |
| 143 | ``` |
| 144 | # If you had this in your V1 code: |
| 145 | dim = tensor_shape[i] |
| 146 | |
| 147 | # Use `dimension_at_index` as direct replacement compatible with both V1 & V2: |
| 148 | dim = dimension_at_index(tensor_shape, i) |
| 149 | |
| 150 | # Another possibility would be this, but WARNING: it only works if the |
| 151 | # tensor_shape instance has a defined rank. |
| 152 | dim = tensor_shape.dims[i] # `dims` may be None if the rank is undefined! |
| 153 | |
| 154 | # In native V2 code, we recommend instead being more explicit: |
| 155 | if tensor_shape.rank is None: |
| 156 | dim = Dimension(None) |
| 157 | else: |
| 158 | dim = tensor_shape.dims[i] |
| 159 | |
| 160 | # Being more explicit will save you from the following trap (present in V1): |
| 161 | # you might do in-place modifications to `dim` and expect them to be reflected |
| 162 | # in `tensor_shape[i]`, but they would not be (as the Dimension object was |
| 163 | # instantiated on the fly. |
| 164 | ``` |
| 165 | |
| 166 | Arguments: |
| 167 | shape: A TensorShape instance. |
| 168 | index: An integer index. |
| 169 | |
| 170 | Returns: |
| 171 | A dimension object. |
| 172 | """ |
| 173 | assert isinstance(shape, TensorShape) |
| 174 | if shape.rank is None: |
| 175 | return Dimension(None) |
| 176 | else: |
| 177 | return shape.dims[index] |
| 178 | |
| 179 | |
| 180 | @tf_export(v1=["Dimension"]) |