如何在keras中减去通道明智的意思?
How to subtract channel wise mean in keras?
我已经实现了一个 lambda 函数来将图像的大小从 28x28x1 调整为 224x224x3。我需要从所有通道中减去 VGG 平均值。当我尝试这样做时,出现错误
TypeError: 'Tensor' 对象不支持项目分配
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
我已经实现了一个 lambda 函数来将图像的大小从 28x28x1 调整为 224x224x3。我需要从所有通道中减去 VGG 平均值。当我尝试这样做时,出现错误
TypeError: 'Tensor' 对象不支持项目分配
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