Keras输入形状抛出预期为4d的值错误,但得到一个形状为数组(60000,28,28) [英] Keras input shape throws value error expected 4d but got an array with shape (60000, 28,28)
问题描述
(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
x_train.shape #Shape is (60000, 28, 28)
然后该模型确保输入形状为28,28,1,因为60k是样本.
Then the model made sure input shape is 28,28,1 since 60k is the sample.
model2 = tf.keras.Sequential()
# Must define the input shape in the first layer of the neural network
model2.add(tf.keras.layers.Conv2D(filters=64, kernel_size=2, padding='same', activation='relu', input_shape=(28,28,1)))
model2.add(tf.keras.layers.MaxPooling2D(pool_size=2))
model2.add(tf.keras.layers.Dropout(0.3))
model2.add(tf.keras.layers.Conv2D(filters=32, kernel_size=2, padding='same', activation='relu'))
model2.add(tf.keras.layers.MaxPooling2D(pool_size=2))
model2.add(tf.keras.layers.Dropout(0.3))
model2.add(tf.keras.layers.Flatten())
model2.add(tf.keras.layers.Dense(256, activation='relu'))
model2.add(tf.keras.layers.Dropout(0.5))
model2.add(tf.keras.layers.Dense(10, activation='softmax'))
model2.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
model2.fit(x_train,
y_train,
batch_size=64,
epochs=25,)
我得到了错误: ValueError:检查输入时出错:预期conv2d_19_input具有4维,但数组的形状为(60000,28,28)
I get the Error: ValueError: Error when checking input: expected conv2d_19_input to have 4 dimensions, but got array with shape (60000, 28, 28)
就像每次我尝试理解输入形状一样,我都会感到更加困惑.就像im与conv2d的输入形状混淆了,此时稠密. 无论如何,为什么会这样?
Like everytime i try to understand input shape i get more confused. Like im confused with the input shapes for conv2d and dense at this point. Anyway, Why is this wrong?
推荐答案
是的,这是正确的,参数input_shape
准备采用3个值.但是,功能Conv2D
希望将4D数组作为输入,内容包括:
Yes, this is correct the parameter input_shape
is prepared to take 3 values. However the function Conv2D
is expecting a 4D array as input, covering:
- 样本数
- 频道数
- 图像宽度
- 图像高度
函数load_data()
是一个3D数组,由宽度,高度和样本数组成.
Whereas the function load_data()
is a 3D array consisting of width, height and number of samples.
您可以期望通过简单的重塑来解决该问题:
You can expect to solve the issue with a simple reshape:
train_X = train_X.reshape(-1, 28,28, 1)
test_X = test_X.reshape(-1, 28,28, 1)
来自keras文档的更好信息:
A better defitinion from keras documentation:
输入形状: 如果data_format为"channels_first",则形状为(批,行,列,列)的4D张量;如果data_format为"channels_last",则形状为:(批,行,列,列)的4D张量.
Input shape: 4D tensor with shape: (batch, channels, rows, cols) if data_format is "channels_first" or 4D tensor with shape: (batch, rows, cols, channels) if data_format is "channels_last".
这篇关于Keras输入形状抛出预期为4d的值错误,但得到一个形状为数组(60000,28,28)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!