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

简介: 在使用Keras构建的图像分类模型训练过程中,因使用了sparse_categorical_crossentropy损失函数而导致标签形状与模型输出形状不匹配的错误,解决方法是更换损失函数为categorical_crossentropy。

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'])
目录
相关文章
|
1月前
|
机器学习/深度学习 API 算法框架/工具
【Tensorflow+keras】Keras API三种搭建神经网络的方式及以mnist举例实现
使用Keras API构建神经网络的三种方法:使用Sequential模型、使用函数式API以及通过继承Model类来自定义模型,并提供了基于MNIST数据集的示例代码。
38 12
|
1月前
|
机器学习/深度学习 IDE API
【Tensorflow+keras】Keras 用Class类封装的模型如何调试call子函数的模型内部变量
该文章介绍了一种调试Keras中自定义Layer类的call方法的方法,通过直接调用call方法并传递输入参数来进行调试。
21 4
|
1月前
|
TensorFlow 算法框架/工具
【Tensorflow+Keras】用Tensorflow.keras的方法替代keras.layers.merge
在TensorFlow 2.0和Keras中替代旧版keras.layers.merge函数的方法,使用了新的层如add, multiply, concatenate, average, 和 dot来实现常见的层合并操作。
15 1
|
1月前
|
机器学习/深度学习 TensorFlow 算法框架/工具
【Tensorflow+keras】解决cuDNN launch failure : input shape ([32,2,8,8]) [[{{node sequential_1/batch_nor
在使用TensorFlow 2.0和Keras训练生成对抗网络(GAN)时,遇到了“cuDNN launch failure”错误,特别是在调用self.generator.predict方法时出现,输入形状为([32,2,8,8])。此问题可能源于输入数据形状与模型期望的形状不匹配或cuDNN版本不兼容。解决方案包括设置GPU内存增长、检查模型定义和输入数据形状、以及确保TensorFlow和cuDNN版本兼容。
24 1
|
1月前
|
TensorFlow 算法框架/工具
【Tensorflow+Keras】学习率指数、分段、逆时间、多项式衰减及自定义学习率衰减的完整实例
使用Tensorflow和Keras实现学习率衰减的完整实例,包括指数衰减、分段常数衰减、多项式衰减、逆时间衰减以及如何通过callbacks自定义学习率衰减策略。
33 0
|
1月前
|
API 算法框架/工具
【Tensorflow+keras】使用keras API保存模型权重、plot画loss损失函数、保存训练loss值
使用keras API保存模型权重、plot画loss损失函数、保存训练loss值
19 0
|
1月前
|
TensorFlow API 算法框架/工具
【Tensorflow+keras】解决使用model.load_weights时报错 ‘str‘ object has no attribute ‘decode‘
python 3.6,Tensorflow 2.0,在使用Tensorflow 的keras API,加载权重模型时,报错’str’ object has no attribute ‘decode’
31 0
|
1月前
|
机器学习/深度学习 API TensorFlow
【Tensorflow+keras】解决 Fail to find the dnn implementation.
在TensorFlow 2.0环境中使用双向长短期记忆层(Bidirectional LSTM)遇到“Fail to find the dnn implementation”错误时的三种解决方案。
33 0
|
2天前
|
机器学习/深度学习 数据挖掘 TensorFlow
从数据小白到AI专家:Python数据分析与TensorFlow/PyTorch深度学习的蜕变之路
【9月更文挑战第10天】从数据新手成长为AI专家,需先掌握Python基础语法,并学会使用NumPy和Pandas进行数据分析。接着,通过Matplotlib和Seaborn实现数据可视化,最后利用TensorFlow或PyTorch探索深度学习。这一过程涉及从数据清洗、可视化到构建神经网络的多个步骤,每一步都需不断实践与学习。借助Python的强大功能及各类库的支持,你能逐步解锁数据的深层价值。
10 0
|
11天前
|
持续交付 测试技术 jenkins
JSF 邂逅持续集成,紧跟技术热点潮流,开启高效开发之旅,引发开发者强烈情感共鸣
【8月更文挑战第31天】在快速发展的软件开发领域,JavaServer Faces(JSF)这一强大的Java Web应用框架与持续集成(CI)结合,可显著提升开发效率及软件质量。持续集成通过频繁的代码集成及自动化构建测试,实现快速反馈、高质量代码、加强团队协作及简化部署流程。以Jenkins为例,配合Maven或Gradle,可轻松搭建JSF项目的CI环境,通过JUnit和Selenium编写自动化测试,确保每次构建的稳定性和正确性。
36 0

热门文章

最新文章