我有28x28张图片的数据集。数据点数组x
的形状为(10000, 28, 28)
,标签数组y
的形状为(10000,)
。
以下代码:
x = x.reshape(-1, 28, 28, 1)
model = Sequential([
Conv2D(8, kernel_size=(3, 3), padding="same", activation=tf.nn.relu, input_shape=(28, 28, 1)),
Dense(64, activation=tf.nn.relu),
Dense(64, activation=tf.nn.relu),
Dense(10, activation=tf.nn.softmax)
])
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
model.fit(x, y, epochs=5) #error
给予:
ValueError: Error when checking target: expected dense_3 to have 4 dimensions, but got array with shape (10000, 1)
model.summary()
输出:
Layer (type) Output Shape Param #
=================================================================
conv2d_1 (Conv2D) (None, 28, 28, 8) 80
_________________________________________________________________
dense_1 (Dense) (None, 28, 28, 64) 576
_________________________________________________________________
dense_2 (Dense) (None, 28, 28, 64) 4160
_________________________________________________________________
dense_3 (Dense) (None, 28, 28, 10) 650
=================================================================
Total params: 5,466
Trainable params: 5,466
Non-trainable params: 0
_________________________________________________________________
答案 0 :(得分:3)
您忘记添加Flatten()
层(keras.layers.Flatten()
):
model = Sequential([
Conv2D(8, kernel_size=(3, 3), padding="same", activation=tf.nn.relu, input_shape=(28, 28, 1)),
Flatten(),
Dense(64, activation=tf.nn.relu),
Dense(64, activation=tf.nn.relu),
Dense(10, activation=tf.nn.softmax)
])
答案 1 :(得分:1)
您的输出是3维的,而目标是1维的。您可能会在Flatten
层之后缺少Con2D
层,这会将卷积的输出减小到一个维度:
from keras.models import Sequential
from keras.layers import Conv2D, Dense, Flatten
# Fake data
import numpy as np
x = np.ones((10000, 28, 28))
y = np.ones((10000,))
x = x.reshape(-1, 28, 28, 1)
model = Sequential([
Conv2D(8, kernel_size=(3, 3), padding="same", activation="relu", input_shape=(28, 28, 1)),
Flatten(),
Dense(64, activation="relu"),
Dense(64, activation="relu"),
Dense(10, activation="softmax")
])
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
model.summary()
model.fit(x, y, epochs=1)
然后,尺寸正确:
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d_1 (Conv2D) (None, 28, 28, 8) 80
_________________________________________________________________
flatten_1 (Flatten) (None, 6272) 0
_________________________________________________________________
dense_1 (Dense) (None, 64) 401472
_________________________________________________________________
dense_2 (Dense) (None, 64) 4160
_________________________________________________________________
dense_3 (Dense) (None, 10) 650
=================================================================
Total params: 406,362
Trainable params: 406,362
Non-trainable params: 0