ValueError:检查目标时出错:预期density_2的形状为(10,),但数组的形状为(9,)

时间:2019-07-18 04:18:02

标签: amazon-s3 amazon-ec2 keras deep-learning

在训练此图像分类代码时,我将图像放在10个文件夹(标签)中,并指定最终的密集层以及num_classes设置为10,但是错误消息的确使我感到困惑。

对我来说,keras模型就像一个黑匣子,我一直在尝试将形状打印到每一层之前,但是没有成功。我玩过密集层的参数。

input_size = 224
batch_size = 32
train_generator = image_datagen.flow_from_directory(
    'C:/output/train/',
    class_mode="categorical",
    seed=seed,
    batch_size=batch_size,
    target_size=(input_size, input_size),
    color_mode='grayscale',
    shuffle=True)

valid_generator = image_datagen.flow_from_directory(
    'C:/output/valid/',
    class_mode="categorical",
    seed=seed,
    batch_size=batch_size,
    target_size=(input_size, input_size),
    color_mode='grayscale',
    shuffle=True)

def getStandardModel(input_size):
    seed = 1
    num_classes = 10 
    num_dense_start_nodes = int((input_size*input_size)/(4*4*4)) # 256
    inputs = Input((input_size, input_size, 1))
    print(inputs.shape)
    #inputs = Input((1,input_size,input_size))
    conv1 = Conv2D(32, (3, 3), activation='relu', 
        padding='same',input_shape=(input_size,input_size, 
        1),data_format="channels_last")(inputs)
    conv1 = BatchNormalization()(conv1)
    conv1 = Conv2D(32, (3, 3), activation='relu', padding='same')(conv1)
    pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)
    pool1 = BatchNormalization()(pool1)

    conv2 = Conv2D(64, (3, 3), activation='relu', padding='same')(pool1)
    conv2 = BatchNormalization()(conv2)
    conv2 = Conv2D(64, (3, 3), activation='relu', padding='same')(conv2)
    pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)
    pool2 = BatchNormalization()(pool2)

    conv3 = Conv2D(128, (3, 3), activation='relu', padding='same')(pool2)
    conv3 = BatchNormalization()(conv3)
    conv3 = Conv2D(128, (3, 3), activation='relu', padding='same')(conv3)
    pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)
    pool3 = BatchNormalization()(pool3)

    conv4 = Conv2D(256, (3, 3), activation='relu', padding='same')(pool3)
    conv4 = BatchNormalization()(conv4)
    conv4 = Conv2D(256, (3, 3), activation='relu', padding='same')(conv4)
    conv4 = BatchNormalization()(conv4)
    '''
    pool4 = MaxPooling2D(pool_size=(2, 2))(conv4)

    conv5 = Conv2D(512, (3, 3), activation='relu', padding='same')(pool4)
    conv5 = Conv2D(512, (3, 3), activation='relu', padding='same')(conv5)
    '''
    flatten5 = Flatten()(conv4)
    dense6 = Dense(num_dense_start_nodes, activation="relu")(flatten5)
    dense6 = BatchNormalization()(dense6)
    dense6 = Dropout(0.2)(dense6)
    dense7 = Dense(int(num_dense_start_nodes/2), activation="relu") 
        (dense6)
    dense7 = BatchNormalization()(dense7)
    dense8 = Dense(num_classes, activation="softmax")(dense6)
    print(dense8.shape, inputs.shape)
    model = Model(inputs=[inputs], outputs=[dense8])
    return model

At the end of the first epoch, the error appears

1 个答案:

答案 0 :(得分:0)

数据可能不匹配,因为生成器似乎只发现了9个类而不是10个类,请检查Keras的输出以找出并进行必要的修正。