ValueError:检查目标时出错:预期密集_2的形状为(1,),但数组的形状为(50,)

时间:2019-11-23 13:19:16

标签: python tensorflow keras model conv-neural-network

这是我的cnn模型代码,我在这里使用flow_from_directory(),但我不知道该错误的解决方案。

如果解决方案是,我必须使用“一键编码”将标签转换为一组50个数字,然后输入到神经网络中。你能告诉我如何在我的代码中使用它吗?

l = zip((1,2), (3,4)) 
x, y = zip(*l)

这是我的错误报告:

model = Sequential()
model.add(Conv2D(32,3,3, input_shape = (64,64,3), activation = "sigmoid"))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Flatten())

model.add(Dense(output_dim = 512, activation="sigmoid"))
model.add(Dense(output_dim=50, activation="softmax"))

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

from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator( rescale = 1./255,
                                   shear_range = 0.2,
                                   zoom_range=0.2,
                                   horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale = 1./255)

training_set = train_datagen.flow_from_directory('Datasets/300_train',
                                                 target_size=(64,64),
                                                 batch_size = 32,
                                                 class_mode='categorical')

testing_set = test_datagen.flow_from_directory('Datasets/300_test',
                                               target_size=(64,64),
                                               batch_size = 32,
                                               class_mode='categorical')

from IPython.display import display
from PIL import Image

model.fit_generator(training_set, steps_per_epoch=250,
                    epochs=10,validation_data=testing_set,
                    validation_steps=50)

1 个答案:

答案 0 :(得分:0)

我的问题的解决方案是: 从sparse_categorical_crossentropy更改损失函数 到categorical_crossentropy

您可以找到更多信息:sparse_categorical_crossentropycategorical_crossentropy