【问题标题】:tensorflow,keras ValueError: Error when checking target: expected dense_3tensorflow,keras ValueError:检查目标时出错:预期的dense_3
【发布时间】:2021-10-20 20:07:08
【问题描述】:

ValueError: 检查目标时出错:预期dense_3 的形状为(1,),但得到的数组的形状为(10,)

这是调试信息

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-34-b3df2c199ae0> in <module>()
      6                     validation_data=valid_generator,
      7                     validation_steps= valid_generator.samples // BATCH_SIZE,
----> 8                     verbose=1
      9                     )

/Users/interface/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/keras/engine/training.py in fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
   1777         use_multiprocessing=use_multiprocessing,
   1778         shuffle=shuffle,
-> 1779         initial_epoch=initial_epoch)
   1780 
   1781   def evaluate_generator(self,

/Users/interface/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/keras/engine/training_generator.py in fit_generator(model, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
    202 
    203         outs = model.train_on_batch(
--> 204             x, y, sample_weight=sample_weight, class_weight=class_weight)
    205 
    206         if not isinstance(outs, list):

/Users/interface/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/keras/engine/training.py in train_on_batch(self, x, y, sample_weight, class_weight)
   1538     # Validate and standardize user data.
   1539     x, y, sample_weights = self._standardize_user_data(
-> 1540         x, y, sample_weight=sample_weight, class_weight=class_weight)
   1541 
   1542     if context.executing_eagerly():

/Users/interface/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/keras/engine/training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, batch_size, check_steps, steps_name, steps, validation_split)
    915           feed_output_shapes,
    916           check_batch_axis=False,  # Don't enforce the batch size.
--> 917           exception_prefix='target')
    918 
    919       # Generate sample-wise weight values given the `sample_weight` and

/Users/interface/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/keras/engine/training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    189                 'Error when checking ' + exception_prefix + ': expected ' +
    190                 names[i] + ' to have shape ' + str(shape) +
--> 191                 ' but got array with shape ' + str(data_shape))
    192   return data
    193 

ValueError: Error when checking target: expected dense_7 to have shape (1,) but got array with shape (10,)

我在catch异常下面运行代码,但我不知道如何处理,请帮助我,非常感谢!

我参考这篇技术文章做了这个案例。本案例未经修改无法正常运行。

https://debuggercafe.com/image-classification-using-tensorflow-on-custom-dataset/

我的数据集请下载10 Monkey Species Image dataset for fine-grain classification

非常感谢

非常感谢

#!/usr/bin/env python
# coding: utf-8

# In[13]:


import matplotlib.pyplot as plt
import os
import tensorflow as tf
import matplotlib

matplotlib.style.use('ggplot')


# ## Data Generators

# In[14]:


IMAGE_SHAPE = (224, 224)
TRAINING_DATA_DIR = 'input/training/training/'
VALID_DATA_DIR = 'input/validation/validation/'


# In[35]:


datagen = tf.keras.preprocessing.image.ImageDataGenerator(
    rescale=1./255
)

train_generator = datagen.flow_from_directory(
    TRAINING_DATA_DIR,
    shuffle=True,
    target_size=IMAGE_SHAPE,
)

valid_generator = datagen.flow_from_directory(
    VALID_DATA_DIR,
    shuffle=False,
    target_size=IMAGE_SHAPE,
)



def build_model(num_classes):
    model = tf.keras.Sequential([
    tf.keras.layers.Conv2D(filters=8, kernel_size=(3, 3), activation='relu', 
                           input_shape=(224, 224, 3)),
    tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=2),
    tf.keras.layers.Conv2D(filters=16, kernel_size=(3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=2),
    tf.keras.layers.Conv2D(filters=32, kernel_size=(3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(num_classes, activation='softmax')
    ])
    return model


# In[17]:


model = build_model(num_classes=10)


# In[18]:


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


# In[19]:


print(model.summary())


# ## Train the Model

# In[28]:


EPOCHS = 20
BATCH_SIZE = 32
history = model.fit_generator(train_generator,
                    steps_per_epoch=train_generator.samples // BATCH_SIZE,
                    epochs=EPOCHS,
                    validation_data=valid_generator,
                    validation_steps= valid_generator.samples // BATCH_SIZE,
                    verbose=1
                    )

    
train_loss = history.history['loss']
train_acc = history.history['accuracy']
valid_loss = history.history['val_loss']
valid_acc = history.history['val_accuracy']


# In[ ]:


def save_plots(train_acc, valid_acc, train_loss, valid_loss):
    """
    Function to save the loss and accuracy plots to disk.
    """
    # accuracy plots
    plt.figure(figsize=(12, 9))
    plt.plot(
        train_acc, color='green', linestyle='-', 
        label='train accuracy'
    )
    plt.plot(
        valid_acc, color='blue', linestyle='-', 
        label='validataion accuracy'
    )
    plt.xlabel('Epochs')
    plt.ylabel('Accuracy')
    plt.legend()
    plt.savefig('accuracy.png')
    plt.show()
    # loss plots
    plt.figure(figsize=(12, 9))
    plt.plot(
        train_loss, color='orange', linestyle='-', 
        label='train loss'
    )
    plt.plot(
        valid_loss, color='red', linestyle='-', 
        label='validataion loss'
    )
    plt.xlabel('Epochs')
    plt.ylabel('Loss')
    plt.legend()
    plt.savefig('loss.png')
    plt.show()

save_plots(train_acc, valid_acc, train_loss, valid_loss)

非常感谢 非常感谢

【问题讨论】:

    标签: python tensorflow keras


    【解决方案1】:

    请显示型号的代码。确保顶层是表单

    x=Dense(10, activation='softmax')x
    

    那是确保你的顶层有 10 个猴子物种的 10 个神经元,并使用 softmax 激活,因为我假设你正在进行分类

    【讨论】:

    • 非常感谢,先下载这个,kaggle.com/slothkong/10-monkey-species
    • 我的问题已结束,我想要你的电子邮件,或者我的电子邮件是 icodepoem@gmail.com,我向你发送问题
    猜你喜欢
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 2018-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多