我一直在使用着名的dogs-vs-cats kaggle数据集,并尝试提出自己的CNN模型。在将数据集配置到分别包含猫和狗图像的两个文件夹中之后,我刚开始使用bin/
方法导入数据集。
这是模型的代码。
image_dataset_from_directory
这是数据集的代码:
from keras.models import Sequential
from keras.layers import Conv2D,MaxPooling2D,\
Dropout,Flatten,Dense,Activation,\
BatchNormalization
model=Sequential()
model.add(Conv2D(32,(3,3),activation='relu',input_shape=(128,128,3)))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(64,(3,3),activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(128,(3,3),activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512,activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Dense(2,activation='sigmoid'))
model.compile(loss = 'binary_crossentropy',
optimizer='adam',metrics=['accuracy'])
运行健身功能训练我的CNN之后。系统显示此错误:
Dataset = tf.keras.preprocessing.image_dataset_from_directory(
TRAIN_DIR,
labels="inferred",
label_mode="binary",
class_names=None,
color_mode="rgb",
batch_size=32,
image_size=(128, 128),
shuffle=True,
seed=None,
validation_split=None,
subset=None,
interpolation="bilinear",
follow_links=False,
)
我该如何解决?
答案 0 :(得分:1)
我终于找到了解决我问题的方法!
我设法通过将损失函数设置为sparse_categorical_crossentropy
而不是binary_crossentropy
来训练模型。然后,我还将最后一层的激活功能更改为softmax
,当我问问题时,该激活功能为sigmoid
。
如果您有兴趣,这里是完整的代码:
from keras.models import Sequential
from keras.layers import Conv2D,MaxPooling2D,\
Dropout,Flatten,Dense,Activation,\
BatchNormalization
model=Sequential()
model.add(Conv2D(32,(3,3),activation='relu',input_shape=(128,128,3)))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(64,(3,3),activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(128,(3,3),activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512,activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Dense(2,activation='softmax'))
model.compile(loss = 'sparse_categorical_crossentropy',
optimizer='adam',metrics=['accuracy'])