CNN值错误输入形状时使用的损失'分类\u交叉熵'。这一损失预计目标的形状将与outpu相同

2024-10-01 13:33:33 发布

您现在位置:Python中文网/ 问答频道 /正文

HiyaBetTryna为鲸鱼做了一个9个分类的图像分类器,我运行的是Python3.6,下面是我的代码

import numpy as np
from tensorflow import keras
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Model
from sklearn.metrics import confusion_matrix
import itertools
import matplotlib.pyplot as plt

train_path=r'C:\Users\Blessie Balais\whales\TRAIN'
valid_path=r'C:\Users\Blessie Balais\whales\VAL'
test_path=r'C:\Users\Blessie Balais\whales\TEST'

class_labels=['BLUE WHALES', 'BOWHEAD WHALES', 'BRYDES WHALES', 'FIN WHALES', 'GRAY WHALES', 'HUMPBACK WHALES', 'MINKE WHALES', 'NORTHERN RIGHT WHALES', 'OMURA WHALES', 'PYGMY RIGHT WHALES', 'SEI WHALES', 'SOUTHERN RIGHT WHALES']

train_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)\
    .flow_from_directory(train_path, target_size=(299,299),classes=class_labels,batch_size=5)
valid_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)\
    .flow_from_directory(valid_path, target_size=(299,299),classes=class_labels,batch_size=5)
test_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)\
    .flow_from_directory(test_path, target_size=(299,299),classes=class_labels,batch_size=5, shuffle=False)

base_model=keras.applications.xception.Xception(include_top=False)

x=base_model.output
x=GlobalAveragePooling2D()(x)
x=Dense(1024, activation='relu')(x)
x=Dense(9, activation='sigmoid')(x)
model=Model(inputs=base_model.input, outputs=x)


base_model.trainable = False

N=30

model.compile(Adam(lr=.0001),loss='categorical_crossentropy', metrics=['accuracy'])
history=model.fit_generator(train_batches, steps_per_epoch=40, validation_data=valid_batches,
validation_steps=90,epochs=N,verbose=1)

print("[INFO]evaluating model...")

test_labels=test_batches.classes
predictions=model.predict_generator(test_batches, steps=28, verbose=1)

我犯了这个错误

Traceback (most recent call last):
  File "C:/Users/Blessie Balais/PycharmProjects/app/classifaying whales.py", line 39, in <module>
    validation_steps=90,epochs=N,verbose=1)
  File "C:\Users\Blessie Balais\Anaconda3\envs\bbssie\lib\site-packages\tensorflow_core\python\keras\engine\training.py", line 1297, in fit_generator
    steps_name='steps_per_epoch')
  File "C:\Users\Blessie Balais\Anaconda3\envs\bbssie\lib\site-packages\tensorflow_core\python\keras\engine\training_generator.py", line 265, in model_iteration
    batch_outs = batch_function(*batch_data)
  File "C:\Users\Blessie Balais\Anaconda3\envs\bbssie\lib\site-packages\tensorflow_core\python\keras\engine\training.py", line 973, in train_on_batch
    class_weight=class_weight, reset_metrics=reset_metrics)
  File "C:\Users\Blessie Balais\Anaconda3\envs\bbssie\lib\site-packages\tensorflow_core\python\keras\engine\training_v2_utils.py", line 253, in train_on_batch
    extract_tensors_from_dataset=True)
  File "C:\Users\Blessie Balais\Anaconda3\envs\bbssie\lib\site-packages\tensorflow_core\python\keras\engine\training.py", line 2538, in _standardize_user_data
    y, self._feed_loss_fns, feed_output_shapes)
  File "C:\Users\Blessie Balais\Anaconda3\envs\bbssie\lib\site-packages\tensorflow_core\python\keras\engine\training_utils.py", line 743, in check_loss_and_target_compatibility
    ' while using as loss ' + loss_name + '. '
ValueError: A target array with shape (5, 12) was passed for an output of shape (None, 9) while using as loss categorical_crossentropy. This loss expects targets to have the same shape as the output.

Process finished with exit code 1

Tags: frompyimportmodeltensorflowbatchlinebatches