我想创建一个TensorFlow/Keras层,在训练和测试期间始终应用对比度。
我使用了TensorFlow对比度调整方法tf.image.adjust_contrast
,但当我将其放在我正在制作的层的call
方法中并尝试训练时,我遇到了一个错误:
LookupError: gradient registry has no entry for: AdjustContrastv2
这是我当前的层代码:
class Contrast(keras.layers.Layer):
def __init__(self, contrast_level=2, **kwargs):
super(Contrast, self).__init__(**kwargs)
self.supports_masking = True
self.contrast_level = contrast_level
def call(self, inputs, training=None):
return tf.image.adjust_contrast(inputs, self.contrast_level)
def get_config(self):
config = {'stddev': self.stddev}
base_config = super(Contrast, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
def compute_output_shape(self, input_shape):
return input_shape
我认为为了提高效率,我应该尝试使用TensorFlow方法来实现对比,但这不是实现对比的方法吗?
错误消息的意思是,tensorflow不知道操作的梯度。您必须自己定义adjust_contrast
。
示例代码:
class Contrast(tf.keras.layers.Layer):
def __init__(self, contrast_level=2.0, **kwargs):
self.contrast_level = contrast_level
super().__init__(**kwargs)
self.supports_masking = True
def call(self, inputs, training=None):
channel_mean = tf.math.reduce_mean(inputs, [1, 2], keepdims=True)
return (inputs - channel_mean) * self.contrast_level + channel_mean
contrast_layer=Contrast()
random_images=[np.random.uniform(1,2,size=(64,224,224,3)).astype(np.float32) for i in range(3)]
print(np.allclose(tf.image.adjust_contrast(random_images[0],2),contrast_layer(random_images[0]),atol=0,rtol=1e-4))#True
print(np.allclose(tf.image.adjust_contrast(random_images[1],2),contrast_layer(random_images[1]),atol=0,rtol=1e-4))#True
print(np.allclose(tf.image.adjust_contrast(random_images[2],2),contrast_layer(random_images[2]),atol=0,rtol=1e-4))#True