Tensorflow Tricks

使用assert

利用assert能快速对模型的形状进行检查,以发现潜在的错误。

  model.add(layers.Reshape((7, 7, 256)))
  assert model.output_shape == (None, 7, 7, 256)

在交互式创建的时候,返回的每一个hidden_layer都是一个Tensor形式的,使用.shape.get_shape()虽然能得到一模一样的形状,但是类型不对,需要通过tuple()函数转换类型后再比较。

assert tuple(hidden_layer.shape) == (None, 7, 7, 64)

tf.io.decode_image的问题

tf.io.decode_image(
    contents, channels=None, dtype=tf.dtypes.uint8, name=None,
    expand_animations=True
)

该函数自动对文件类型BMP,GIF,JPEG和PNG进行判定,但实际使用的时候遇到了问题。 可能图片读取的时候不会报错,但是后面的代码因为数据不正确反而报错了:

    /.../load_cmp_facade.py:41 __random_jitter  *
        image_a = resize(image_a, [self.config.RESIZE_UP_SIZE, self.config.RESIZE_UP_SIZE])
    /.../data_augmentation.py:24 resize  *
        return tf.image.resize(images=input_image,
    /.../image_ops_impl.py:1357 resize_images_v2
        skip_resize_if_same=False)
    /.../image_ops_impl.py:1072 _resize_images_common
        raise ValueError('\'images\' contains no shape.')

    ValueError: 'images' contains no shape.

这样的Bug实际出现时挺难找,报错和实际原因关联比较弱。 因该优先使用tf.io.decode_jpeg之类的函数,保证能正确读取。

Last updated

Was this helpful?