将形状为(32,3)的目标数组传递为形状(None,15,15,3)的输出,同时将其用作损耗`categorical_crossentropy`

时间:2020-06-10 09:10:54

标签: python tensorflow keras deep-learning neural-network

import tensorflow as tf
from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(
        rescale=1./255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True)
training_set = train_datagen.flow_from_directory(
        'animals/training_set',
        target_size=(64, 64),
        batch_size=32,
        class_mode='categorical')

test_datagen = ImageDataGenerator(rescale=1./255)
test_set = test_datagen.flow_from_directory(
        'animals/test_set',
        target_size=(64, 64),
        batch_size=32,
        class_mode='categorical')

cnn = tf.keras.models.Sequential()

cnn.add(tf.keras.layers.Conv2D(filters = 32, kernel_size = 2, activation = 'relu', input_shape = [64, 
64, 3]))

cnn.add(tf.keras.layers.MaxPool2D(pool_size = 2, strides = 2))

cnn.add(tf.keras.layers.Conv2D(filters = 32, kernel_size = 2, activation = 'relu', input_shape = [64, 
64, 3]))
cnn.add(tf.keras.layers.MaxPool2D(pool_size = 2, strides = 2))

cnn.add(tf.keras.layers.Dense(units = 128, activation = 'relu'))

cnn.add(tf.keras.layers.Dense(units = 3, activation = 'softmax'))

cnn.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])

cnn.fit(x = training_set, validatian_data = test_set, epochs = 15)

弹出以下错误消息:

ValueError:传递形状为(32,3)的目标数组以输出形状为(None,15,15,3)的输出,同时用作损失categorical_crossentropy。这种损失会导致目标与输出的形状相同。

2 个答案:

答案 0 :(得分:0)

您必须在最后一个Maxpool2D之后添加一个tf.keras.layers.Flatten层,以便在1D数据上使用Dense层。否则,“密集”层将应用于导致不匹配的2D数据。

答案 1 :(得分:0)

在第二个cnn.add(tf.keras.layers.Conv2D())函数中,您不得传递输入形状。输入形状仅传递给第一层。