【问题标题】:mnist CNN ValueError expected min_ndim=4, found ndim=3. Full shape received: [32, 28, 28] [duplicate]mnist CNN ValueError 预期 min_ndim=4,发现 ndim=3。收到的完整形状:[32、28、28] [重复]
【发布时间】:2021-05-18 22:44:41
【问题描述】:

我定义模型定义如下。

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]

【问题讨论】:

    标签: python tensorflow machine-learning keras tensorflow2.0


    【解决方案1】:

    看到您的错误,我认为您可能没有在训练集中添加批处理轴,即 [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 batch 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
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2020-11-26
        • 2020-11-16
        • 1970-01-01
        • 2021-06-16
        • 1970-01-01
        • 2021-02-14
        • 2020-03-20
        • 1970-01-01
        • 2021-10-08
        相关资源
        最近更新 更多