我已经实现了一个lambda函数,将图像从28x28x1调整大小到224x224x3。我需要从所有通道中减去VGG均值。当我尝试这样做时,出现了错误
TypeError: ‘Tensor’ object does not support item assignment
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]
进行张量元素-wise减法的推荐解决方案是什么?
回答:
在Keras 2.1.2之后,你可以在张量上使用keras.applications.imagenet_utils.preprocess_input
。在默认模式'caffe'
下,它会从x
中减去VGG均值。
from keras.applications.imagenet_utils import preprocess_inputdef 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