如何在Keras中按通道减去均值?

我已经实现了一个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

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注