繁体   English   中英

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

[英]Input to tf.keras Conv2D layer not of appropriate size

我正在按照此处教程中概述的步骤进行操作

我正在尝试在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)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM