MNIST卷积神经网络出现ValueError错误,期望的最小维度为4,但是实际维度为3。接收到的完整形状为[32, 28, 28]。

4

我将以下内容定义为模型定义。

tf.keras.datasets.mnist 
model = keras.models.Sequential([  
    tf.keras.layers.Conv2D(28, (3,3), activation='relu', input_shape=(28, 28, 1)),  
    tf.keras.layers.MaxPooling2D((2, 2)),  
    tf.keras.layers.Conv2D(56, (3,3), activation='relu'),  
    tf.keras.layers.Flatten(),  
    tf.keras.layers.Dense(64, activation='relu'),  
    tf.keras.layers.Dense(10, activation='softmax'),  
])  
model.fit(x_train, y_train, epochs=3)  <----error

当我尝试使用我的数据集运行时,会出现以下错误。

 ValueError: Input 0 of layer sequential_3 is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: [32, 28, 28]
2个回答

9

看到您的错误,我认为您可能没有在训练集中添加通道轴,即 [batch, w, h, channel]。以下是可行的代码:

数据集

import tensorflow as tf 
import numpy as np 
from sklearn.model_selection import train_test_split

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()

x_train = np.expand_dims(x_train, axis=-1) # <--- add channel axis
x_train = x_train.astype('float32') / 255
y_train = tf.keras.utils.to_categorical(y_train, num_classes=10)

print(x_train.shape, y_train.shape)
# (60000, 28, 28, 1) (60000, 10)

训练

model = tf.keras.models.Sequential([  
    tf.keras.layers.Conv2D(28, (3,3), activation='relu', input_shape=(28, 28, 1)),  
    tf.keras.layers.MaxPooling2D((2, 2)),  
    tf.keras.layers.Conv2D(56, (3,3), activation='relu'),  
    tf.keras.layers.Flatten(),  
    tf.keras.layers.Dense(64, activation='relu'),  
    tf.keras.layers.Dense(10, activation='softmax'),  
])  
model.compile(loss='categorical_crossentropy',optimizer='Adam',metrics=['accuracy'])
model.fit(x_train, y_train, epochs=3)

Epoch 1/3
1875/1875 [==============================] - 11s 2ms/step - loss: 0.2803 - accuracy: 0.9160
Epoch 2/3
1875/1875 [==============================] - 4s 2ms/step - loss: 0.0434 - accuracy: 0.9869
Epoch 3/3
1875/1875 [==============================] - 4s 2ms/step - loss: 0.0273 - accuracy: 0.9917

0

另一种解决方法:
x_train,x_test = x_train.reshape(-1,28,28,1),x_test.reshape(-1,28,28,1)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接