xref: /aosp_15_r20/external/tensorflow/tensorflow/python/data/util/convert.py (revision b6fb3261f9314811a0f4371741dbb8839866f948)
1# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ==============================================================================
15"""Helpers constructing Datasets."""
16from tensorflow.python.framework import constant_op
17from tensorflow.python.framework import dtypes
18from tensorflow.python.framework import ops
19from tensorflow.python.framework import tensor_shape
20
21
22def optional_param_to_tensor(argument_name,
23                             argument_value,
24                             argument_default=0,
25                             argument_dtype=dtypes.int64):
26  if argument_value is not None:
27    return ops.convert_to_tensor(
28        argument_value, dtype=argument_dtype, name=argument_name)
29  else:
30    return constant_op.constant(
31        argument_default, dtype=argument_dtype, name=argument_name)
32
33
34def partial_shape_to_tensor(shape_like):
35  """Returns a `tf.Tensor` that represents the given shape.
36
37  Args:
38    shape_like: A value that can be converted to a `tf.TensorShape` or a
39      `tf.Tensor`.
40
41  Returns:
42    A 1-D `tf.Tensor` of `tf.int64` elements representing the given shape, where
43    `-1` is substituted for any unknown dimensions.
44  """
45  try:
46    # First attempt to convert the input to a shape, and return the
47    # "canonical" tensor representation, which uses `-1` in place of
48    # `None`.
49    shape_like = tensor_shape.as_shape(shape_like)
50    return ops.convert_to_tensor(
51        [dim if dim is not None else -1 for dim in shape_like.as_list()],
52        dtype=dtypes.int64)
53  except (TypeError, ValueError):
54    # The argument was not trivially convertible to a
55    # `tf.TensorShape`, so fall back on the conversion to tensor
56    # machinery.
57    ret = ops.convert_to_tensor(shape_like, preferred_dtype=dtypes.int64)
58    if ret.shape.dims is not None and len(ret.shape.dims) != 1:
59      raise ValueError("The given shape {} must be a 1-D tensor of `tf.int64` "
60                       "values, but the shape was {}.".format(
61                           shape_like, ret.shape))
62    if ret.dtype != dtypes.int64:
63      raise TypeError("The given shape {} must be a 1-D tensor of `tf.int64` "
64                      "values, but the element type was {}.".format(
65                          shape_like, ret.dtype.name))
66
67    return ret
68