2017-12-18 308 views
0

我已經實現了一個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] 

有什麼推薦的解決方案做張量的元素方式減法?

+0

正如我們所知,我們可以在輸入本身中執行此操作。但是我想將它作爲Lamda圖層的一部分,以便在輸入數據增量後應用這種減法。 – user1159517

回答

2

您可以在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 
+0

順便說一句,如果你使用MobileNet,你應該使用'mode ='tf''而不是減去VGG的平均值。 –

+0

https://stackoverflow.com/questions/47862788/how-to-load-mobilenet-weights-with-an-input-tensor-in-keras?noredirect=1#comment82692173_47862788 你能幫忙嗎? – user1159517

相關問題