Keras图像数据特征标准化

预备工作:在PYTHON上下载keras

做法:

数据集:mnist数据集

使用mnist数据集。首先,绘制一个未经标准化的图像:

代码:

from keras.datasets import mnist
from matplotlib import pyplot
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# create a grid of 3x3 images
for i in range(0, 9):
    ax = pyplot.subplot(330 + 1 + i)
    pyplot.tight_layout()
    ax.tick_params(axis='x', colors='white')
    ax.tick_params(axis='y', colors='white')
    pyplot.imshow(X_train[i], cmap=pyplot.get_cmap('gray'))
# show the plot
pyplot.show()



接下来使用ImageDataGenerator对该图进行特征标准化处理。

初始化ImageDataGenerator

使用keras.preprocessing.image.ImageDataGenerator(featurewise_center=False,samplewise_center=False,featurewise_std_normalization=False,samplewise_std_normalization=False)

初始化ImageDataGenerator。

参数介绍如下:

·featurewise_center:布尔值,将数据集的输入均值设置为0,按特征执行。·samplewise_center:布尔值,将样本均值都初始化为0。·featurewise_std_normalization:布尔值,将输入除以数据集的标准差,按特征执行。·samplewise_std_normalization:布尔值,将输入的每个样本除以其自身的标准差。将这一初始化程序应用于mnist数据集:


将这一初始化程序应用于mnist数据集:

from keras.preprocessing.image import ImageDataGenerator
from keras import backend as K
K.set_image_dim_ordering('th')
X_train = X_train.reshape(X_train.shape[0], 1, 28, 28)
X_test = X_test.reshape(X_test.shape[0], 1, 28, 28)
# convert from int to float
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
# define data preparation
datagen = ImageDataGenerator(featurewise_center=True, featurewise_std_normalization=True,
                            samplewise_center=True, samplewise_std_normalization=True)
# fit parameters from data
datagen.fit(X_train)
# configure batch size and retrieve one batch of images
for X_batch, y_batch in datagen.flow(X_train, y_train, batch_size=9):
# create a grid of 3x3 images
    for i in range(0, 9):
        ax =pyplot.subplot(330 + 1 + i)
        pyplot.tight_layout()