AttributeError:“CustomAugment”对象在保存TensorFlow模型时没有属性“\u\u name\u”

2024-09-30 22:25:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在玩弄TensorFlow图像分类的数据增强。我使用了一个教程来创建一个自定义的增强类,代码如下,然后使用Keras Lamda将其加载到模型中。培训工作正常,但是当我尝试在培训后立即保存模型时,它会崩溃,出现标题中提供的错误

我对python非常陌生,但我的理解是该类应该有一个隐藏的变量名。有什么好处

自定义扩充类

class CustomAugment(object):
    def __call__(self, image):        
        # Random flips and grayscale with some stochasticity
        img = self._random_apply(tf.image.flip_left_right, image, p=0.6)
        img = self._random_apply(self._color_drop, img, p=0.9)
        return img

    def _color_drop(self, x):
        image = tf.image.rgb_to_grayscale(x)
        image = tf.tile(x, [1, 1, 1, 3])
        return x
    
    def _random_apply(self, func, x, p):
        return tf.cond(
          tf.less(tf.random.uniform([], minval=0, maxval=1, dtype=tf.float32),
                  tf.cast(p, tf.float32)),
          lambda: func(x),
          lambda: x)


data_augmentation = keras.Sequential(
  [
    tf.keras.layers.Lambda(CustomAugment()),
    layers.experimental.preprocessing.RandomRotation(0.1),
  ]
)

在模型中使用它

model = Sequential([
  tf.keras.Input(shape=(160, 160, 3)),
  data_augmentation,
  layers.Conv2D(16, 3, padding='same', activation='relu', input_shape=(160, 160, 3)),
  layers.Conv2D(16, 3, padding='same', activation='relu'),
#rest of model here

在这里撞车

model.save('el_patho_maximo')

Tags: 模型imageselfimgmodelreturnlayerstf
2条回答

找到了问题的解决办法

我必须简单地在CustomAugment类的uuuuu_uu初始化uuu之前添加uuuuu名称uuu(不带空格)=CustomAugment

这是一个缩进问题。在_random_apply中,除第一行以外的所有行都没有正确缩进。要么把它放在一行中,要么留下自动留下的空间

相关问题 更多 >