此页面由 Cloud Translation API 翻译。
Switch to English

tf.ensure_shape

TensorFlow 1版 GitHub上查看源代码

更新的张量,并检查在运行时的形状的形状保持。

怀着热切的执行,这是一个形状断言,返回输入:

x = tf.constant([1,2,3])
print(x.shape)
(3,)
x = tf.ensure_shape(x, [3])
x = tf.ensure_shape(x, [5])
Traceback (most recent call last):

tf.errors.InvalidArgumentError: Shape of tensor dummy_input [3] is not
  compatible with expected shape [5]. [Op:EnsureShape]

tf.functionv1.Graph背景下,检查两个构建时和运行时的形状。这比严格tf.Tensor.set_shape仅检查构建时的形状。

例如,一个已知的大小的加载图像的:

@tf.function
def decode_image(png):
  image = tf.image.decode_png(png, channels=3)
  # the `print` executes during tracing.
  print("Initial shape: ", image.shape)
  image = tf.ensure_shape(image,[28, 28, 3])
  print("Final shape: ", image.shape)
  return image

当跟踪一个功能,正在执行无OPS,形状可以是未知的。请参阅具体功能指南的详细信息。

concrete_decode = decode_image.get_concrete_function(
    tf.TensorSpec([], dtype=tf.string))
Initial shape:  (None, None, 3)
Final shape:  (28, 28, 3)
image = tf.random.uniform(maxval=255, shape=[28, 28, 3], dtype=tf.int32)
image = tf.cast(image,tf.uint8)
png = tf.image.encode_png(image)
image2 = concrete_decode(png)
print(image2.shape)
(28, 28, 3)
image = tf.concat([image,image], axis=0)
print(image.shape)
(56, 28, 3)
png = tf.image.encode_png(image)
image2 = concrete_decode(png)
Traceback (most recent call last):

tf.errors.InvalidArgumentError:  Shape of tensor DecodePng [56,28,3] is not
  compatible with expected shape [28,28,3].
@tf.function
def bad_decode_image(png):
  image = tf.image.decode_png(png, channels=3)
  # the `print` executes during tracing.
  print("Initial shape: ", image.shape)
  # BAD: forgot to use the returned tensor.
  tf.ensure_shape(image,[28, 28, 3])
  print("Final shape: ", image.shape)
  return image
image = bad_decode_image(png)
Initial shape:  (None, None, 3)
Final shape:  (None, None, 3)
print(image.shape)
(56, 28, 3)

x 一个Tensor
shape TensorShape表示此张量,一个的形状TensorShapeProto ,列表,元组,或无。
name 用于该操作(可选)的名称。默认为“EnsureShape”。

一个Tensor 。具有相同类型和内容为x 。在运行时,提出了一个tf.errors.InvalidArgumentError如果shape是形状不兼容x