Python tf.keras Conv2D层的输入大小不合适

Python tf.keras Conv2D层的输入大小不合适,python,tensorflow,keras,Python,Tensorflow,Keras,我将遵循教程中概述的步骤 我试图在Google Colaboratory笔记本中的单元格中运行教程中的以下代码: 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

我将遵循教程中概述的步骤

我试图在Google Colaboratory笔记本中的单元格中运行教程中的以下代码:

  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的附加维度,但到目前为止没有任何效果。有人能指出我在这里可能遗漏了什么吗?

看起来您跳过了教程中的重塑零件:

# 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)。

奇怪的是,我在我的评论链接中根本看不到这一点。那么,我是否理解了我将input_shape参数设置为描述x_序列的重塑大小的元组?您应该将
input_shape
设置为描述x_序列中一个“训练样本”的元组。在此,您的一个培训样本的大小为28x28x1。我指的代码在这里,在你在问题中链接的博客帖子中有一个链接: