1

I have been working on a project involving CNN and its weights and I have been trying to reduce the number of weights present in the CNN. I want to resize the MNIST images from 28x28 into 14x14 before training the CNN but I have no idea how to do it in Keras.

Here is a sample of the code used in importing the MNIST dataset and building the 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()

The X_train variable is the one used in the training of the model. What adjustments should I make to reduce the size of the X_train into 14x14 before the training starts?

Thank you!

Goldwin Giron
  • 13
  • 1
  • 3

1 Answers1

0

The default load_data function doesn't have any options for on the fly modification such as resize. Since you have NumPy arrays now, you have to pre-process, resize the images as arrays. Here is a post about resizing NumPy arrays as images.

nuric
  • 11,027
  • 3
  • 27
  • 42
  • Thanks! I found the answer in this post. Although, the opencv solution didn't work for me as it generates an error when processing images of large batches (like the MNIST train images). The scikit-image solution worked for me flawlessly. – Goldwin Giron Jun 04 '18 at 07:30