检查目标时出错:预期softmax_1的形状为(1,),但数组的形状为(2,)',Keras [英] Error when checking target: expected softmax_1 to have shape (1,) but got array with shape (2,)', Keras

查看:107
本文介绍了检查目标时出错:预期softmax_1的形状为(1,),但数组的形状为(2,)',Keras的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次使用Keras构建Conv Net.我的图层如下:

I am using Keras for building Conv Net for the first time. My layers are as follows:

layers = [
Conv2D(8,kernel_size=(4,4),padding='same',input_shape=( 200, 180,3),kernel_initializer="glorot_normal",data_format="channels_first"),
Activation("relu"),
MaxPooling2D(pool_size=(8,8),padding='same',data_format='channels_first'),
Conv2D(16,(2,2),padding='same',kernel_initializer="glorot_normal"),
Activation("relu"),
MaxPooling2D(pool_size=(4,4),padding='same',data_format='channels_first'),
Conv2D(4,(3,3),padding='same',kernel_initializer="glorot_normal"),
Activation("relu"),
MaxPooling2D(pool_size=(2,2),padding='same',data_format='channels_first'),
Flatten(),
Dense(2,input_shape=(48,)),
Softmax(axis=-1)
]
#Edit, here is the part for compiling the model and fitting it
model = Sequential(layers)    

model.compile(optimizer="adam",loss="sparse_categorical_crossentropy" 
metrics=["accuracy"])
trainHistory = model.fit(x=X_train,y=Y_train,batch_size=3,epochs=1000)

我的标签数组的形状为(,2).但是,当我尝试在模型上使用拟合时,它给了我softmax_1期望形状为(1,)的错误.但是我清楚地提到Dense的单位为2,并且softmax返回与输入尺寸相同的输出.

My labels array is of shape (,2). But when I try to use fit on the model, it gives me the error that softmax_1 expected to have shape (1,). But I have clearly mentioned units of Dense as 2 and softmax returns output of the same dimension as the input.

那么1是哪里来的呢?我尝试使用1维的虚拟标签数组,并且它可以运行.那我在做什么错?如何使用已有的二维数组?

So where did the 1, came from? I tried to use dummy label array of 1 dimension and it runs. So what am I doing wrong? How do I use 2 dimensional array that I have?

推荐答案

问题是您正在使用sparse_categorical_crossentropy作为损失函数.当给定标签(即Y_train)被编码为整数(即​​0、1、2,...)时,将使用此损失函数.但是,如果标签是一键编码的(在您的代码中似乎是这种情况),则需要使用categorical_crossentropy作为损失函数.

The problem is that you are using sparse_categorical_crossentropy as the loss function. This loss function is used when the given labels (i.e. Y_train) are encoded as integers (i.e. 0, 1, 2, ...). However, If the labels are one-hot encoded, which seems to be the case in your code, you need to use categorical_crossentropy as the loss function instead.

这篇关于检查目标时出错:预期softmax_1的形状为(1,),但数组的形状为(2,)',Keras的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆