Tensorflow+keras解决Exception has occurred: ValueError Shape mismatch: The shape of labels (received(代

Posted Better Bench

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Tensorflow+keras解决Exception has occurred: ValueError Shape mismatch: The shape of labels (received(代相关的知识,希望对你有一定的参考价值。

1 引言

使用网络做分类,训练的时候报错ValueError: Shape mismatch: The shape of labels (received (15,)) should equal the shape of logits except for the last dimension (received (5, 3))

from tensorflow.keras import datasets, layers, models

IMG_WIDTH = 192
IMG_HEIGHT = 192
train_dir = 'train'
validation_dir = 'validation'

from google.colab import drive
drive.mount('/content/drive')

import os
os.chdir("drive/My Drive/colab")

from tensorflow.keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
        train_dir,
        target_size=(IMG_WIDTH, IMG_HEIGHT),
        batch_size=5)

validation_datagen = ImageDataGenerator(rescale=1./255)
validation_generator = validation_datagen.flow_from_directory(
        validation_dir,
        target_size=(IMG_WIDTH, IMG_HEIGHT),
        batch_size=5)

model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu',
                        input_shape=(IMG_WIDTH, IMG_HEIGHT, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
for i in range(2):
  model.add(layers.Conv2D(128, (3, 3), activation='relu'))
  model.add(layers.MaxPooling2D((2, 2)))

model.add(layers.Flatten())
model.add(layers.Dense(3, activation='softmax'))

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

history = model.fit_generator(
      train_generator,
      epochs=10,
      validation_data=validation_generator)

2 解决办法

原因是使用的损失函数,是sparse_categorical_crossentropy,在训练的时候会默认把label拉平,变成一维的,是有区别于categorical_crossentropy的。
要解决该问题就是更换损失函数为categorical_crossentropy或者其他的损失函数

model.compile(optimizer='adam',
              loss='categorical_crossentropy',
              metrics=['accuracy'])

以上是关于Tensorflow+keras解决Exception has occurred: ValueError Shape mismatch: The shape of labels (received(代的主要内容,如果未能解决你的问题,请参考以下文章

Tensorflow+keras解决 Fail to find the dnn implementation.

Tensorflow+keras解决 Fail to find the dnn implementation.

linux安装keras+tensorflow-gpu步骤

(已解决)Tensorflow 联合 | tff.learning.from_keras_model() 具有具有 DenseFeature 层和多个输入的模型

Tensorflow+keras解决使用model.load_weights时报错 ‘str‘ object has no attribute ‘decode‘

Tensorflow+keras解决使用model.load_weights时报错 ‘str‘ object has no attribute ‘decode‘