开发多分类输出时使用Categorical Crossentropy遇ValueError请求详解
嘿,我来帮你把这个问题掰扯清楚!你现在在做7分类任务(类别A到G),遇到的这个错误核心就是目标标签的格式和你用的损失函数不兼容。
先看你贴的错误提示:
ValueError: You are passing a target array of shape (79, 1) while using as loss categorical_crossentropy . categorical_crossentropy expects targets to be binary matrices (1s and 0s) of shape (samples, classes). If your targets are integer classes, you can convert them to the expected format via: from keras.utils.np_utils import to_categorical y_binary = to_categor...
错误原因拆解
你现在传入的目标数组是形状为(79,1)的整数标签(比如每个样本对应0-6的整数,分别对应A到G),但categorical_crossentropy这个损失函数,要求目标数据必须是独热编码(one-hot encoding)的二进制矩阵——简单说就是每个样本的标签要变成一个长度等于类别数的数组,只有对应类别的位置是1,其余全是0。比如类别A(假设对应整数0)会变成[1,0,0,0,0,0,0],你的79个样本就需要是形状为(79,7)的数组。
两种解决方案,任你选
方案1:把整数标签转成独热编码
直接用Keras提供的工具函数转换,代码如下:
from keras.utils.np_utils import to_categorical # 先把你的(79,1)标签转成一维数组(如果是二维的话) y = y.reshape(-1) # 转换为独热编码,num_classes设为你的类别数7 y_one_hot = to_categorical(y, num_classes=7)
之后训练模型时,用y_one_hot作为目标数据就可以了。
方案2:改用适配整数标签的损失函数
如果你不想折腾格式转换,可以直接把损失函数换成sparse_categorical_crossentropy,它专门支持整数形式的目标标签,不用做任何格式修改。比如模型编译的时候这么写:
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
这样直接用你原来的(79,1)形状标签数组就行,省心不少。
额外注意点
不管用哪种方案,你的模型最后一层的激活函数都应该用softmax,并且输出维度要设置为7(对应你的7个分类类别)哦。
内容的提问来源于stack exchange,提问作者Haraldii

