预期density_1的形状为(1,),但数组的形状为(2,)

时间:2018-12-07 14:16:34

标签: python-2.7 numpy tensorflow keras

我收到此错误:

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

当我跑步时:

num_classes = 2
model = keras.Sequential()

model.add(keras.layers.InputLayer(input_shape=[64,64,1]))
model.add(keras.layers.Conv2D(filters = 32, kernel_size=5, strides=1, padding ='same', activation='relu'))
model.add(keras.layers.MaxPooling2D(pool_size=5, padding='same'))

model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(512, activation='relu'))
model.add(keras.layers.Dense(num_classes, activation='softmax'))
#model.summary()

#Compile and train the model
model.compile(optimizer=tf.train.AdamOptimizer(0.001),
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(x = tr_img, y = tr_lbl, epochs=2, batch_size = 5)

我的输入(图像)数据存储在numpy数组中,其形状为(300,64,64,1)

我的标签的形状为(300,2),并且采用一种热门格式,例如:[0,1] ...

我该如何解决?

1 个答案:

答案 0 :(得分:0)

问题在于您的损失功能。如果您使用带有一键热编码标签的softmax输出,则应该使用loss='binary_crossentropy'loss='categorical_crossentropy'