我正在尝试在Places2数据集上训练一个网络,并已将所有类别安排在子文件夹中。当训练和验证数据集通过以下方式加载时:
from tensorflow.keras.preprocessing import image_dataset_from_directorytrain_ds = image_dataset_from_directory( "S:/Places2", image_size=(224, 224), batch_size=128,)validation_ds = image_dataset_from_directory( "S:/Places2Val", image_size=(224, 224), batch_size=128,)
控制台报告说所有图像都已在正确数量的类别中找到:
Found 1803460 files belonging to 365 classes.
Found 36501 files belonging to 365 classes.
然而,在尝试训练以下网络时:
它抛出了形状不兼容的错误:ValueError: Shapes (None, 365) and (None, 1) are incompatible
尽管image_dataset_from_directory默认返回推断的标签,并使用整数标签,专门用于与稀疏分类交叉熵一起使用。如果模型具有正确数量的输出,并且数据加载了正确数量的图像类别,那么为什么其中一个输出形状不正确呢?
特别令人困惑的是,当将损失函数更改为categorical_crossentropy
时,错误变成了:ValueError: Shapes (None, 1) and (None, 365) are incompatible
使用以下代码打印第一批次的标签
for images, labels in train_ds.take(1): print(labels)
显示标签格式如预期的那样——即一个长度为128的整数标签张量。这应该与稀疏分类交叉熵兼容。
tf.Tensor([ 17 226 130 186 177 34 342 33 277 284 333 358 245 263 33 72 50 139 298 331 250 241 50 48 264 276 218 236 303 355 3 185 107 329 277 299 10 314 62 141 221 200 9 64 227 288 253 234 77 174 358 69 277 345 361 205 8 197 194 217 114 135 296 305 278 82 355 134 300 129 76 321 167 296 90 299 291 344 29 291 202 333 168 257 354 79 142 77 280 5 261 234 78 90 250 245 302 189 97 194 347 272 54 256 160 55 131 206 284 51 347 163 313 354 263 63 190 150 220 22 102 33 8 35 97 13 16 277], shape=(128,), dtype=int32)
回答:
经过几个小时的苦思冥想,我终于弄明白了!您只需要在model.compile中将metrics=[‘Accuracy’]更改为metrics=[‘accuracy’]。我回顾了几年前构建的一个使用sparse_categorical_crossentropy的老网络,并逐行检查了它。