python - 使用 Tensorflow 的目标数组形状与预期输出不同

标签 python tensorflow keras

我正在尝试制作 CNN(还是初学者)。尝试拟合模型时出现此错误:

ValueError:形状为 (10000, 10) 的目标数组被传递用于形状输出 (None, 6, 6, 10),同时用作损失 categorical_crossentropy。此损失期望目标与输出具有相同的形状。

标签的形状 = (10000, 10) 图像数据的形状 = (10000, 32, 32, 3)

代码:

import pickle
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import (Dense, Dropout, Activation, Flatten, 
                                     Conv2D, MaxPooling2D)
from tensorflow.keras.callbacks import TensorBoard
from keras.utils import to_categorical
import numpy as np
import time

MODEL_NAME = f"_________{int(time.time())}"
BATCH_SIZE = 64

class ConvolutionalNetwork():
    '''
    A convolutional neural network to be used to classify images
    from the CIFAR-10 dataset.
    '''

    def __init__(self):
        '''
        self.training_images -- a 10000x3072 numpy array of uint8s. Each 
                                a row of the array stores a 32x32 colour image. 
                                The first 1024 entries contain the red channel 
                                values, the next 1024 the green, and the final 
                                1024 the blue. The image is stored in row-major 
                                order, so that the first 32 entries of the array are the red channel values of the first row of the image.
        self.training_labels -- a list of 10000 numbers in the range 0-9. 
                                The number at index I indicates the label 
                                of the ith image in the array data.
        '''
        # List of image categories
        self.label_names = (self.unpickle("cifar-10-batches-py/batches.meta",
                            encoding='utf-8')['label_names'])

        self.training_data = self.unpickle("cifar-10-batches-py/data_batch_1")
        self.training_images = self.training_data[b'data']
        self.training_labels = self.training_data[b'labels']

        # Reshaping the images + scaling 
        self.shape_images()  

        # Converts labels to one-hot
        self.training_labels = np.array(to_categorical(self.training_labels))

        self.create_model()

        self.tensorboard = TensorBoard(log_dir=f'logs/{MODEL_NAME}')

    def unpickle(self, file, encoding='bytes'):
        '''
        Unpickles the dataset files.
        '''
        with open(file, 'rb') as fo:
            training_dict = pickle.load(fo, encoding=encoding)
        return training_dict

    def shape_images(self):
        '''
        Reshapes the images and scales by 255.
        '''
        images = list()
        for d in self.training_images:
            image = np.zeros((32,32,3), dtype=np.uint8)
            image[...,0] = np.reshape(d[:1024], (32,32)) # Red channel
            image[...,1] = np.reshape(d[1024:2048], (32,32)) # Green channel
            image[...,2] = np.reshape(d[2048:], (32,32)) # Blue channel
            images.append(image)

        for i in range(len(images)):
            images[i] = images[i]/255

        images = np.array(images)
        self.training_images = images
        print(self.training_images.shape)

    def create_model(self):
        '''
        Creating the ConvNet model.
        '''
        self.model = Sequential()
        self.model.add(Conv2D(64, (3, 3), input_shape=self.training_images.shape[1:]))
        self.model.add(Activation("relu"))
        self.model.add(MaxPooling2D(pool_size=(2,2)))

        self.model.add(Conv2D(64, (3,3)))
        self.model.add(Activation("relu"))
        self.model.add(MaxPooling2D(pool_size=(2,2)))

        # self.model.add(Flatten())
        # self.model.add(Dense(64))
        # self.model.add(Activation('relu'))

        self.model.add(Dense(10))
        self.model.add(Activation(activation='softmax'))

        self.model.compile(loss="categorical_crossentropy", optimizer="adam", 
                           metrics=['accuracy'])

    def train(self):
        '''
        Fits the model.
        '''
        print(self.training_images.shape)
        print(self.training_labels.shape)
        self.model.fit(self.training_images, self.training_labels, batch_size=BATCH_SIZE, 
                       validation_split=0.1, epochs=5, callbacks=[self.tensorboard])


network = ConvolutionalNetwork()
network.train()

非常感谢您的帮助,已经尝试修复了一个小时。

最佳答案

您需要在创建模型时取消注释 Flatten 层。本质上,这一层所做的是它采用 4D 输入 (batch_size, height, width, num_filters) 并将其展开为 2D 输入 (batch_size, height * width * num_filters)。这是获得所需输出形状所必需的。

关于python - 使用 Tensorflow 的目标数组形状与预期输出不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56912176/

相关文章:

python - 使用 Python 和正则表达式查找字符串中的所有中文文本

python - to_CSV 将 np.array 保存为字符串而不是列表

python selenium selenium.common.exceptions.StaleElementReferenceException 错误

python - 在 pandas 中使用不同类型的 elif 创建数据框列

python - 在 Keras 中实现注意力机制

tensorflow - 如何使用 Dataset API 最大化 tensorflow GPU 训练中的 CPU 利用率?

python - 检查目标时出错 : Converting FC layers to Conv2D

python - 如何防止权重和偏差保存最佳模型参数

python - 如何在 keras 模型中对某些输出进行比其他输出更多的惩罚?

tensorflow - 将 keras 模型另存为 .h5