CNN值错误输入形状,同时用作损耗`categorical_crossentropy`。这种损失期望目标与输出具有相同的形状

时间:2019-12-12 21:44:38

标签: python

hiya一直尝试使用运行python 3.6的9个类别为鲸鱼种类创建图像分类器,这是我的代码

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

1 个答案:

答案 0 :(得分:0)

我将其x=Dense(9, activation='sigmoid')(x)的nvm输出设置为9而不是12