keras mnist CNN值错误,预期min_ndim=4,找到ndim=3,收到完整图形:[32、28、28] [副本]

nnsrf1az  于 2022-11-13  发布在  其他
关注(0)|答案(2)|浏览(174)

此问题在此处已有答案

ValueError: Input 0 of layer sequential is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: [8, 28, 28](3个答案)
去年关闭了。
我将模型定义如下。

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]
2vuwiymt

2vuwiymt1#

通过看到你的错误,我认为你可能没有在训练集中添加通道轴,即[ 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)

培训

第一个

4bbkushb

4bbkushb2#

另一种解决方法是:
x_训练,x_测试= x_训练.重新整形(-1,28,28,1),x_测试.重新整形(-1,28,28,1)

相关问题