ValueError: Shapes (None, 1) and (None, 2) are incompatible
老是碰见这种问题,解决方法是:
如果数据集加载了 image_dataset_from_directory
, use label_mode='categorial'
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
path,
label_mode='categorial'
)
或加载flow_from_directory
,flow_from_dataframe
then useclass_mode='categorical'
train_ds = ImageDataGenerator.flow_from_directory(
path,
class_mode='categorical'
)
范畴交叉熵(Categorical Cross entropy):
model = Sequential([
Conv2D(32,3, activation='relu', input_shape=(48,48,1)),
BatchNormalization(),
MaxPooling2D(pool_size=(3, 3)),
Flatten(),
Dense(512, activation='relu'),
Dense(2,activation='softmax') # activation change
])
model.compile(optimizer='adam',
loss='categorical_crossentropy', # Loss
metrics=['accuracy'])
二元交叉熵(Binary Crossentropy)
model = Sequential([
Conv2D(32,3, activation='relu', input_shape=(48,48,1)),
BatchNormalization(),
MaxPooling2D(pool_size=(3, 3)),
Flatten(),
Dense(512, activation='relu'),
Dense(1,activation='sigmoid') #activation change
])
model.compile(optimizer='adam',
loss='binary_crossentropy', # Loss
metrics=['accuracy'])
我的训练时因为加了下面两句话才开始正常训练的
MaxPooling2D(pool_size=(3, 3)),
Flatten(),
训练如下所示: