如何减去keras中的通道平均值?

我已经实现了一个lambda函数来将图像的大小从28x28x1调整为224x224x3。我需要从所有频道中减去VGG的平均值。当我尝试,我得到一个错误如何减去keras中的通道平均值?

类型错误:“张量”对象不支持项目分配

def try_reshape_to_vgg(x): 

x = K.repeat_elements(x, 3, axis=3)

x = K.resize_images(x, 8, 8, data_format="channels_last")

x[:, :, :, 0] = x[:, :, :, 0] - 103.939

x[:, :, :, 1] = x[:, :, :, 1] - 116.779

x[:, :, :, 2] = x[:, :, :, 2] - 123.68

return x[:, :, :, ::-1]

有什么推荐的解决方案做张量的元素方式减法?

回答:

您可以在Keras 2.1.2之后在张量上使用keras.applications.imagenet_utils.preprocess_input。它会在默认模式'caffe'下减去x的VGG平均值。

from keras.applications.imagenet_utils import preprocess_input 

def try_reshape_to_vgg(x):

x = K.repeat_elements(x, 3, axis=3)

x = K.resize_images(x, 8, 8, data_format="channels_last")

x = preprocess_input(x)

return x

如果你想留在旧版本Keras的,也许你可以检查它是如何在Keras 2.1.2实现的,提取有用的线成try_reshape_to_vgg

def _preprocess_symbolic_input(x, data_format, mode): 

global _IMAGENET_MEAN

if mode == 'tf':

x /= 127.5

x -= 1.

return x

if data_format == 'channels_first':

# 'RGB'->'BGR'

if K.ndim(x) == 3:

x = x[::-1, ...]

else:

x = x[:, ::-1, ...]

else:

# 'RGB'->'BGR'

x = x[..., ::-1]

if _IMAGENET_MEAN is None:

_IMAGENET_MEAN = K.constant(-np.array([103.939, 116.779, 123.68]))

# Zero-center by mean pixel

if K.dtype(x) != K.dtype(_IMAGENET_MEAN):

x = K.bias_add(x, K.cast(_IMAGENET_MEAN, K.dtype(x)), data_format)

else:

x = K.bias_add(x, _IMAGENET_MEAN, data_format)

return x

以上是 如何减去keras中的通道平均值? 的全部内容, 来源链接: utcz.com/qa/260885.html

回到顶部