keras 遇到错误“ValueError:形状(无,5)和(无,4)不兼容”

fivyi3re  于 2022-11-13  发布在  其他
关注(0)|答案(1)|浏览(130)

任何人都可以帮助我这个错误吗?总文件是2204至5类。和1764文件的培训。谢谢先进。
这是我代码:

import matplotlib.pyplot as plt
import numpy as np
import os
import PIL
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.python.keras.layers import Dense, Flatten
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam
import pathlib
data_dir = r"/root/data_Camera"
data_dir = pathlib.Path(data_dir)
rock = list(data_dir.glob('rock/*'))
print(rock[0])
PIL.Image.open(str(rock[0]))
img_height, img_width = 400,2000
batch_size = 32
trains_ds = tf.keras.preprocessing.image_dataset_from_directory(
  data_dir,
  validation_split = 0.2,
  subset = "training",
  seed = 123,
  label_mode = 'categorical',
  image_size = (img_height, img_width),
  batch_size = batch_size)
val_ds = tf.keras.preprocessing.image_dataset_from_directory(
    data_dir,
    validation_split=0.2,
    subset="validation",
    seed=123,
    label_mode = 'categorical',
    image_size=(img_height, img_width),
    batch_size=batch_size)
class_names = trains_ds.class_names
print(class_names)
resnet_model = Sequential()
pretrained_model = tf.keras.applications.ResNet50(include_top=False, 
                                                  input_shape=(400,2000,3),
                                                  pooling='avg', 
                                                  classes = 5, 
                                                  weights = 'imagenet')
for layer in pretrained_model.layers: 
    layer.trainable=False
resnet_model.add(pretrained_model)
resnet_model.add(Flatten())
resnet_model.add(Dense(512, activation='relu'))
resnet_model.add(Dense(4,activation='softmax'))
resnet_model.summary()
resnet_model.compile(optimizer=Adam(learning_rate=0.001),loss='categorical_crossentropy',metrics=['accuracy'])
epochs = 10
history= resnet_model.fit(
    trains_ds,
    validation_data=val_ds,
    epochs=epochs)

而我遇到的错误是:值错误:形状(无,5)和(无,4)是不兼容的,我也添加文件代码到这里。https://github.com/CallaDai/Tensorflow.git你可以检查出来。谢谢!

raogr8fs

raogr8fs1#

我最近遇到了一个类似的问题,使用loss='sparse_categorical_crossentropy而不是使用loss='categorical_crossentropy。出现这个错误是因为'categorical_crossentropy'适用于一个热编码目标,而'sparse_categorical_crossentropy'适用于整数目标。希望它能起作用。upvote如果有帮助的话。

相关问题