不为别的,只为做一个连自己都羡慕的人

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_directoryflow_from_dataframe then use class_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'])

 参考:https://stackoverflow.com/questions/61742556/valueerror-shapes-none-1-and-none-2-are-incompatible?noredirect=1

 

我的训练时因为加了下面两句话才开始正常训练的

MaxPooling2D(pool_size=(3, 3)),
Flatten(),

 训练如下所示:

 

posted @ 2021-01-08 16:46  升级打怪  阅读(6200)  评论(0编辑  收藏  举报