在使用Keras训练之前调整MNIST图像的大小

时间:2018-06-03 05:45:54

标签: python machine-learning keras convolutional-neural-network

我一直致力于一个涉及CNN及其权重的项目,我一直在努力减少CNN中存在的权重数量。我想在训练CNN之前将MNIST图像从28x28调整为14x14,但我不知道如何在Keras中进行。

以下是导入MNIST数据集和构建CNN时使用的代码示例:

# LOAD MNIST DATA
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# RESHAPE TO [SAMPLES][PIXELS][WIDTH][HEIGHT]
X_train = X_train.reshape(X_train.shape[0], 1, 28, 28).astype('float32')
X_test = X_test.reshape(X_test.shape[0], 1, 28, 28).astype('float32')

# NORMALIZE 0-255 TO 0-1
X_train = X_train / 255
X_test = X_test / 255
# ONE HOT ENCODE
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]

#DEFINE MODEL
def larger_model():
  # CREATE MODEL
  model = Sequential()
  model.add(Conv2D(2, (5, 5), input_shape=(1, 28, 28), activation='relu', 
padding="same"))
  model.add(MaxPooling2D(pool_size=(2, 2)))
  model.add(Conv2D(2, (5, 5), activation='relu', padding="same"))
  model.add(MaxPooling2D(pool_size=(2, 2)))
  model.add(Dropout(0.2))
  model.add(Flatten())
  model.add(Dense(16, activation='relu'))
  model.add(Dense(num_classes, activation='softmax'))
  # COMPILE MODEL
  model.compile(loss='categorical_crossentropy', optimizer='adam', metrics= 
 ['accuracy'])
  return model

# BUILD MODEL
model = larger_model()
model.summary()

X_train变量是模型训练中使用的变量。在训练开始之前,我应该做些什么调整才能将X_train的大小减小到14x14?

谢谢!

1 个答案:

答案 0 :(得分:0)

默认load_data函数没有任何动态修改选项,例如resize。由于您现在拥有NumPy阵列,因此必须预处理图像作为数组调整大小。这是关于将NumPy数组调整为图像的post