输入到tf.keras的Conv2D层的大小不正确

时间:2018-08-07 20:40:35

标签: python tensorflow keras

我正在按照教程here

中概述的步骤进行操作

我正在尝试在Google合作实验室笔记本中的单元格中运行该教程中的以下代码:

  import tensorflow as tf
  mnist = tf.keras.datasets.mnist
  (x_train, y_train), (x_test, y_test) = 
  tf.keras.datasets.fashion_mnist.load_data()
  x_train = x_train.astype('float32') / 255
  x_test = x_test.astype('float32') / 255
  model = tf.keras.Sequential()



 # Must define the input shape in the first layer of the neural network
  model.add(tf.keras.layers.Conv2D(filters=64, kernel_size=2, padding='same', activation='relu', input_shape=(28,28,1))) 



 model.add(tf.keras.layers.MaxPooling2D(pool_size=2))
  model.add(tf.keras.layers.Dropout(0.3))
  model.add(tf.keras.layers.Conv2D(filters=32, kernel_size=2, padding='same', activation='relu'))
  model.add(tf.keras.layers.MaxPooling2D(pool_size=2))
  model.add(tf.keras.layers.Dropout(0.3))
  model.add(tf.keras.layers.Flatten())
  model.add(tf.keras.layers.Dense(256, activation='relu'))
  model.add(tf.keras.layers.Dropout(0.5))
  model.add(tf.keras.layers.Dense(10, activation='softmax'))
  # Take a look at the model summary
  model.compile(loss='categorical_crossentropy',
               optimizer='adam',
               metrics=['accuracy'])
  model.fit(x_train,
           y_train,
           batch_size=64,
           epochs=10)


  # Evaluate the model on test set
  score = model.evaluate(x_test, y_test, verbose=0)
  # Print test accuracy
  print('\n', 'Test accuracy:', score[1])

运行单元格时,出现以下错误:

Error when checking input: expected conv2d_5_input to have 4 dimensions, but got array with shape (60000, 28, 28)

我觉得我缺少了使用卷积层的基础知识,尽管看起来应该可行。我在SO上发现了一些类似的问题,人们建议操纵“ input_shape”参数。我尝试将其更改为(60000,28,28),并且还添加了附加尺寸,其值为1,但到目前为止没有任何效果。谁能指出我可能在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

您似乎跳过了本教程的重塑部分:

# Reshape input data from (28, 28) to (28, 28, 1)
w, h = 28, 28
x_train = x_train.reshape(x_train.shape[0], w, h, 1)
x_valid = x_valid.reshape(x_valid.shape[0], w, h, 1)
x_test = x_test.reshape(x_test.shape[0], w, h, 1)

这里的想法是您的样本为28x28x1(一种颜色,28x28像素),第一维为样本数(在您的情况下为60000)。

相关问题