Keras中to_categorical独热编码输出维度超出实际类别数如何解决
问题修复方案
首先明确问题根因:keras.utils.np_utils.to_categorical 默认会根据输入标签的最大值+1自动生成独热向量的维度,你的标签最大值为9,因此默认生成0~9对应的10维向量,多出了不存在的0、1、2三个类别维度。
下面提供两种可行修复方案:
方案1:标签映射为连续0~N编号(推荐)
这是最通用、不易出错的方案,将离散的原始标签统一映射为从0开始的连续整数,再做独热编码:
import numpy as np from sklearn.preprocessing import LabelEncoder from keras.utils import np_utils # 1. 合并训练集和测试集标签,拟合编码器,保证两边映射规则一致 all_labels = np.concatenate([y_train, y_test]) encoder = LabelEncoder() encoder.fit(all_labels) # 2. 转换标签为0~6的连续整数 y_train_encoded = encoder.transform(y_train) y_test_encoded = encoder.transform(y_test) # 3. 做独热编码,此时维度自动为7 y_train_onehot = np_utils.to_categorical(y_train_encoded) y_test_onehot = np_utils.to_categorical(y_test_encoded)
该方案的优势是无需关心原始标签的取值范围,即使后续标签分布变化也能自动适配,也符合深度学习分类任务的常规标签处理规范。
方案2:对生成的独热向量切片裁剪多余维度
如果需要保留原始标签的对应关系,也可以直接裁剪掉独热向量前3个多余的维度(对应不存在的0、1、2类):
from keras.utils import np_utils # 先做默认的独热编码得到10维向量 y_train_onehot_raw = np_utils.to_categorical(y_train) y_test_onehot_raw = np_utils.to_categorical(y_test) # 裁剪掉前3列,保留第3到第9列共7维 y_train_onehot = y_train_onehot_raw[:, 3:] y_test_onehot = y_test_onehot_raw[:, 3:]
注意:使用该方案需要确认你的原始标签最小值确实为3,且不存在0、1、2的有效标签,避免裁剪掉有用维度
内容的提问来源于stack exchange,提问作者user466534
相关产品推荐
相关产品推荐

