微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法避免张量流函数回溯

如何解决无法避免张量流函数回溯

我实现了我的自定义层以使用填充调整图像大小。 我只是想(按比例)调整我的图像大小,这就是我实现自定义图层而不是使用 tf.image.resize() 的原因。我想使用特殊的预处理层而不是在 Python 中手动执行此操作。然后我可以保存和加载拍摄不同尺寸图像的模型。所以它会非常便携等等。 但是当我使用 predict() 方法测试模型时,我得到以下红色警告:

警告:tensorflow:最近 12 次调用 中的 6 次触发了 tf.function 回溯。跟踪是昂贵的,过多的跟踪可能是由于传递了 python 对象而不是张量。此外, tf.function 有 Experiment_relax_shapes=True 选项,可以放宽参数形状,以避免不必要的回溯。请参阅 https://www.tensorflow.org/tutorials/customization/performance#python_or_tensor_argshttps://www.tensorflow.org/api_docs/python/tf/function 了解更多详情。

这是我的代码

class ResizeWithPad(Layer):
"""Resize an image to the target width and height by keeping the aspect ratio
the same without distortion. If the target dimensions don't match the image dimensions,the image is resized and then padded with zeroes to match requested dimensions.
The input should be 4-D Tensor of shape [batch,height,width,channels].

Arguments:

height: Integer,the height of the output shape.

width: Integer,the width of the output shape.

name: A string,the name of the layer.
"""

def __init__(self,name=None,**kwargs):
    super(ResizeWithPad,self).__init__(name=name,**kwargs)
    self.target_height = height
    self.target_width = width
    self.input_spec = InputSpec(shape=(None,None,3))
    print("\nTRACE!!!\n")

@tf.function(input_signature=(tf.TensorSpec(shape=[None,3],dtype=tf.float32),),experimental_relax_shapes=True)
def call(self,inputs):
    print("\nTRACE!!!\n")
    outputs = tf.image.resize_with_pad(
        inputs,self.target_height,self.target_width)
    return outputs

@tf.function(input_signature=(tf.TensorSpec(shape=[None,experimental_relax_shapes=True)
def compute_output_shape(self,input_shape):
    print("\nTRACE!!!\n")
    input_shape = tensor_shape.TensorShape(input_shape).as_list()
    return tensor_shape.TensorShape(
        [input_shape[0],self.target_width,input_shape[3]])

@tf.function(input_signature=(tf.TensorSpec(shape=[None,experimental_relax_shapes=True)
def get_config(self):
    print("\nTRACE!!!\n")
    config = {
        'height': self.target_height,'width': self.target_width
    }
    base_config = super(ResizeWithPad,self).get_config()
    return dict(list(base_config.items()) + list(config.items()))

def main():
    tf.config.experimental_run_functions_eagerly(False)
    img = cv2.imread(file)
    inp = tf.convert_to_tensor(np.expand_dims(roi,axis=0))
    model_output = test_model.predict(inp)[0]

我试图禁用急切执行,使用带有不同参数的 tf.function,但没有任何帮助。 当您有可变长度的输入时,也许这是不可避免的?也许我不应该担心这个,因为这是正常的。如果你有新的形状,你应该重建图形。当然,这需要时间,但是在提供给模型之前在 Python 函数中预处理图像也需要时间。所以也许没关系。你怎么看?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。