(x_train, y_train), (x_test, y_test) = tf.keras.datasets.fashion_mnist.load_data()x_train = x_train.astype('float32') / 255x_test = x_test.astype('float32') / 255x_train.shape #Shape is (60000, 28, 28)然后模型確保輸入形狀為 28,28,1,因為 60k 是樣本。model2 = tf.keras.Sequential()# Must define the input shape in the first layer of the neural networkmodel2.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) 的數組就像每次我嘗試理解輸入形狀時一樣,我會更加困惑。就像我在這一點上對 conv2d 和密集的輸入形狀感到困惑。無論如何,為什么這是錯誤的?
2 回答

HUX布斯
TA貢獻1876條經驗 獲得超6個贊
是的,這是正確的,參數input_shape
準備取 3 個值。然而,該函數Conv2D
需要一個 4D 數組作為輸入,包括:
樣本數
通道數
圖像寬度
圖像高度
而該函數load_data()
是一個由寬度、高度和樣本數量組成的 3D 數組。
您可以期望通過簡單的重塑來解決該問題:
train_X = train_X.reshape(-1, 28,28, 1) test_X = test_X.reshape(-1, 28,28, 1)
來自 keras 文檔的更好定義:
輸入形狀:4D 張量,形狀:(batch,channels,rows,cols)如果 data_format 是“channels_first”或 4D 張量,形狀:(batch,rows,cols,channels)如果 data_format 是“channels_last”。

慕尼黑8549860
TA貢獻1818條經驗 獲得超11個贊
您缺少通道維度(值為 1),可以通過重塑數組輕松糾正:
x_train = x_train.reshape((-1, 28, 28, 1)) x_test = x_test.reshape((-1, 28, 28, 1))
添加回答
舉報
0/150
提交
取消